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 put(Identifier ident, Item item) {
if (item == null || ident == null) {
return;
}
synchronized (range) {
map.put(ident, item);
if (range.contains(ident)) {
range.remove(ident);
}
range.push(ident);
clean();
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "put"
|
"public void put(Identifier ident, Item item) {
if (item == null || ident == null) {
return;
}
<MASK>map.put(ident, item);</MASK>
synchronized (range) {
if (range.contains(ident)) {
range.remove(ident);
}
range.push(ident);
clean();
}
}"
|
Inversion-Mutation
|
megadiff
|
"@Override
public void appModeChanged() {
setCursor(new Cursor(Cursor.WAIT_CURSOR));
if (currentMode != null) {
saveLayout(FILEPATH_LAYOUT + "." + currentMode.name());
saveConfig(FILEPATH_MAP + "." + currentMode.name());
}
final CidsAppBackend.Mode mode = CidsAppBackend.getInstance().getMode();
if (mode.equals(mode.ALLGEMEIN)) {
setupLayoutInfo();
} else if (mode.equals(mode.ESW)) {
setupLayoutWDSR();
} else if (mode.equals(mode.REGEN)) {
setupLayoutRegen();
}
currentMode = mode;
refreshClipboardButtons();
refreshClipboardButtonsToolTipText();
refreshItemButtons();
final ModeLayer ml = de.cismet.cismap.commons.ModeLayerRegistry.getInstance()
.getModeLayer("verdisAppModeLayer");
if (ml != null) {
ml.forceMode(mode.toString());
}
setupMap(currentMode);
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "appModeChanged"
|
"@Override
public void appModeChanged() {
setCursor(new Cursor(Cursor.WAIT_CURSOR));
if (currentMode != null) {
saveLayout(FILEPATH_LAYOUT + "." + currentMode.name());
saveConfig(FILEPATH_MAP + "." + currentMode.name());
}
final CidsAppBackend.Mode mode = CidsAppBackend.getInstance().getMode();
if (mode.equals(mode.ALLGEMEIN)) {
setupLayoutInfo();
} else if (mode.equals(mode.ESW)) {
setupLayoutWDSR();
} else if (mode.equals(mode.REGEN)) {
setupLayoutRegen();
}
currentMode = mode;
<MASK>setupMap(currentMode);</MASK>
refreshClipboardButtons();
refreshClipboardButtonsToolTipText();
refreshItemButtons();
final ModeLayer ml = de.cismet.cismap.commons.ModeLayerRegistry.getInstance()
.getModeLayer("verdisAppModeLayer");
if (ml != null) {
ml.forceMode(mode.toString());
}
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}"
|
Inversion-Mutation
|
megadiff
|
"public static void main(String[] args)
{
IPAddress ip = new IPAddress();
String myIP = ip.getIPaddress();
String yourIP = "192.168.1.51"; //myIP; //should be whatever the other user's IP is, ultimately
String me = "david"; //will come from the user starting up the application, ultimately
String sender_server = "sender_server@";
String tmp_dst = "shifa@"; //should come from node logic that knows other players
/* Build a node for the local player */
try {
client = new OtpSelf(me, "test"); //this should be the username of the local player
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
initServers(myIP, sender_server);
OtpPeer dst = new OtpPeer(tmp_dst.concat(yourIP));
OtpErlangAtom type = new OtpErlangAtom("test"); //just for proof of concept; will need to be defined based on which logic is being used
sendMsg(client, type, dst, myIP, yourIP); //send a message
}"
|
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)
{
IPAddress ip = new IPAddress();
String myIP = ip.getIPaddress();
String yourIP = "192.168.1.51"; //myIP; //should be whatever the other user's IP is, ultimately
<MASK>String sender_server = "sender_server@";</MASK>
String me = "david"; //will come from the user starting up the application, ultimately
String tmp_dst = "shifa@"; //should come from node logic that knows other players
/* Build a node for the local player */
try {
client = new OtpSelf(me, "test"); //this should be the username of the local player
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
initServers(myIP, sender_server);
OtpPeer dst = new OtpPeer(tmp_dst.concat(yourIP));
OtpErlangAtom type = new OtpErlangAtom("test"); //just for proof of concept; will need to be defined based on which logic is being used
sendMsg(client, type, dst, myIP, yourIP); //send a message
}"
|
Inversion-Mutation
|
megadiff
|
"public HttpUrlConnectionCall(HttpClientHelper helper, String method,
String requestUri, boolean hasEntity) throws IOException {
super(helper, method, requestUri);
if (requestUri.startsWith("http")) {
URL url = new URL(requestUri);
this.connection = (HttpURLConnection) url.openConnection();
int majorVersionNumber = Factory.getMajorJavaVersion();
int minorVersionNumber = Factory.getMinorJavaVersion();
if ((majorVersionNumber > 1)
|| (majorVersionNumber == 1 && minorVersionNumber >= 5)) {
this.connection.setConnectTimeout(getHelper()
.getConnectTimeout());
this.connection.setReadTimeout(getHelper().getReadTimeout());
}
this.connection.setAllowUserInteraction(getHelper()
.isAllowUserInteraction());
this.connection.setDoOutput(hasEntity);
this.connection.setInstanceFollowRedirects(getHelper()
.isFollowRedirects());
this.connection.setUseCaches(getHelper().isUseCaches());
this.responseHeadersAdded = false;
setConfidential(this.connection instanceof HttpsURLConnection);
} else {
throw new IllegalArgumentException(
"Only HTTP or HTTPS resource URIs are allowed here");
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "HttpUrlConnectionCall"
|
"public HttpUrlConnectionCall(HttpClientHelper helper, String method,
String requestUri, boolean hasEntity) throws IOException {
super(helper, method, requestUri);
if (requestUri.startsWith("http")) {
URL url = new URL(requestUri);
this.connection = (HttpURLConnection) url.openConnection();
int majorVersionNumber = Factory.getMajorJavaVersion();
int minorVersionNumber = Factory.getMinorJavaVersion();
if ((majorVersionNumber > 1)
|| (majorVersionNumber == 1 && minorVersionNumber >= 5)) {
this.connection.setConnectTimeout(getHelper()
.getConnectTimeout());
}
<MASK>this.connection.setReadTimeout(getHelper().getReadTimeout());</MASK>
this.connection.setAllowUserInteraction(getHelper()
.isAllowUserInteraction());
this.connection.setDoOutput(hasEntity);
this.connection.setInstanceFollowRedirects(getHelper()
.isFollowRedirects());
this.connection.setUseCaches(getHelper().isUseCaches());
this.responseHeadersAdded = false;
setConfidential(this.connection instanceof HttpsURLConnection);
} else {
throw new IllegalArgumentException(
"Only HTTP or HTTPS resource URIs are allowed here");
}
}"
|
Inversion-Mutation
|
megadiff
|
"public void draw(Canvas canvas) {
try {
canvas.drawRGB(255, 255, 255);
canvas.drawBitmap(renderView.bolo.getBitmap(), 10, 310, null);
for(Mosca it:renderView.moscas) {
if(it.getY() < 450)
it.move();
else {
System.out.format("valor %d\n", it.getStatus());
if(it.getStatus() == SkinType.VOANDO_D)
it.setStatus(SkinType.POUSADA_D);
else
it.setStatus(SkinType.POUSADA_E);
}
canvas.drawBitmap(it.getBitmap(), it.getX(), it.getY(), null);
}
/****
for(BigMosca it:renderView.big_moscas) {
if(it.getY() < 430)
it.move();
else {
System.out.format("valor %d\n", it.getStatus());
if(it.getStatus() == SkinType.VOANDO_D)
it.setStatus(SkinType.POUSADA_D);
else
it.setStatus(SkinType.POUSADA_E);
}
canvas.drawBitmap(it.getBitmap(), it.getX(), it.getY(), null);
// if(it.getStatus() == SkinType.MORRENDO) renderView.moscas.remove(it);
}
for(MoscaAgulha it:renderView.moscas_agulha) {
if(it.getY() < 430)
it.move();
else {
System.out.format("valor %d\n", it.getStatus());
if(it.getStatus() == SkinType.VOANDO_D)
it.setStatus(SkinType.POUSADA_D);
else
it.setStatus(SkinType.POUSADA_E);
}
canvas.drawBitmap(it.getBitmap(), it.getX(), it.getY(), null);
// if(it.getStatus() == SkinType.MORRENDO) renderView.moscas.remove(it);
}
for(MoscaOndular it:renderView.moscas_ondular) {
if(it.getY() < 430)
it.move();
else {
System.out.format("valor %d\n", it.getStatus());
if(it.getStatus() == SkinType.VOANDO_D)
it.setStatus(SkinType.POUSADA_D);
else
it.setStatus(SkinType.POUSADA_E);
}
canvas.drawBitmap(it.getBitmap(), it.getX(), it.getY(), null);
// if(it.getStatus() == SkinType.MORRENDO) renderView.moscas.remove(it);
}
***/
for(final Mosca it:renderView.moscas) {
if(it.getStatus() == SkinType.MORRENDO) {
handler.post( new Runnable() {
public void run() {
renderView.moscas.remove(it);
infoBar.increment(10);
}
});
break;
}
}
if(renderView.moscas.size() < 6) {
// for(int i = 0; i < 6; i++) {
int i = new Random().nextInt(10);;
final Mosca m = new Mosca(this.renderView.getContext());
if((i % 3) == 0) m.setStatus(SkinType.VOANDO_D);
else m.setStatus(SkinType.VOANDO_E);
handler.post( new Runnable() {
public void run() {
renderView.moscas.add(m);
}
});
// }
}
infoBar.draw(canvas);
}
catch(Exception e) {
Log.d("Bzzz", "Nao consegui mover a mosca");
}
// Log.d("Bzzz", new String("Elapsed time " + Long.toString(System.currentTimeMillis() - start_elapsed_time)));
long res = Math.abs(System.currentTimeMillis() - start_elapsed_time);
// Log.d("Bzzz", new String("Elapsed time " + Long.toString(res)));
if(res < 30000)
try { Thread.sleep(ELAPSED_TIME + (30000 - res)/1000); } catch(Exception e) { }
else
try { Thread.sleep(ELAPSED_TIME); } catch (Exception e) { }
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "draw"
|
"public void draw(Canvas canvas) {
<MASK>canvas.drawRGB(255, 255, 255);</MASK>
try {
canvas.drawBitmap(renderView.bolo.getBitmap(), 10, 310, null);
for(Mosca it:renderView.moscas) {
if(it.getY() < 450)
it.move();
else {
System.out.format("valor %d\n", it.getStatus());
if(it.getStatus() == SkinType.VOANDO_D)
it.setStatus(SkinType.POUSADA_D);
else
it.setStatus(SkinType.POUSADA_E);
}
canvas.drawBitmap(it.getBitmap(), it.getX(), it.getY(), null);
}
/****
for(BigMosca it:renderView.big_moscas) {
if(it.getY() < 430)
it.move();
else {
System.out.format("valor %d\n", it.getStatus());
if(it.getStatus() == SkinType.VOANDO_D)
it.setStatus(SkinType.POUSADA_D);
else
it.setStatus(SkinType.POUSADA_E);
}
canvas.drawBitmap(it.getBitmap(), it.getX(), it.getY(), null);
// if(it.getStatus() == SkinType.MORRENDO) renderView.moscas.remove(it);
}
for(MoscaAgulha it:renderView.moscas_agulha) {
if(it.getY() < 430)
it.move();
else {
System.out.format("valor %d\n", it.getStatus());
if(it.getStatus() == SkinType.VOANDO_D)
it.setStatus(SkinType.POUSADA_D);
else
it.setStatus(SkinType.POUSADA_E);
}
canvas.drawBitmap(it.getBitmap(), it.getX(), it.getY(), null);
// if(it.getStatus() == SkinType.MORRENDO) renderView.moscas.remove(it);
}
for(MoscaOndular it:renderView.moscas_ondular) {
if(it.getY() < 430)
it.move();
else {
System.out.format("valor %d\n", it.getStatus());
if(it.getStatus() == SkinType.VOANDO_D)
it.setStatus(SkinType.POUSADA_D);
else
it.setStatus(SkinType.POUSADA_E);
}
canvas.drawBitmap(it.getBitmap(), it.getX(), it.getY(), null);
// if(it.getStatus() == SkinType.MORRENDO) renderView.moscas.remove(it);
}
***/
for(final Mosca it:renderView.moscas) {
if(it.getStatus() == SkinType.MORRENDO) {
handler.post( new Runnable() {
public void run() {
renderView.moscas.remove(it);
infoBar.increment(10);
}
});
break;
}
}
if(renderView.moscas.size() < 6) {
// for(int i = 0; i < 6; i++) {
int i = new Random().nextInt(10);;
final Mosca m = new Mosca(this.renderView.getContext());
if((i % 3) == 0) m.setStatus(SkinType.VOANDO_D);
else m.setStatus(SkinType.VOANDO_E);
handler.post( new Runnable() {
public void run() {
renderView.moscas.add(m);
}
});
// }
}
infoBar.draw(canvas);
}
catch(Exception e) {
Log.d("Bzzz", "Nao consegui mover a mosca");
}
// Log.d("Bzzz", new String("Elapsed time " + Long.toString(System.currentTimeMillis() - start_elapsed_time)));
long res = Math.abs(System.currentTimeMillis() - start_elapsed_time);
// Log.d("Bzzz", new String("Elapsed time " + Long.toString(res)));
if(res < 30000)
try { Thread.sleep(ELAPSED_TIME + (30000 - res)/1000); } catch(Exception e) { }
else
try { Thread.sleep(ELAPSED_TIME); } catch (Exception e) { }
}"
|
Inversion-Mutation
|
megadiff
|
"public void doPlot(NEFEnsemble ensemble) {
XYSeriesCollection dataset = new XYSeriesCollection();
synchronized(ensemble){
float[][] encoders = ensemble.getEncoders();
NEFNode[] nodes = (NEFNode[]) ensemble.getNodes();
float[] x = new float[101];
for (int i = 0; i < x.length; i++) {
x[i] = -1f + (float) i * (2f / (float) (x.length-1));
}
SimulationMode mode = ensemble.getMode();
ensemble.setMode(SimulationMode.CONSTANT_RATE);
float[][] rates = new float[nodes.length][];
for (int i = 0; i < nodes.length; i++) {
//radius of encoded space in direction of this encoder
float radius = MU.pnorm(MU.prodElementwise(encoders[i], ensemble.getRadii()), 2);
XYSeries series = new XYSeries("Neuron " + i);
rates[i] = new float[x.length];
for (int j = 0; j < x.length; j++) {
float radialInput = (ensemble.getDimension() == 1) ? x[j]*encoders[i][0] : x[j];
// float radialInput = getRadialInput(ensemble, i, x[j]);
((NEFNode) nodes[i]).setRadialInput(radialInput);
try {
Noise noise=null;
if (nodes[i] instanceof SpikingNeuron) {
noise=((SpikingNeuron)nodes[i]).getNoise();
((SpikingNeuron)nodes[i]).setNoise(null);
}
nodes[i].run(0f, 0f);
RealOutput output = (RealOutput) nodes[i].getOrigin(Neuron.AXON).getValues();
series.add(x[j]*radius, output.getValues()[0]);
rates[i][j] = output.getValues()[0];
nodes[i].reset(false);
if (noise!=null) {
((SpikingNeuron)nodes[i]).setNoise(noise);
}
} catch (SimulationException e) {
throw new RuntimeException("Can't plot activities: error running neurons", e);
} catch (ClassCastException e) {
throw new RuntimeException("Can't plot activities: neurons producing spike output", e);
} catch (StructuralException e) {
throw new RuntimeException("Can't plot activities: error running neurons", e);
}
}
dataset.addSeries(series);
}
// MatlabExporter exporter = new MatlabExporter();
// exporter.add("x", new float[][]{x});
// exporter.add("rates", rates);
// try {
// exporter.write(new File("activities.mat"));
// } catch (IOException e) {
// e.printStackTrace();
// }
ensemble.setMode(mode);
}
JFreeChart chart = ChartFactory.createXYLineChart(
"Activities",
"X",
"Firing Rate (spikes/s)",
dataset,
PlotOrientation.VERTICAL,
false, false, false
);
showChart(chart, "Activities Plot");
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doPlot"
|
"public void doPlot(NEFEnsemble ensemble) {
XYSeriesCollection dataset = new XYSeriesCollection();
synchronized(ensemble){
float[][] encoders = ensemble.getEncoders();
NEFNode[] nodes = (NEFNode[]) ensemble.getNodes();
float[] x = new float[101];
for (int i = 0; i < x.length; i++) {
x[i] = -1f + (float) i * (2f / (float) (x.length-1));
}
SimulationMode mode = ensemble.getMode();
ensemble.setMode(SimulationMode.CONSTANT_RATE);
float[][] rates = new float[nodes.length][];
for (int i = 0; i < nodes.length; i++) {
//radius of encoded space in direction of this encoder
float radius = MU.pnorm(MU.prodElementwise(encoders[i], ensemble.getRadii()), 2);
XYSeries series = new XYSeries("Neuron " + i);
rates[i] = new float[x.length];
for (int j = 0; j < x.length; j++) {
float radialInput = (ensemble.getDimension() == 1) ? x[j]*encoders[i][0] : x[j];
// float radialInput = getRadialInput(ensemble, i, x[j]);
((NEFNode) nodes[i]).setRadialInput(radialInput);
try {
Noise noise=null;
if (nodes[i] instanceof SpikingNeuron) {
noise=((SpikingNeuron)nodes[i]).getNoise();
((SpikingNeuron)nodes[i]).setNoise(null);
}
<MASK>nodes[i].reset(false);</MASK>
nodes[i].run(0f, 0f);
RealOutput output = (RealOutput) nodes[i].getOrigin(Neuron.AXON).getValues();
series.add(x[j]*radius, output.getValues()[0]);
rates[i][j] = output.getValues()[0];
if (noise!=null) {
((SpikingNeuron)nodes[i]).setNoise(noise);
}
} catch (SimulationException e) {
throw new RuntimeException("Can't plot activities: error running neurons", e);
} catch (ClassCastException e) {
throw new RuntimeException("Can't plot activities: neurons producing spike output", e);
} catch (StructuralException e) {
throw new RuntimeException("Can't plot activities: error running neurons", e);
}
}
dataset.addSeries(series);
}
// MatlabExporter exporter = new MatlabExporter();
// exporter.add("x", new float[][]{x});
// exporter.add("rates", rates);
// try {
// exporter.write(new File("activities.mat"));
// } catch (IOException e) {
// e.printStackTrace();
// }
ensemble.setMode(mode);
}
JFreeChart chart = ChartFactory.createXYLineChart(
"Activities",
"X",
"Firing Rate (spikes/s)",
dataset,
PlotOrientation.VERTICAL,
false, false, false
);
showChart(chart, "Activities Plot");
}"
|
Inversion-Mutation
|
megadiff
|
"public void hidePlaceholder() {
if (super.getText().equals(this.getPlaceholderText())) {
super.setText("");
}
super.removeStyleName(this.getPlaceholderStyleName());
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "hidePlaceholder"
|
"public void hidePlaceholder() {
if (super.getText().equals(this.getPlaceholderText())) {
super.setText("");
<MASK>super.removeStyleName(this.getPlaceholderStyleName());</MASK>
}
}"
|
Inversion-Mutation
|
megadiff
|
"public void execute(final StepExecution stepExecution) throws UnexpectedJobExecutionException,
JobInterruptedException {
ExitStatus status = ExitStatus.FAILED;
final ExceptionHolder fatalException = new ExceptionHolder();
try {
stepExecution.setStartTime(new Date(System.currentTimeMillis()));
// We need to save the step execution right away, before we start
// using its ID. It would be better to make the creation atomic in
// the caller.
fatalException.setException(updateStatus(stepExecution, BatchStatus.STARTED));
// Execute step level listeners *after* the execution context is
// fixed in the step. E.g. ItemStream instances need the the same
// reference to the ExecutionContext as the step execution.
listener.beforeStep(stepExecution);
stream.open(stepExecution.getExecutionContext());
itemHandler.mark();
status = stepOperations.iterate(new RepeatCallback() {
public ExitStatus doInIteration(final RepeatContext context) throws Exception {
final StepContribution contribution = stepExecution.createStepContribution();
// Before starting a new transaction, check for
// interruption.
if (stepExecution.isTerminateOnly()) {
context.setTerminateOnly();
}
interruptionPolicy.checkInterrupted(stepExecution);
ExitStatus result = ExitStatus.CONTINUABLE;
TransactionStatus transaction = transactionManager
.getTransaction(new DefaultTransactionDefinition());
try {
result = processChunk(stepExecution, contribution);
contribution.incrementCommitCount();
// If the step operations are asynchronous then we need
// to synchronize changes to the step execution (at a
// minimum).
try {
synchronizer.lock(stepExecution);
}
catch (InterruptedException e) {
stepExecution.setStatus(BatchStatus.STOPPED);
Thread.currentThread().interrupt();
}
// Apply the contribution to the step
// only if chunk was successful
stepExecution.apply(contribution);
// Attempt to flush before the step execution and stream
// state are updated
itemHandler.flush();
stream.update(stepExecution.getExecutionContext());
try {
jobRepository.saveOrUpdateExecutionContext(stepExecution);
}
catch (Exception e) {
fatalException.setException(e);
stepExecution.setStatus(BatchStatus.UNKNOWN);
throw new CommitFailedException(
"Fatal error detected during save of step execution context", e);
}
try {
itemHandler.mark();
transactionManager.commit(transaction);
}
catch (Exception e) {
fatalException.setException(e);
stepExecution.setStatus(BatchStatus.UNKNOWN);
throw new CommitFailedException("Fatal error detected during commit", e);
}
}
catch (Error e) {
stepExecution.incrementSkipCountBy(contribution.getContributionSkipCount());
processRollback(stepExecution, fatalException, transaction);
throw e;
}
catch (Exception e) {
stepExecution.incrementSkipCountBy(contribution.getContributionSkipCount());
processRollback(stepExecution, fatalException, transaction);
throw e;
}
finally {
synchronizer.release(stepExecution);
}
// Check for interruption after transaction as well, so that
// the interrupted exception is correctly propagated up to
// caller
interruptionPolicy.checkInterrupted(stepExecution);
return result;
}
});
fatalException.setException(updateStatus(stepExecution, BatchStatus.COMPLETED));
}
catch (CommitFailedException e) {
logger.error("Fatal error detected during commit.");
throw e;
}
catch (RuntimeException e) {
status = processFailure(stepExecution, fatalException, e);
if (e.getCause() instanceof JobInterruptedException) {
updateStatus(stepExecution, BatchStatus.STOPPED);
throw (JobInterruptedException) e.getCause();
}
throw e;
}
catch (Error e) {
status = processFailure(stepExecution, fatalException, e);
throw e;
}
finally {
try {
status = status.and(listener.afterStep(stepExecution));
}
catch (RuntimeException e) {
logger.error("Unexpected error in listener after step.", e);
}
stepExecution.setExitStatus(status);
stepExecution.setEndTime(new Date(System.currentTimeMillis()));
try {
jobRepository.saveOrUpdate(stepExecution);
}
catch (RuntimeException e) {
String msg = "Fatal error detected during final save of meta data";
logger.error(msg, e);
if (!fatalException.hasException()) {
fatalException.setException(e);
}
throw new UnexpectedJobExecutionException(msg, fatalException.getException());
}
try {
stream.close(stepExecution.getExecutionContext());
}
catch (RuntimeException e) {
String msg = "Fatal error detected during close of streams. "
+ "The job execution completed (possibly unsuccessfully but with consistent meta-data).";
logger.error(msg, e);
if (!fatalException.hasException()) {
fatalException.setException(e);
}
throw new UnexpectedJobExecutionException(msg, fatalException.getException());
}
if (fatalException.hasException()) {
throw new UnexpectedJobExecutionException("Encountered an error saving batch meta data.",
fatalException.getException());
}
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "execute"
|
"public void execute(final StepExecution stepExecution) throws UnexpectedJobExecutionException,
JobInterruptedException {
ExitStatus status = ExitStatus.FAILED;
final ExceptionHolder fatalException = new ExceptionHolder();
try {
stepExecution.setStartTime(new Date(System.currentTimeMillis()));
// We need to save the step execution right away, before we start
// using its ID. It would be better to make the creation atomic in
// the caller.
fatalException.setException(updateStatus(stepExecution, BatchStatus.STARTED));
// Execute step level listeners *after* the execution context is
// fixed in the step. E.g. ItemStream instances need the the same
// reference to the ExecutionContext as the step execution.
listener.beforeStep(stepExecution);
stream.open(stepExecution.getExecutionContext());
status = stepOperations.iterate(new RepeatCallback() {
public ExitStatus doInIteration(final RepeatContext context) throws Exception {
final StepContribution contribution = stepExecution.createStepContribution();
// Before starting a new transaction, check for
// interruption.
if (stepExecution.isTerminateOnly()) {
context.setTerminateOnly();
}
interruptionPolicy.checkInterrupted(stepExecution);
ExitStatus result = ExitStatus.CONTINUABLE;
TransactionStatus transaction = transactionManager
.getTransaction(new DefaultTransactionDefinition());
try {
<MASK>itemHandler.mark();</MASK>
result = processChunk(stepExecution, contribution);
contribution.incrementCommitCount();
// If the step operations are asynchronous then we need
// to synchronize changes to the step execution (at a
// minimum).
try {
synchronizer.lock(stepExecution);
}
catch (InterruptedException e) {
stepExecution.setStatus(BatchStatus.STOPPED);
Thread.currentThread().interrupt();
}
// Apply the contribution to the step
// only if chunk was successful
stepExecution.apply(contribution);
// Attempt to flush before the step execution and stream
// state are updated
itemHandler.flush();
stream.update(stepExecution.getExecutionContext());
try {
jobRepository.saveOrUpdateExecutionContext(stepExecution);
}
catch (Exception e) {
fatalException.setException(e);
stepExecution.setStatus(BatchStatus.UNKNOWN);
throw new CommitFailedException(
"Fatal error detected during save of step execution context", e);
}
try {
<MASK>itemHandler.mark();</MASK>
transactionManager.commit(transaction);
}
catch (Exception e) {
fatalException.setException(e);
stepExecution.setStatus(BatchStatus.UNKNOWN);
throw new CommitFailedException("Fatal error detected during commit", e);
}
}
catch (Error e) {
stepExecution.incrementSkipCountBy(contribution.getContributionSkipCount());
processRollback(stepExecution, fatalException, transaction);
throw e;
}
catch (Exception e) {
stepExecution.incrementSkipCountBy(contribution.getContributionSkipCount());
processRollback(stepExecution, fatalException, transaction);
throw e;
}
finally {
synchronizer.release(stepExecution);
}
// Check for interruption after transaction as well, so that
// the interrupted exception is correctly propagated up to
// caller
interruptionPolicy.checkInterrupted(stepExecution);
return result;
}
});
fatalException.setException(updateStatus(stepExecution, BatchStatus.COMPLETED));
}
catch (CommitFailedException e) {
logger.error("Fatal error detected during commit.");
throw e;
}
catch (RuntimeException e) {
status = processFailure(stepExecution, fatalException, e);
if (e.getCause() instanceof JobInterruptedException) {
updateStatus(stepExecution, BatchStatus.STOPPED);
throw (JobInterruptedException) e.getCause();
}
throw e;
}
catch (Error e) {
status = processFailure(stepExecution, fatalException, e);
throw e;
}
finally {
try {
status = status.and(listener.afterStep(stepExecution));
}
catch (RuntimeException e) {
logger.error("Unexpected error in listener after step.", e);
}
stepExecution.setExitStatus(status);
stepExecution.setEndTime(new Date(System.currentTimeMillis()));
try {
jobRepository.saveOrUpdate(stepExecution);
}
catch (RuntimeException e) {
String msg = "Fatal error detected during final save of meta data";
logger.error(msg, e);
if (!fatalException.hasException()) {
fatalException.setException(e);
}
throw new UnexpectedJobExecutionException(msg, fatalException.getException());
}
try {
stream.close(stepExecution.getExecutionContext());
}
catch (RuntimeException e) {
String msg = "Fatal error detected during close of streams. "
+ "The job execution completed (possibly unsuccessfully but with consistent meta-data).";
logger.error(msg, e);
if (!fatalException.hasException()) {
fatalException.setException(e);
}
throw new UnexpectedJobExecutionException(msg, fatalException.getException());
}
if (fatalException.hasException()) {
throw new UnexpectedJobExecutionException("Encountered an error saving batch meta data.",
fatalException.getException());
}
}
}"
|
Inversion-Mutation
|
megadiff
|
"public StartupPageTemplateHolder getTemplate() throws IOException {
readContent();
template.reset();
applyBranding();
addThemeDefinitions();
template.replace( StartupPageTemplateHolder.VAR_LIBRARIES, getJsLibraries() );
template.replace( StartupPageTemplateHolder.VAR_APPSCRIPT, getAppScript() );
return template;
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getTemplate"
|
"public StartupPageTemplateHolder getTemplate() throws IOException {
readContent();
applyBranding();
addThemeDefinitions();
<MASK>template.reset();</MASK>
template.replace( StartupPageTemplateHolder.VAR_LIBRARIES, getJsLibraries() );
template.replace( StartupPageTemplateHolder.VAR_APPSCRIPT, getAppScript() );
return template;
}"
|
Inversion-Mutation
|
megadiff
|
"@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException, DataAccessException {
log.debug("loading username: " + s);
CfUser user = null;
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("select u from CfUser u where u.name = :username " +
"and u.metadata.state = :state");
query.setString("username", s);
query.setInteger("state", CfMetaState.ACTIVE.ordinal());
user = (CfUser) query.uniqueResult();
if (user == null)
throw new UsernameNotFoundException("No such user");
log.debug(user.getUsername() + " " + user.getPassword());
return new CfUserDetails(user, loadGrantedAuthoritiesFor(user));
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "loadUserByUsername"
|
"@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException, DataAccessException {
log.debug("loading username: " + s);
CfUser user = null;
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("select u from CfUser u where u.name = :username " +
"and u.metadata.state = :state");
query.setString("username", s);
query.setInteger("state", CfMetaState.ACTIVE.ordinal());
user = (CfUser) query.uniqueResult();
<MASK>log.debug(user.getUsername() + " " + user.getPassword());</MASK>
if (user == null)
throw new UsernameNotFoundException("No such user");
return new CfUserDetails(user, loadGrantedAuthoritiesFor(user));
}"
|
Inversion-Mutation
|
megadiff
|
"private Diff(ArgList argList) throws IOException {
this(
JenaConnect.parseConfig(argList.get("m"), argList.getValueMap("M")),
JenaConnect.parseConfig(argList.get("s"), argList.getValueMap("S")),
JenaConnect.parseConfig(argList.get("o"), argList.getValueMap("O")),
argList.get("d")
);
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "Diff"
|
"private Diff(ArgList argList) throws IOException {
this(
<MASK>JenaConnect.parseConfig(argList.get("s"), argList.getValueMap("S")),</MASK>
JenaConnect.parseConfig(argList.get("m"), argList.getValueMap("M")),
JenaConnect.parseConfig(argList.get("o"), argList.getValueMap("O")),
argList.get("d")
);
}"
|
Inversion-Mutation
|
megadiff
|
"private int readMessages(ClientSession session, ClientConsumer consumer, SimpleString queue) throws MessagingException
{
session.start();
int msgs = 0;
ClientMessage msg = null;
do
{
msg = consumer.receive(1000);
if (msg != null)
{
msg.processed();
if (++msgs % 10000 == 0)
{
System.out.println("received " + msgs);
session.commit();
}
}
}
while (msg != null);
session.commit();
return msgs;
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "readMessages"
|
"private int readMessages(ClientSession session, ClientConsumer consumer, SimpleString queue) throws MessagingException
{
session.start();
int msgs = 0;
ClientMessage msg = null;
do
{
msg = consumer.receive(1000);
<MASK>msg.processed();</MASK>
if (msg != null)
{
if (++msgs % 10000 == 0)
{
System.out.println("received " + msgs);
session.commit();
}
}
}
while (msg != null);
session.commit();
return msgs;
}"
|
Inversion-Mutation
|
megadiff
|
"@Before
public void setUp() {
try {
testObjects = (HashMap<String, Object>) context.getBean("cancelOrder");
ShoppingCartCustomerEntity customer = (ShoppingCartCustomerEntity) testObjects.get("customer");
List<ShoppingCartCustomerAddressEntity> addresses = (List<ShoppingCartCustomerAddressEntity>) testObjects.get("customerAddresses");
String shippingMethod = testObjects.get("shippingMethod").toString();
ShoppingCartPaymentMethodEntity paymentMethod = (ShoppingCartPaymentMethodEntity) testObjects.get("paymentMethod");
List<HashMap<String, Object>> products = (List<HashMap<String, Object>>) testObjects.get("products");
List<ShoppingCartProductEntity> shoppingCartProducts = new ArrayList<ShoppingCartProductEntity>();
List<Integer> productIds = new ArrayList<Integer>();
for (HashMap<String, Object> product : products) {
// Get the product data
String productType = (String) product.get("type");
int productSet = (Integer) product.get("set");
String productSKU = (String) product.get("sku");
CatalogProductCreateEntity attributes = (CatalogProductCreateEntity) product.get("attributesRef");
// Create the product and get the product ID
int productId = createProduct(productType, productSet, productSKU, attributes);
// Get the quantity to place in the shopping cart
double qtyToPurchase = (Double) product.get("qtyToPurchase");
// Create the shopping cart product entity
ShoppingCartProductEntity shoppingCartProduct = new ShoppingCartProductEntity();
shoppingCartProduct.setProduct_id(productId + "");
shoppingCartProduct.setQty(qtyToPurchase);
shoppingCartProducts.add(shoppingCartProduct);
productIds.add(productId);
}
testObjects.put("productIds", productIds);
String orderId = createShoppingCartOrder(customer, addresses, paymentMethod, shippingMethod, shoppingCartProducts);
testObjects.put("orderId", orderId);
}
catch (Exception e) {
e.printStackTrace();
fail();
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setUp"
|
"@Before
public void setUp() {
try {
testObjects = (HashMap<String, Object>) context.getBean("cancelOrder");
ShoppingCartCustomerEntity customer = (ShoppingCartCustomerEntity) testObjects.get("customer");
List<ShoppingCartCustomerAddressEntity> addresses = (List<ShoppingCartCustomerAddressEntity>) testObjects.get("customerAddresses");
String shippingMethod = testObjects.get("shippingMethod").toString();
ShoppingCartPaymentMethodEntity paymentMethod = (ShoppingCartPaymentMethodEntity) testObjects.get("paymentMethod");
List<HashMap<String, Object>> products = (List<HashMap<String, Object>>) testObjects.get("products");
List<ShoppingCartProductEntity> shoppingCartProducts = new ArrayList<ShoppingCartProductEntity>();
List<Integer> productIds = new ArrayList<Integer>();
for (HashMap<String, Object> product : products) {
// Get the product data
String productType = (String) product.get("type");
int productSet = (Integer) product.get("set");
String productSKU = (String) product.get("sku");
CatalogProductCreateEntity attributes = (CatalogProductCreateEntity) product.get("attributesRef");
// Create the product and get the product ID
int productId = createProduct(productType, productSet, productSKU, attributes);
// Get the quantity to place in the shopping cart
double qtyToPurchase = (Double) product.get("qtyToPurchase");
// Create the shopping cart product entity
ShoppingCartProductEntity shoppingCartProduct = new ShoppingCartProductEntity();
shoppingCartProduct.setProduct_id(productId + "");
shoppingCartProduct.setQty(qtyToPurchase);
shoppingCartProducts.add(shoppingCartProduct);
productIds.add(productId);
}
String orderId = createShoppingCartOrder(customer, addresses, paymentMethod, shippingMethod, shoppingCartProducts);
<MASK>testObjects.put("productIds", productIds);</MASK>
testObjects.put("orderId", orderId);
}
catch (Exception e) {
e.printStackTrace();
fail();
}
}"
|
Inversion-Mutation
|
megadiff
|
"@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
HttpRequest request = (HttpRequest) e.getMessage();
RandomAccessFile raf = null;
boolean found = true;
File file = null;
for (String p : paths) {
String path = p + sanitizeUri(request.getUri());
if (path.endsWith("/") || path.endsWith(File.separator)) {
path += "index.html";
}
if (path == null) {
found = false;
continue;
}
file = new File(path);
if (file.isHidden() || !file.exists()) {
found = false;
continue;
}
if (!file.isFile()) {
found = false;
continue;
}
try {
raf = new RandomAccessFile(file, "r");
found = true;
break;
} catch (FileNotFoundException fnfe) {
found = false;
continue;
}
}
if (!found) {
sendError(ctx, NOT_FOUND, e);
return;
}
request.addHeader(SERVICED, "true");
// Cache Validation
String ifModifiedSince = request.getHeader(IF_MODIFIED_SINCE);
if (file != null && ifModifiedSince != null && ifModifiedSince.length() != 0) {
SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);
// Only compare up to the second because the datetime format we send to the client does
// not have milliseconds
long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
long fileLastModifiedSeconds = file.lastModified() / 1000;
if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
sendNotModified(ctx);
return;
}
}
long fileLength = raf.length();
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
contentType(request, response, file);
setContentLength(response, fileLength);
setDateAndCacheHeaders(response,file);
Channel ch = e.getChannel();
// Write the initial line and the header.
ch.write(response);
// Write the content.
ChannelFuture writeFuture;
if (ch.getPipeline().get(SslHandler.class) != null) {
// Cannot use zero-copy with HTTPS.
writeFuture = ch.write(new ChunkedFile(raf, 0, fileLength, 8192));
} else {
// No encryption - use zero-copy.
final FileRegion region =
new DefaultFileRegion(raf.getChannel(), 0, fileLength);
writeFuture = ch.write(region);
writeFuture.addListener(new ChannelFutureProgressListener() {
public void operationComplete(ChannelFuture future) {
region.releaseExternalResources();
}
public void operationProgressed(
ChannelFuture future, long amount, long current, long total) {
}
});
}
// Decide whether to close the connection or not.
if (!isKeepAlive(request)) {
// Close the connection when the whole content is written out.
writeFuture.addListener(ChannelFutureListener.CLOSE);
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "messageReceived"
|
"@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
HttpRequest request = (HttpRequest) e.getMessage();
RandomAccessFile raf = null;
boolean found = true;
File file = null;
for (String p : paths) {
String path = p + sanitizeUri(request.getUri());
if (path.endsWith("/") || path.endsWith(File.separator)) {
path += "index.html";
}
if (path == null) {
found = false;
continue;
}
file = new File(path);
if (file.isHidden() || !file.exists()) {
found = false;
continue;
}
if (!file.isFile()) {
found = false;
continue;
}
try {
raf = new RandomAccessFile(file, "r");
found = true;
break;
} catch (FileNotFoundException fnfe) {
found = false;
continue;
}
}
if (!found) {
sendError(ctx, NOT_FOUND, e);
return;
}
// Cache Validation
String ifModifiedSince = request.getHeader(IF_MODIFIED_SINCE);
if (file != null && ifModifiedSince != null && ifModifiedSince.length() != 0) {
SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);
// Only compare up to the second because the datetime format we send to the client does
// not have milliseconds
long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
long fileLastModifiedSeconds = file.lastModified() / 1000;
if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
sendNotModified(ctx);
return;
}
}
long fileLength = raf.length();
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
contentType(request, response, file);
setContentLength(response, fileLength);
setDateAndCacheHeaders(response,file);
Channel ch = e.getChannel();
// Write the initial line and the header.
ch.write(response);
// Write the content.
ChannelFuture writeFuture;
if (ch.getPipeline().get(SslHandler.class) != null) {
// Cannot use zero-copy with HTTPS.
writeFuture = ch.write(new ChunkedFile(raf, 0, fileLength, 8192));
} else {
// No encryption - use zero-copy.
final FileRegion region =
new DefaultFileRegion(raf.getChannel(), 0, fileLength);
writeFuture = ch.write(region);
writeFuture.addListener(new ChannelFutureProgressListener() {
public void operationComplete(ChannelFuture future) {
region.releaseExternalResources();
}
public void operationProgressed(
ChannelFuture future, long amount, long current, long total) {
}
});
}
// Decide whether to close the connection or not.
if (!isKeepAlive(request)) {
// Close the connection when the whole content is written out.
writeFuture.addListener(ChannelFutureListener.CLOSE);
}
<MASK>request.addHeader(SERVICED, "true");</MASK>
}"
|
Inversion-Mutation
|
megadiff
|
"public frmConfiguration() {
aloader = Main.getInstance().emuConfig;
initComponents();
this.setLocationRelativeTo(null);
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "frmConfiguration"
|
"public frmConfiguration() {
<MASK>initComponents();</MASK>
aloader = Main.getInstance().emuConfig;
this.setLocationRelativeTo(null);
}"
|
Inversion-Mutation
|
megadiff
|
"@Override
protected void onCreate(Bundle savedInstanceState)
{
Components.onCreateActivity(this, 0);
super.onCreate(savedInstanceState);
// Drug drug = (Drug) getIntent().getSerializableExtra(Extras.DRUG);
mDrug = Drug.get(getIntent().getIntExtra(Extras.DRUG_ID, 0));
setTitle(mDrug.getName());
updateLogFragment();
// setListAdapter(new DoseHistoryAdapter(this, mDrug));
}"
|
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)
{
<MASK>super.onCreate(savedInstanceState);</MASK>
Components.onCreateActivity(this, 0);
// Drug drug = (Drug) getIntent().getSerializableExtra(Extras.DRUG);
mDrug = Drug.get(getIntent().getIntExtra(Extras.DRUG_ID, 0));
setTitle(mDrug.getName());
updateLogFragment();
// setListAdapter(new DoseHistoryAdapter(this, mDrug));
}"
|
Inversion-Mutation
|
megadiff
|
"public void initializeCompiler()
{
if (!initialized)
{
URL[] urls = ClasspathUrlFinder.findClassPaths();
ModuleUtils.initializeScannerURLs(urls);
ClassScanner.initialize(urls);
initializeProcessors();
for (CruxPreProcessor preprocess : this.preProcessors)
{
preprocess.initialize(urls);
}
for (CruxPostProcessor postprocess : this.postProcessors)
{
postprocess.initialize(urls);
}
this.initialized = true;
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "initializeCompiler"
|
"public void initializeCompiler()
{
if (!initialized)
{
URL[] urls = ClasspathUrlFinder.findClassPaths();
ModuleUtils.initializeScannerURLs(urls);
ClassScanner.initialize(urls);
for (CruxPreProcessor preprocess : this.preProcessors)
{
preprocess.initialize(urls);
}
for (CruxPostProcessor postprocess : this.postProcessors)
{
postprocess.initialize(urls);
}
<MASK>initializeProcessors();</MASK>
this.initialized = true;
}
}"
|
Inversion-Mutation
|
megadiff
|
"void validatePrediction(MatrixFactorizationModel model, int users, int products, int features,
DoubleMatrix trueRatings, double matchThreshold, boolean implicitPrefs, DoubleMatrix truePrefs) {
DoubleMatrix predictedU = new DoubleMatrix(users, features);
List<scala.Tuple2<Object, double[]>> userFeatures = model.userFeatures().toJavaRDD().collect();
for (int i = 0; i < features; ++i) {
for (scala.Tuple2<Object, double[]> userFeature : userFeatures) {
predictedU.put((Integer)userFeature._1(), i, userFeature._2()[i]);
}
}
DoubleMatrix predictedP = new DoubleMatrix(products, features);
List<scala.Tuple2<Object, double[]>> productFeatures =
model.productFeatures().toJavaRDD().collect();
for (int i = 0; i < features; ++i) {
for (scala.Tuple2<Object, double[]> productFeature : productFeatures) {
predictedP.put((Integer)productFeature._1(), i, productFeature._2()[i]);
}
}
DoubleMatrix predictedRatings = predictedU.mmul(predictedP.transpose());
if (!implicitPrefs) {
for (int u = 0; u < users; ++u) {
for (int p = 0; p < products; ++p) {
double prediction = predictedRatings.get(u, p);
double correct = trueRatings.get(u, p);
Assert.assertTrue(String.format("Prediction=%2.4f not below match threshold of %2.2f",
prediction, matchThreshold), Math.abs(prediction - correct) < matchThreshold);
}
}
} else {
// For implicit prefs we use the confidence-weighted RMSE to test (ref Mahout's implicit ALS tests)
double sqErr = 0.0;
double denom = 0.0;
for (int u = 0; u < users; ++u) {
for (int p = 0; p < products; ++p) {
double prediction = predictedRatings.get(u, p);
double truePref = truePrefs.get(u, p);
double confidence = 1.0 + /* alpha = */ 1.0 * trueRatings.get(u, p);
double err = confidence * (truePref - prediction) * (truePref - prediction);
sqErr += err;
denom += 1.0;
}
}
double rmse = Math.sqrt(sqErr / denom);
Assert.assertTrue(String.format("Confidence-weighted RMSE=%2.4f above threshold of %2.2f",
rmse, matchThreshold), Math.abs(rmse) < matchThreshold);
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "validatePrediction"
|
"void validatePrediction(MatrixFactorizationModel model, int users, int products, int features,
DoubleMatrix trueRatings, double matchThreshold, boolean implicitPrefs, DoubleMatrix truePrefs) {
DoubleMatrix predictedU = new DoubleMatrix(users, features);
List<scala.Tuple2<Object, double[]>> userFeatures = model.userFeatures().toJavaRDD().collect();
for (int i = 0; i < features; ++i) {
for (scala.Tuple2<Object, double[]> userFeature : userFeatures) {
predictedU.put((Integer)userFeature._1(), i, userFeature._2()[i]);
<MASK>}</MASK>
<MASK>}</MASK>
DoubleMatrix predictedP = new DoubleMatrix(products, features);
List<scala.Tuple2<Object, double[]>> productFeatures =
model.productFeatures().toJavaRDD().collect();
for (int i = 0; i < features; ++i) {
for (scala.Tuple2<Object, double[]> productFeature : productFeatures) {
predictedP.put((Integer)productFeature._1(), i, productFeature._2()[i]);
<MASK>}</MASK>
<MASK>}</MASK>
DoubleMatrix predictedRatings = predictedU.mmul(predictedP.transpose());
if (!implicitPrefs) {
for (int u = 0; u < users; ++u) {
for (int p = 0; p < products; ++p) {
double prediction = predictedRatings.get(u, p);
double correct = trueRatings.get(u, p);
Assert.assertTrue(String.format("Prediction=%2.4f not below match threshold of %2.2f",
prediction, matchThreshold), Math.abs(prediction - correct) < matchThreshold);
<MASK>}</MASK>
<MASK>}</MASK>
<MASK>}</MASK> else {
// For implicit prefs we use the confidence-weighted RMSE to test (ref Mahout's implicit ALS tests)
double sqErr = 0.0;
double denom = 0.0;
for (int u = 0; u < users; ++u) {
for (int p = 0; p < products; ++p) {
double prediction = predictedRatings.get(u, p);
double truePref = truePrefs.get(u, p);
double confidence = 1.0 + /* alpha = */ 1.0 * trueRatings.get(u, p);
double err = confidence * (truePref - prediction) * (truePref - prediction);
sqErr += err;
denom += 1.0;
<MASK>}</MASK>
<MASK>}</MASK>
double rmse = Math.sqrt(sqErr / denom);
Assert.assertTrue(String.format("Confidence-weighted RMSE=%2.4f above threshold of %2.2f",
rmse, matchThreshold), Math.abs(rmse) < matchThreshold);
<MASK>}</MASK>
<MASK>}</MASK>"
|
Inversion-Mutation
|
megadiff
|
"protected void createContext(AppSettings settings) throws LWJGLException{
DisplayMode displayMode = null;
if (settings.getWidth() <= 0 || settings.getHeight() <= 0){
displayMode = Display.getDesktopDisplayMode();
settings.setResolution(displayMode.getWidth(), displayMode.getHeight());
}else if (settings.isFullscreen()){
displayMode = getFullscreenDisplayMode(settings.getWidth(), settings.getHeight(),
settings.getBitsPerPixel(), settings.getFrequency());
if (displayMode == null)
throw new RuntimeException("Unable to find fullscreen display mode matching settings");
}else{
displayMode = new DisplayMode(settings.getWidth(), settings.getHeight());
}
PixelFormat pf = new PixelFormat(settings.getBitsPerPixel(),
0,
settings.getDepthBits(),
settings.getStencilBits(),
settings.getSamples());
frameRate = settings.getFrameRate();
logger.log(Level.INFO, "Selected display mode: {0}", displayMode);
boolean pixelFormatChanged = false;
if (created.get() && (pixelFormat.getBitsPerPixel() != pf.getBitsPerPixel()
||pixelFormat.getDepthBits() != pf.getDepthBits()
||pixelFormat.getStencilBits() != pf.getStencilBits()
||pixelFormat.getSamples() != pf.getSamples())){
renderer.resetGLObjects();
Display.destroy();
pixelFormatChanged = true;
}
pixelFormat = pf;
Display.setTitle(settings.getTitle());
if (displayMode != null)
Display.setDisplayMode(displayMode);
if (settings.getIcons() != null)
Display.setIcon(imagesToByteBuffers(settings.getIcons()));
Display.setFullscreen(settings.isFullscreen());
Display.setVSyncEnabled(settings.isVSync());
if (!created.get() || pixelFormatChanged){
ContextAttribs attr = createContextAttribs();
if (attr != null){
Display.create(pixelFormat, attr);
}else{
Display.create(pixelFormat);
}
renderable.set(true);
if (pixelFormatChanged && pixelFormat.getSamples() > 1
&& GLContext.getCapabilities().GL_ARB_multisample){
GL11.glEnable(ARBMultisample.GL_MULTISAMPLE_ARB);
}
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createContext"
|
"protected void createContext(AppSettings settings) throws LWJGLException{
DisplayMode displayMode = null;
if (settings.getWidth() <= 0 || settings.getHeight() <= 0){
displayMode = Display.getDesktopDisplayMode();
settings.setResolution(displayMode.getWidth(), displayMode.getHeight());
}else if (settings.isFullscreen()){
displayMode = getFullscreenDisplayMode(settings.getWidth(), settings.getHeight(),
settings.getBitsPerPixel(), settings.getFrequency());
if (displayMode == null)
throw new RuntimeException("Unable to find fullscreen display mode matching settings");
}else{
displayMode = new DisplayMode(settings.getWidth(), settings.getHeight());
}
PixelFormat pf = new PixelFormat(settings.getBitsPerPixel(),
0,
settings.getDepthBits(),
settings.getStencilBits(),
settings.getSamples());
frameRate = settings.getFrameRate();
logger.log(Level.INFO, "Selected display mode: {0}", displayMode);
boolean pixelFormatChanged = false;
if (created.get() && (pixelFormat.getBitsPerPixel() != pf.getBitsPerPixel()
||pixelFormat.getDepthBits() != pf.getDepthBits()
||pixelFormat.getStencilBits() != pf.getStencilBits()
||pixelFormat.getSamples() != pf.getSamples())){
<MASK>Display.destroy();</MASK>
renderer.resetGLObjects();
pixelFormatChanged = true;
}
pixelFormat = pf;
Display.setTitle(settings.getTitle());
if (displayMode != null)
Display.setDisplayMode(displayMode);
if (settings.getIcons() != null)
Display.setIcon(imagesToByteBuffers(settings.getIcons()));
Display.setFullscreen(settings.isFullscreen());
Display.setVSyncEnabled(settings.isVSync());
if (!created.get() || pixelFormatChanged){
ContextAttribs attr = createContextAttribs();
if (attr != null){
Display.create(pixelFormat, attr);
}else{
Display.create(pixelFormat);
}
renderable.set(true);
if (pixelFormatChanged && pixelFormat.getSamples() > 1
&& GLContext.getCapabilities().GL_ARB_multisample){
GL11.glEnable(ARBMultisample.GL_MULTISAMPLE_ARB);
}
}
}"
|
Inversion-Mutation
|
megadiff
|
"public static List<String> getMatchingURIs(Resource current, String namespace, List<Property> properties, JenaConnect vivo) {
StringBuilder sbQuery = new StringBuilder();
ArrayList<String> filters = new ArrayList<String>();
int valueCount = 0;
sbQuery.append("SELECT ?uri\nWHERE\n{");
for(Property p : properties) {
for(Statement s : IterableAdaptor.adapt(current.listProperties(p))) {
sbQuery.append("\t?uri <");
sbQuery.append(p.getURI());
sbQuery.append("> ");
if(s.getObject().isResource()) {
sbQuery.append("<");
sbQuery.append(s.getObject().asResource().getURI());
sbQuery.append(">");
} else {
filters.add("( str(?value"+valueCount+") = \""+s.getObject().asLiteral().getValue().toString()+"\" )");
sbQuery.append("?value");
sbQuery.append(valueCount);
valueCount++;
}
sbQuery.append(" .\n");
}
}
// sbQuery.append("regex( ?uri , \"");
// sbQuery.append(namespace);
// sbQuery.append("\" )");
if(!filters.isEmpty()) {
sbQuery.append("\tFILTER (");
// sbQuery.append(" && ");
sbQuery.append(StringUtils.join(" && ", filters));
}
sbQuery.append(")\n}");
ArrayList<String> retVal = new ArrayList<String>();
int count = 0;
log.debug("Query:\n"+sbQuery.toString());
log.debug("namespace: "+namespace);
for(QuerySolution qs : IterableAdaptor.adapt(vivo.executeQuery(sbQuery.toString()))) {
Resource res = qs.getResource("uri");
if(res.getNameSpace().equals(namespace)) {
String uri = res.getURI();
retVal.add(uri);
log.debug("Matched URI["+count+"]: <"+uri+">");
count++;
}
}
return retVal;
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getMatchingURIs"
|
"public static List<String> getMatchingURIs(Resource current, String namespace, List<Property> properties, JenaConnect vivo) {
StringBuilder sbQuery = new StringBuilder();
ArrayList<String> filters = new ArrayList<String>();
int valueCount = 0;
sbQuery.append("SELECT ?uri\nWHERE\n{");
for(Property p : properties) {
for(Statement s : IterableAdaptor.adapt(current.listProperties(p))) {
sbQuery.append("\t?uri <");
sbQuery.append(p.getURI());
sbQuery.append("> ");
if(s.getObject().isResource()) {
sbQuery.append("<");
sbQuery.append(s.getObject().asResource().getURI());
sbQuery.append(">");
} else {
filters.add("( str(?value"+valueCount+") = \""+s.getObject().asLiteral().getValue().toString()+"\" )");
sbQuery.append("?value");
sbQuery.append(valueCount);
valueCount++;
}
sbQuery.append(" .\n");
}
}
<MASK>sbQuery.append("\tFILTER (");</MASK>
// sbQuery.append("regex( ?uri , \"");
// sbQuery.append(namespace);
// sbQuery.append("\" )");
if(!filters.isEmpty()) {
// sbQuery.append(" && ");
sbQuery.append(StringUtils.join(" && ", filters));
}
sbQuery.append(")\n}");
ArrayList<String> retVal = new ArrayList<String>();
int count = 0;
log.debug("Query:\n"+sbQuery.toString());
log.debug("namespace: "+namespace);
for(QuerySolution qs : IterableAdaptor.adapt(vivo.executeQuery(sbQuery.toString()))) {
Resource res = qs.getResource("uri");
if(res.getNameSpace().equals(namespace)) {
String uri = res.getURI();
retVal.add(uri);
log.debug("Matched URI["+count+"]: <"+uri+">");
count++;
}
}
return retVal;
}"
|
Inversion-Mutation
|
megadiff
|
"private void initSuggest() {
String locale = mSubtypeSwitcher.getInputLocaleStr();
Locale savedLocale = mSubtypeSwitcher.changeSystemLocale(new Locale(locale));
if (mSuggest != null) {
mSuggest.close();
}
final SharedPreferences prefs = mPrefs;
mQuickFixes = isQuickFixesEnabled(prefs);
final Resources res = mResources;
int mainDicResId = Utils.getMainDictionaryResourceId(res);
mSuggest = new Suggest(this, mainDicResId);
loadAndSetAutoCorrectionThreshold(prefs);
updateAutoTextEnabled();
mUserDictionary = new UserDictionary(this, locale);
mSuggest.setUserDictionary(mUserDictionary);
mContactsDictionary = new ContactsDictionary(this, Suggest.DIC_CONTACTS);
mSuggest.setContactsDictionary(mContactsDictionary);
mAutoDictionary = new AutoDictionary(this, this, locale, Suggest.DIC_AUTO);
mSuggest.setAutoDictionary(mAutoDictionary);
mUserBigramDictionary = new UserBigramDictionary(this, this, locale, Suggest.DIC_USER);
mSuggest.setUserBigramDictionary(mUserBigramDictionary);
updateCorrectionMode();
mWordSeparators = res.getString(R.string.word_separators);
mSentenceSeparators = res.getString(R.string.sentence_separators);
mSubtypeSwitcher.changeSystemLocale(savedLocale);
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "initSuggest"
|
"private void initSuggest() {
<MASK>updateAutoTextEnabled();</MASK>
String locale = mSubtypeSwitcher.getInputLocaleStr();
Locale savedLocale = mSubtypeSwitcher.changeSystemLocale(new Locale(locale));
if (mSuggest != null) {
mSuggest.close();
}
final SharedPreferences prefs = mPrefs;
mQuickFixes = isQuickFixesEnabled(prefs);
final Resources res = mResources;
int mainDicResId = Utils.getMainDictionaryResourceId(res);
mSuggest = new Suggest(this, mainDicResId);
loadAndSetAutoCorrectionThreshold(prefs);
mUserDictionary = new UserDictionary(this, locale);
mSuggest.setUserDictionary(mUserDictionary);
mContactsDictionary = new ContactsDictionary(this, Suggest.DIC_CONTACTS);
mSuggest.setContactsDictionary(mContactsDictionary);
mAutoDictionary = new AutoDictionary(this, this, locale, Suggest.DIC_AUTO);
mSuggest.setAutoDictionary(mAutoDictionary);
mUserBigramDictionary = new UserBigramDictionary(this, this, locale, Suggest.DIC_USER);
mSuggest.setUserBigramDictionary(mUserBigramDictionary);
updateCorrectionMode();
mWordSeparators = res.getString(R.string.word_separators);
mSentenceSeparators = res.getString(R.string.sentence_separators);
mSubtypeSwitcher.changeSystemLocale(savedLocale);
}"
|
Inversion-Mutation
|
megadiff
|
"public void onEnable(){
getServer().getPluginManager().registerEvent(Type.PLAYER_CHAT, new ChatListen(this), Priority.Normal, this);
setupSQL();
if (!setupPermissions()) return;
if (!checkRedeemType()) return;
send("is now enabled, version: "+this.getDescription().getVersion());
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onEnable"
|
"public void onEnable(){
getServer().getPluginManager().registerEvent(Type.PLAYER_CHAT, new ChatListen(this), Priority.Normal, this);
if (!setupPermissions()) return;
if (!checkRedeemType()) return;
<MASK>setupSQL();</MASK>
send("is now enabled, version: "+this.getDescription().getVersion());
}"
|
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
|
"@Override
public MRSEncounter createEncounter(MRSEncounter mrsEncounter) {
Encounter existingOpenMrsEncounter = findDuplicateOpenMrsEncounter(mrsEncounter);
if (existingOpenMrsEncounter == null) {
return openmrsToMrsEncounter(encounterService.saveEncounter(mrsToOpenMRSEncounter(mrsEncounter)));
} else {
final Set<Obs> existingObs = existingOpenMrsEncounter.getAllObs(true);
openMRSObservationAdapter.purgeObservations(existingObs);
existingOpenMrsEncounter.setObs(null);
encounterService.saveEncounter(existingOpenMrsEncounter);
openMRSObservationAdapter.saveObservations(mrsEncounter.getObservations(), existingOpenMrsEncounter);
encounterService.saveEncounter(existingOpenMrsEncounter);
return openmrsToMrsEncounter(existingOpenMrsEncounter);
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createEncounter"
|
"@Override
public MRSEncounter createEncounter(MRSEncounter mrsEncounter) {
Encounter existingOpenMrsEncounter = findDuplicateOpenMrsEncounter(mrsEncounter);
if (existingOpenMrsEncounter == null) {
return openmrsToMrsEncounter(encounterService.saveEncounter(mrsToOpenMRSEncounter(mrsEncounter)));
} else {
final Set<Obs> existingObs = existingOpenMrsEncounter.getAllObs(true);
existingOpenMrsEncounter.setObs(null);
encounterService.saveEncounter(existingOpenMrsEncounter);
<MASK>openMRSObservationAdapter.purgeObservations(existingObs);</MASK>
openMRSObservationAdapter.saveObservations(mrsEncounter.getObservations(), existingOpenMrsEncounter);
encounterService.saveEncounter(existingOpenMrsEncounter);
return openmrsToMrsEncounter(existingOpenMrsEncounter);
}
}"
|
Inversion-Mutation
|
megadiff
|
"private void delayedCleanupAfterDisconnect() {
if (VDBG) log("delayedCleanupAfterDisconnect()... Phone state = " + mCM.getState());
// Clean up any connections in the DISCONNECTED state.
//
// [Background: Even after a connection gets disconnected, its
// Connection object still stays around, in the special
// DISCONNECTED state. This is necessary because we we need the
// caller-id information from that Connection to properly draw the
// "Call ended" state of the CallCard.
// But at this point we truly don't need that connection any
// more, so tell the Phone that it's now OK to to clean up any
// connections still in that state.]
mCM.clearDisconnected();
// There are two cases where we should *not* exit the InCallScreen:
// (1) Phone is still in use
// or
// (2) There's an active progress indication (i.e. the "Retrying..."
// progress dialog) that we need to continue to display.
boolean stayHere = phoneIsInUse() || mApp.inCallUiState.isProgressIndicationActive();
if (stayHere) {
if (DBG) log("- delayedCleanupAfterDisconnect: staying on the InCallScreen...");
} else {
// Phone is idle! We should exit the in-call UI now.
if (DBG) log("- delayedCleanupAfterDisconnect: phone is idle...");
// And (finally!) exit from the in-call screen
// (but not if we're already in the process of pausing...)
if (mIsForegroundActivity) {
if (DBG) log("- delayedCleanupAfterDisconnect: finishing InCallScreen...");
// In some cases we finish the call by taking the user to the
// Call Log. Otherwise, we simply call endInCallScreenSession,
// which will take us back to wherever we came from.
//
// UI note: In eclair and earlier, we went to the Call Log
// after outgoing calls initiated on the device, but never for
// incoming calls. Now we do it for incoming calls too, as
// long as the call was answered by the user. (We always go
// back where you came from after a rejected or missed incoming
// call.)
//
// And in any case, *never* go to the call log if we're in
// emergency mode (i.e. if the screen is locked and a lock
// pattern or PIN/password is set), or if we somehow got here
// on a non-voice-capable device.
if (VDBG) log("- Post-call behavior:");
if (VDBG) log(" - mLastDisconnectCause = " + mLastDisconnectCause);
if (VDBG) log(" - isPhoneStateRestricted() = " + isPhoneStateRestricted());
// DisconnectCause values in the most common scenarios:
// - INCOMING_MISSED: incoming ringing call times out, or the
// other end hangs up while still ringing
// - INCOMING_REJECTED: user rejects the call while ringing
// - LOCAL: user hung up while a call was active (after
// answering an incoming call, or after making an
// outgoing call)
// - NORMAL: the other end hung up (after answering an incoming
// call, or after making an outgoing call)
if ((mLastDisconnectCause != Connection.DisconnectCause.INCOMING_MISSED)
&& (mLastDisconnectCause != Connection.DisconnectCause.INCOMING_REJECTED)
&& !isPhoneStateRestricted()
&& PhoneGlobals.sVoiceCapable) {
final Intent intent = mApp.createPhoneEndIntentUsingCallOrigin();
ActivityOptions opts = ActivityOptions.makeCustomAnimation(this,
R.anim.activity_close_enter, R.anim.activity_close_exit);
if (VDBG) {
log("- Show Call Log (or Dialtacts) after disconnect. Current intent: "
+ intent);
}
try {
startActivity(intent, opts.toBundle());
} catch (ActivityNotFoundException e) {
// Don't crash if there's somehow no "Call log" at
// all on this device.
// (This should never happen, though, since we already
// checked PhoneApp.sVoiceCapable above, and any
// voice-capable device surely *should* have a call
// log activity....)
Log.w(LOG_TAG, "delayedCleanupAfterDisconnect: "
+ "transition to call log failed; intent = " + intent);
// ...so just return back where we came from....
}
// Even if we did go to the call log, note that we still
// call endInCallScreenSession (below) to make sure we don't
// stay in the activity history.
}
}
endInCallScreenSession();
// Reset the call origin when the session ends and this in-call UI is being finished.
mApp.setLatestActiveCallOrigin(null);
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "delayedCleanupAfterDisconnect"
|
"private void delayedCleanupAfterDisconnect() {
if (VDBG) log("delayedCleanupAfterDisconnect()... Phone state = " + mCM.getState());
// Clean up any connections in the DISCONNECTED state.
//
// [Background: Even after a connection gets disconnected, its
// Connection object still stays around, in the special
// DISCONNECTED state. This is necessary because we we need the
// caller-id information from that Connection to properly draw the
// "Call ended" state of the CallCard.
// But at this point we truly don't need that connection any
// more, so tell the Phone that it's now OK to to clean up any
// connections still in that state.]
mCM.clearDisconnected();
// There are two cases where we should *not* exit the InCallScreen:
// (1) Phone is still in use
// or
// (2) There's an active progress indication (i.e. the "Retrying..."
// progress dialog) that we need to continue to display.
boolean stayHere = phoneIsInUse() || mApp.inCallUiState.isProgressIndicationActive();
if (stayHere) {
if (DBG) log("- delayedCleanupAfterDisconnect: staying on the InCallScreen...");
} else {
// Phone is idle! We should exit the in-call UI now.
if (DBG) log("- delayedCleanupAfterDisconnect: phone is idle...");
// And (finally!) exit from the in-call screen
// (but not if we're already in the process of pausing...)
if (mIsForegroundActivity) {
if (DBG) log("- delayedCleanupAfterDisconnect: finishing InCallScreen...");
// In some cases we finish the call by taking the user to the
// Call Log. Otherwise, we simply call endInCallScreenSession,
// which will take us back to wherever we came from.
//
// UI note: In eclair and earlier, we went to the Call Log
// after outgoing calls initiated on the device, but never for
// incoming calls. Now we do it for incoming calls too, as
// long as the call was answered by the user. (We always go
// back where you came from after a rejected or missed incoming
// call.)
//
// And in any case, *never* go to the call log if we're in
// emergency mode (i.e. if the screen is locked and a lock
// pattern or PIN/password is set), or if we somehow got here
// on a non-voice-capable device.
if (VDBG) log("- Post-call behavior:");
if (VDBG) log(" - mLastDisconnectCause = " + mLastDisconnectCause);
if (VDBG) log(" - isPhoneStateRestricted() = " + isPhoneStateRestricted());
// DisconnectCause values in the most common scenarios:
// - INCOMING_MISSED: incoming ringing call times out, or the
// other end hangs up while still ringing
// - INCOMING_REJECTED: user rejects the call while ringing
// - LOCAL: user hung up while a call was active (after
// answering an incoming call, or after making an
// outgoing call)
// - NORMAL: the other end hung up (after answering an incoming
// call, or after making an outgoing call)
if ((mLastDisconnectCause != Connection.DisconnectCause.INCOMING_MISSED)
&& (mLastDisconnectCause != Connection.DisconnectCause.INCOMING_REJECTED)
&& !isPhoneStateRestricted()
&& PhoneGlobals.sVoiceCapable) {
final Intent intent = mApp.createPhoneEndIntentUsingCallOrigin();
ActivityOptions opts = ActivityOptions.makeCustomAnimation(this,
R.anim.activity_close_enter, R.anim.activity_close_exit);
if (VDBG) {
log("- Show Call Log (or Dialtacts) after disconnect. Current intent: "
+ intent);
}
try {
startActivity(intent, opts.toBundle());
} catch (ActivityNotFoundException e) {
// Don't crash if there's somehow no "Call log" at
// all on this device.
// (This should never happen, though, since we already
// checked PhoneApp.sVoiceCapable above, and any
// voice-capable device surely *should* have a call
// log activity....)
Log.w(LOG_TAG, "delayedCleanupAfterDisconnect: "
+ "transition to call log failed; intent = " + intent);
// ...so just return back where we came from....
}
// Even if we did go to the call log, note that we still
// call endInCallScreenSession (below) to make sure we don't
// stay in the activity history.
}
<MASK>endInCallScreenSession();</MASK>
}
// Reset the call origin when the session ends and this in-call UI is being finished.
mApp.setLatestActiveCallOrigin(null);
}
}"
|
Inversion-Mutation
|
megadiff
|
"public void start() {
if (stopped || getState() == ProjectState.STOPPED) {
stopped = false;
LOG.info("Project " + name + " starting");
setState(ProjectState.IDLE);
createNewSchedulingThread();
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "start"
|
"public void start() {
if (stopped || getState() == ProjectState.STOPPED) {
stopped = false;
<MASK>createNewSchedulingThread();</MASK>
LOG.info("Project " + name + " starting");
setState(ProjectState.IDLE);
}
}"
|
Inversion-Mutation
|
megadiff
|
"public static <T extends JPASupport> T edit(Object o, String name, Map<String, String[]> params) {
try {
BeanWrapper bw = new BeanWrapper(o.getClass());
// Start with relations
Set<Field> fields = new HashSet<Field>();
Class clazz = o.getClass();
while (!clazz.equals(JPASupport.class)) {
Collections.addAll(fields, clazz.getDeclaredFields());
clazz = clazz.getSuperclass();
}
for (Field field : fields) {
boolean isEntity = false;
String relation = null;
boolean multiple = false;
//
if (field.isAnnotationPresent(OneToOne.class) || field.isAnnotationPresent(ManyToOne.class)) {
isEntity = true;
relation = field.getType().getName();
}
if (field.isAnnotationPresent(OneToMany.class) || field.isAnnotationPresent(ManyToMany.class)) {
Class fieldType = (Class) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];
isEntity = true;
relation = fieldType.getName();
multiple = true;
}
if (isEntity) {
if (multiple && Collection.class.isAssignableFrom(field.getType())) {
Collection l = new ArrayList();
if (Set.class.isAssignableFrom(field.getType())) {
l = new HashSet();
}
String[] ids = params.get(name + "." + field.getName() + "@id");
if(ids == null) {
ids = params.get(name + "." + field.getName() + ".id");
}
if (ids != null) {
params.remove(name + "." + field.getName() + ".id");
params.remove(name + "." + field.getName() + "@id");
for (String _id : ids) {
if (_id.equals("")) {
continue;
}
Query q = JPA.em().createQuery("from " + relation + " where id = ?");
q.setParameter(1, Binder.directBind(_id, findKeyType(Play.classloader.loadClass(relation))));
try {
l.add(q.getSingleResult());
} catch(NoResultException e) {
Validation.addError(name+"."+field.getName(), "validation.notFound", _id);
}
}
}
bw.set(field.getName(), o, l);
} else {
String[] ids = params.get(name + "." + field.getName() + "@id");
if(ids == null) {
ids = params.get(name + "." + field.getName() + ".id");
}
if (ids != null && ids.length > 0 && !ids[0].equals("")) {
params.remove(name + "." + field.getName() + ".id");
params.remove(name + "." + field.getName() + "@id");
Query q = JPA.em().createQuery("from " + relation + " where id = ?");
q.setParameter(1, Binder.directBind(ids[0], findKeyType(Play.classloader.loadClass(relation))));
try {
Object to = q.getSingleResult();
bw.set(field.getName(), o, to);
} catch(NoResultException e) {
Validation.addError(name+"."+field.getName(), "validation.notFound", ids[0]);
}
} else if(ids != null && ids.length > 0 && ids[0].equals("")) {
bw.set(field.getName(), o , null);
params.remove(name + "." + field.getName() + ".id");
params.remove(name + "." + field.getName() + "@id");
}
}
}
if (field.getType().equals(FileAttachment.class)) {
FileAttachment fileAttachment = ((FileAttachment) field.get(o));
if (fileAttachment == null) {
fileAttachment = new FileAttachment(o, field.getName());
bw.set(field.getName(), o, fileAttachment);
}
File file = Params.current().get(name + "." + field.getName(), File.class);
if (file != null && file.exists() && file.length() > 0) {
fileAttachment.set(Params.current().get(name + "." + field.getName(), File.class));
fileAttachment.filename = file.getName();
} else {
String df = Params.current().get(name + "." + field.getName() + "_delete_", String.class);
if (df != null && df.equals("true")) {
fileAttachment.delete();
bw.set(field.getName(), o, null);
}
}
params.remove(name + "." + field.getName());
}
}
// Then bind
bw.bind(name, o.getClass(), params, "", o);
return (T) o;
} catch (Exception e) {
throw new UnexpectedException(e);
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "edit"
|
"public static <T extends JPASupport> T edit(Object o, String name, Map<String, String[]> params) {
try {
BeanWrapper bw = new BeanWrapper(o.getClass());
// Start with relations
Set<Field> fields = new HashSet<Field>();
Class clazz = o.getClass();
while (!clazz.equals(JPASupport.class)) {
Collections.addAll(fields, clazz.getDeclaredFields());
clazz = clazz.getSuperclass();
}
for (Field field : fields) {
boolean isEntity = false;
String relation = null;
boolean multiple = false;
//
if (field.isAnnotationPresent(OneToOne.class) || field.isAnnotationPresent(ManyToOne.class)) {
isEntity = true;
relation = field.getType().getName();
}
if (field.isAnnotationPresent(OneToMany.class) || field.isAnnotationPresent(ManyToMany.class)) {
Class fieldType = (Class) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];
isEntity = true;
relation = fieldType.getName();
multiple = true;
}
if (isEntity) {
if (multiple && Collection.class.isAssignableFrom(field.getType())) {
Collection l = new ArrayList();
if (Set.class.isAssignableFrom(field.getType())) {
l = new HashSet();
}
String[] ids = params.get(name + "." + field.getName() + "@id");
if(ids == null) {
ids = params.get(name + "." + field.getName() + ".id");
}
if (ids != null) {
params.remove(name + "." + field.getName() + ".id");
params.remove(name + "." + field.getName() + "@id");
for (String _id : ids) {
if (_id.equals("")) {
continue;
}
Query q = JPA.em().createQuery("from " + relation + " where id = ?");
q.setParameter(1, Binder.directBind(_id, findKeyType(Play.classloader.loadClass(relation))));
try {
l.add(q.getSingleResult());
} catch(NoResultException e) {
Validation.addError(name+"."+field.getName(), "validation.notFound", _id);
}
}
}
bw.set(field.getName(), o, l);
} else {
String[] ids = params.get(name + "." + field.getName() + "@id");
if(ids == null) {
ids = params.get(name + "." + field.getName() + ".id");
}
if (ids != null && ids.length > 0 && !ids[0].equals("")) {
params.remove(name + "." + field.getName() + ".id");
params.remove(name + "." + field.getName() + "@id");
Query q = JPA.em().createQuery("from " + relation + " where id = ?");
q.setParameter(1, Binder.directBind(ids[0], findKeyType(Play.classloader.loadClass(relation))));
try {
Object to = q.getSingleResult();
bw.set(field.getName(), o, to);
} catch(NoResultException e) {
Validation.addError(name+"."+field.getName(), "validation.notFound", ids[0]);
}
} else if(ids != null && ids.length > 0 && ids[0].equals("")) {
bw.set(field.getName(), o , null);
params.remove(name + "." + field.getName() + ".id");
params.remove(name + "." + field.getName() + "@id");
}
}
}
if (field.getType().equals(FileAttachment.class)) {
FileAttachment fileAttachment = ((FileAttachment) field.get(o));
if (fileAttachment == null) {
fileAttachment = new FileAttachment(o, field.getName());
bw.set(field.getName(), o, fileAttachment);
}
File file = Params.current().get(name + "." + field.getName(), File.class);
if (file != null && file.exists() && file.length() > 0) {
<MASK>params.remove(name + "." + field.getName());</MASK>
fileAttachment.set(Params.current().get(name + "." + field.getName(), File.class));
fileAttachment.filename = file.getName();
} else {
String df = Params.current().get(name + "." + field.getName() + "_delete_", String.class);
if (df != null && df.equals("true")) {
fileAttachment.delete();
bw.set(field.getName(), o, null);
}
}
}
}
// Then bind
bw.bind(name, o.getClass(), params, "", o);
return (T) o;
} catch (Exception e) {
throw new UnexpectedException(e);
}
}"
|
Inversion-Mutation
|
megadiff
|
"public void closeColonyPanel() {
if (getColony().getUnitCount() == 0) {
if (getCanvas().showConfirmDialog("abandonColony.text",
"abandonColony.yes",
"abandonColony.no")) {
getCanvas().remove(this);
getController().abandonColony(getColony());
}
} else {
BuildableType buildable = colony.getCurrentlyBuilding();
if (buildable != null
&& buildable.getPopulationRequired() > colony.getUnitCount()
&& !getCanvas().showConfirmDialog("colonyPanel.reducePopulation",
"ok", "cancel",
"%colony%", colony.getName(),
"%number%", String.valueOf(buildable.getPopulationRequired()),
"%buildable%", buildable.getName())) {
return;
}
getCanvas().remove(this);
// remove property listeners
if (colony != null) {
colony.removePropertyChangeListener(this);
colony.getTile().removePropertyChangeListener(Tile.UNIT_CHANGE, outsideColonyPanel);
colony.getGoodsContainer().removePropertyChangeListener(warehousePanel);
}
if (getSelectedUnit() != null) {
getSelectedUnit().removePropertyChangeListener(this);
}
buildingsPanel.removePropertyChangeListeners();
tilePanel.removePropertyChangeListeners();
if (getGame().getCurrentPlayer() == getMyPlayer()) {
getController().nextModelMessage();
Unit activeUnit = getCanvas().getGUI().getActiveUnit();
if (activeUnit == null || activeUnit.getTile() == null || activeUnit.getMovesLeft() <= 0
|| (!(activeUnit.getLocation() instanceof Tile) && !(activeUnit.isOnCarrier()))) {
getCanvas().getGUI().setActiveUnit(null);
getController().nextActiveUnit();
}
}
getClient().getGUI().restartBlinking();
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "closeColonyPanel"
|
"public void closeColonyPanel() {
if (getColony().getUnitCount() == 0) {
if (getCanvas().showConfirmDialog("abandonColony.text",
"abandonColony.yes",
"abandonColony.no")) {
<MASK>getController().abandonColony(getColony());</MASK>
getCanvas().remove(this);
}
} else {
BuildableType buildable = colony.getCurrentlyBuilding();
if (buildable != null
&& buildable.getPopulationRequired() > colony.getUnitCount()
&& !getCanvas().showConfirmDialog("colonyPanel.reducePopulation",
"ok", "cancel",
"%colony%", colony.getName(),
"%number%", String.valueOf(buildable.getPopulationRequired()),
"%buildable%", buildable.getName())) {
return;
}
getCanvas().remove(this);
// remove property listeners
if (colony != null) {
colony.removePropertyChangeListener(this);
colony.getTile().removePropertyChangeListener(Tile.UNIT_CHANGE, outsideColonyPanel);
colony.getGoodsContainer().removePropertyChangeListener(warehousePanel);
}
if (getSelectedUnit() != null) {
getSelectedUnit().removePropertyChangeListener(this);
}
buildingsPanel.removePropertyChangeListeners();
tilePanel.removePropertyChangeListeners();
if (getGame().getCurrentPlayer() == getMyPlayer()) {
getController().nextModelMessage();
Unit activeUnit = getCanvas().getGUI().getActiveUnit();
if (activeUnit == null || activeUnit.getTile() == null || activeUnit.getMovesLeft() <= 0
|| (!(activeUnit.getLocation() instanceof Tile) && !(activeUnit.isOnCarrier()))) {
getCanvas().getGUI().setActiveUnit(null);
getController().nextActiveUnit();
}
}
getClient().getGUI().restartBlinking();
}
}"
|
Inversion-Mutation
|
megadiff
|
"protected int computeAdornmentFlags(Object obj) {
try {
if (obj instanceof IModelElement) {
IModelElement element= (IModelElement) obj;
int type= element.getElementType();
switch (type) {
case IModelElement.SCRIPT_MODEL:
case IModelElement.SCRIPT_PROJECT:
case IModelElement.PROJECT_FRAGMENT:
case IModelElement.SCRIPT_FOLDER:
return getErrorTicksFromMarkers(element.getResource(), IResource.DEPTH_INFINITE, null);
case IModelElement.SOURCE_MODULE:
return getErrorTicksFromMarkers(element.getResource(), IResource.DEPTH_ONE, null);
case IModelElement.TYPE:
case IModelElement.METHOD:
case IModelElement.FIELD:
ISourceModule cu= (ISourceModule) element.getAncestor(IModelElement.SOURCE_MODULE);
if (cu != null) {
ISourceReference ref= (type == IModelElement.SOURCE_MODULE) ? null : (ISourceReference) element;
// The assumption is that only source elements in compilation unit can have markers
IAnnotationModel model= isInScriptAnnotationModel(cu);
int result= 0;
if (model != null) {
// open in Script editor: look at annotation model
result= getErrorTicksFromAnnotationModel(model, ref);
} else {
result= getErrorTicksFromMarkers(cu.getResource(), IResource.DEPTH_ONE, ref);
}
fCachedRange= null;
return result;
}
break;
default:
}
} else if (obj instanceof IResource) {
return getErrorTicksFromMarkers((IResource) obj, IResource.DEPTH_INFINITE, null);
}
} catch (CoreException e) {
if (e instanceof ModelException) {
if (((ModelException) e).isDoesNotExist()) {
return 0;
}
}
if (e.getStatus().getCode() == IResourceStatus.MARKER_NOT_FOUND) {
return 0;
}
DLTKUIPlugin.log(e);
}
return 0;
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "computeAdornmentFlags"
|
"protected int computeAdornmentFlags(Object obj) {
try {
if (obj instanceof IModelElement) {
IModelElement element= (IModelElement) obj;
int type= element.getElementType();
switch (type) {
case IModelElement.SCRIPT_MODEL:
case IModelElement.SCRIPT_PROJECT:
case IModelElement.PROJECT_FRAGMENT:
<MASK>return getErrorTicksFromMarkers(element.getResource(), IResource.DEPTH_INFINITE, null);</MASK>
case IModelElement.SCRIPT_FOLDER:
case IModelElement.SOURCE_MODULE:
return getErrorTicksFromMarkers(element.getResource(), IResource.DEPTH_ONE, null);
case IModelElement.TYPE:
case IModelElement.METHOD:
case IModelElement.FIELD:
ISourceModule cu= (ISourceModule) element.getAncestor(IModelElement.SOURCE_MODULE);
if (cu != null) {
ISourceReference ref= (type == IModelElement.SOURCE_MODULE) ? null : (ISourceReference) element;
// The assumption is that only source elements in compilation unit can have markers
IAnnotationModel model= isInScriptAnnotationModel(cu);
int result= 0;
if (model != null) {
// open in Script editor: look at annotation model
result= getErrorTicksFromAnnotationModel(model, ref);
} else {
result= getErrorTicksFromMarkers(cu.getResource(), IResource.DEPTH_ONE, ref);
}
fCachedRange= null;
return result;
}
break;
default:
}
} else if (obj instanceof IResource) {
return getErrorTicksFromMarkers((IResource) obj, IResource.DEPTH_INFINITE, null);
}
} catch (CoreException e) {
if (e instanceof ModelException) {
if (((ModelException) e).isDoesNotExist()) {
return 0;
}
}
if (e.getStatus().getCode() == IResourceStatus.MARKER_NOT_FOUND) {
return 0;
}
DLTKUIPlugin.log(e);
}
return 0;
}"
|
Inversion-Mutation
|
megadiff
|
"public void testReaderOperation() {
Charset utf8 = Charset.forName("UTF-8");
byte[] mime = new String("--BOUNDARY\r\nFoo: Bar\r\n Header : Val ue \r\n\r\npart the first\r\n--BOUNDARY \r\n\r\n2nd part\r\n--BOUNDARY--").getBytes(utf8);
for (int chunkSize=1; chunkSize <= mime.length; ++chunkSize) {
ByteArrayInputStream mimeInputStream = new ByteArrayInputStream(mime);
TestMultipartReaderDelegate delegate = new TestMultipartReaderDelegate();
String contentType = "multipart/related; boundary=\"BOUNDARY\"";
CBLMultipartReader reader = new CBLMultipartReader(contentType, delegate);
Assert.assertFalse(reader.finished());
int location = 0;
int length = 0;
do {
Assert.assertTrue("Parser didn't stop at end", location < mime.length);
length = Math.min(chunkSize, (mime.length - location));
byte[] bytesRead = new byte[length];
mimeInputStream.read(bytesRead, 0, length);
reader.appendData(bytesRead);
location += chunkSize;
} while (!reader.finished());
Assert.assertEquals(delegate.partList.size(), 2);
Assert.assertEquals(delegate.headersList.size(), 2);
byte[] part1Expected = new String("part the first").getBytes(utf8);
byte[] part2Expected = new String("2nd part").getBytes(utf8);
ByteArrayBuffer part1 = delegate.partList.get(0);
ByteArrayBuffer part2 = delegate.partList.get(1);
Assert.assertTrue(Arrays.equals(part1.toByteArray(), part1Expected));
Assert.assertTrue(Arrays.equals(part2.toByteArray(), part2Expected));
Map<String, String> headers1 = delegate.headersList.get(0);
Assert.assertTrue(headers1.containsKey("Foo"));
Assert.assertEquals(headers1.get("Foo"), "Bar");
Assert.assertTrue(headers1.containsKey("Header"));
Assert.assertEquals(headers1.get("Header"), "Val ue");
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "testReaderOperation"
|
"public void testReaderOperation() {
Charset utf8 = Charset.forName("UTF-8");
byte[] mime = new String("--BOUNDARY\r\nFoo: Bar\r\n Header : Val ue \r\n\r\npart the first\r\n--BOUNDARY \r\n\r\n2nd part\r\n--BOUNDARY--").getBytes(utf8);
<MASK>ByteArrayInputStream mimeInputStream = new ByteArrayInputStream(mime);</MASK>
for (int chunkSize=1; chunkSize <= mime.length; ++chunkSize) {
TestMultipartReaderDelegate delegate = new TestMultipartReaderDelegate();
String contentType = "multipart/related; boundary=\"BOUNDARY\"";
CBLMultipartReader reader = new CBLMultipartReader(contentType, delegate);
Assert.assertFalse(reader.finished());
int location = 0;
int length = 0;
do {
Assert.assertTrue("Parser didn't stop at end", location < mime.length);
length = Math.min(chunkSize, (mime.length - location));
byte[] bytesRead = new byte[length];
mimeInputStream.read(bytesRead, 0, length);
reader.appendData(bytesRead);
location += chunkSize;
} while (!reader.finished());
Assert.assertEquals(delegate.partList.size(), 2);
Assert.assertEquals(delegate.headersList.size(), 2);
byte[] part1Expected = new String("part the first").getBytes(utf8);
byte[] part2Expected = new String("2nd part").getBytes(utf8);
ByteArrayBuffer part1 = delegate.partList.get(0);
ByteArrayBuffer part2 = delegate.partList.get(1);
Assert.assertTrue(Arrays.equals(part1.toByteArray(), part1Expected));
Assert.assertTrue(Arrays.equals(part2.toByteArray(), part2Expected));
Map<String, String> headers1 = delegate.headersList.get(0);
Assert.assertTrue(headers1.containsKey("Foo"));
Assert.assertEquals(headers1.get("Foo"), "Bar");
Assert.assertTrue(headers1.containsKey("Header"));
Assert.assertEquals(headers1.get("Header"), "Val ue");
}
}"
|
Inversion-Mutation
|
megadiff
|
"public static void main(final String[] args) {
Tools.init();
final JFrame mainFrame = new JFrame(
Tools.getString("DrbdMC.Title") + " " + Tools.getRelease());
final List<Image> il = new ArrayList<Image>();
for (final String iconS : new String[]{"LCMC.AppIcon32",
"LCMC.AppIcon48",
"LCMC.AppIcon64",
"LCMC.AppIcon128",
"LCMC.AppIcon256"}) {
il.add(Tools.createImageIcon(Tools.getDefault(iconS)).getImage());
}
mainFrame.setIconImages(il);
final String autoArgs = initApp(args);
if (autoArgs != null) {
Tools.parseAutoArgs(autoArgs);
}
Tools.invokeLater(new Runnable() {
@Override
public void run() {
createMainFrame(mainFrame);
createAndShowGUI((Container) mainFrame);
}
});
//final Thread t = new Thread(new Runnable() {
// public void run() {
// drbd.utilities.RoboTest.startMover(600000, true);
// }
//});
//t.start();
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "main"
|
"public static void main(final String[] args) {
Tools.init();
final JFrame mainFrame = new JFrame(
Tools.getString("DrbdMC.Title") + " " + Tools.getRelease());
final List<Image> il = new ArrayList<Image>();
for (final String iconS : new String[]{"LCMC.AppIcon32",
"LCMC.AppIcon48",
"LCMC.AppIcon64",
"LCMC.AppIcon128",
"LCMC.AppIcon256"}) {
il.add(Tools.createImageIcon(Tools.getDefault(iconS)).getImage());
}
mainFrame.setIconImages(il);
final String autoArgs = initApp(args);
if (autoArgs != null) {
Tools.parseAutoArgs(autoArgs);
}
<MASK>createMainFrame(mainFrame);</MASK>
Tools.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowGUI((Container) mainFrame);
}
});
//final Thread t = new Thread(new Runnable() {
// public void run() {
// drbd.utilities.RoboTest.startMover(600000, true);
// }
//});
//t.start();
}"
|
Inversion-Mutation
|
megadiff
|
"private void handleExecUrl(String url) {
int idx1 = CORDOVA_EXEC_URL_PREFIX.length();
int idx2 = url.indexOf('#', idx1 + 1);
int idx3 = url.indexOf('#', idx2 + 1);
int idx4 = url.indexOf('#', idx3 + 1);
if (idx1 == -1 || idx2 == -1 || idx3 == -1 || idx4 == -1) {
Log.e(TAG, "Could not decode URL command: " + url);
return;
}
String service = url.substring(idx1, idx2);
String action = url.substring(idx2 + 1, idx3);
String callbackId = url.substring(idx3 + 1, idx4);
String jsonArgs = url.substring(idx4 + 1);
PluginResult r = appView.pluginManager.exec(service, action, callbackId, jsonArgs, true /* async */);
if (r != null) {
String callbackString = r.toCallbackString(callbackId);
appView.sendJavascript(callbackString);
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handleExecUrl"
|
"private void handleExecUrl(String url) {
int idx1 = CORDOVA_EXEC_URL_PREFIX.length();
int idx2 = url.indexOf('#', idx1 + 1);
int idx3 = url.indexOf('#', idx2 + 1);
int idx4 = url.indexOf('#', idx3 + 1);
if (idx1 == -1 || idx2 == -1 || idx3 == -1 || idx4 == -1) {
Log.e(TAG, "Could not decode URL command: " + url);
return;
}
String service = url.substring(idx1, idx2);
String action = url.substring(idx2 + 1, idx3);
String callbackId = url.substring(idx3 + 1, idx4);
String jsonArgs = url.substring(idx4 + 1);
PluginResult r = appView.pluginManager.exec(service, action, callbackId, jsonArgs, true /* async */);
<MASK>String callbackString = r.toCallbackString(callbackId);</MASK>
if (r != null) {
appView.sendJavascript(callbackString);
}
}"
|
Inversion-Mutation
|
megadiff
|
"public synchronized Object getConnectionHandle(boolean recycle) throws Exception {
if (failed) {
try {
if (log.isDebugEnabled()) log.debug("resource '" + bean.getUniqueName() + "' is marked as failed, resetting and recovering it before trying connection acquisition");
close();
init();
IncrementalRecoverer.recover(xaResourceProducer);
}
catch (RecoveryException ex) {
throw new BitronixRuntimeException("incremental recovery failed when trying to acquire a connection from failed resource '" + bean.getUniqueName() + "'", ex);
}
catch (Exception ex) {
throw new BitronixRuntimeException("pool reset failed when trying to acquire a connection from failed resource '" + bean.getUniqueName() + "'", ex);
}
}
long remainingTime = bean.getAcquisitionTimeout() * 1000L;
while (true) {
long before = MonotonicClock.currentTimeMillis();
XAStatefulHolder xaStatefulHolder = null;
if (recycle) {
if (bean.getShareTransactionConnections()) {
xaStatefulHolder = getSharedXAStatefulHolder();
}
else {
xaStatefulHolder = getNotAccessible();
}
}
if (xaStatefulHolder == null) {
xaStatefulHolder = getInPool();
}
if (log.isDebugEnabled()) log.debug("found " + Decoder.decodeXAStatefulHolderState(xaStatefulHolder.getState()) + " connection " + xaStatefulHolder + " from " + this);
try {
// getConnection() here could throw an exception, if it doesn't the connection is
// still alive and we can share it (if sharing is enabled)
Object connectionHandle = xaStatefulHolder.getConnectionHandle();
if (bean.getShareTransactionConnections()) {
putSharedXAStatefulHolder(xaStatefulHolder);
}
growUntilMinPoolSize();
return connectionHandle;
} catch (Exception ex) {
if (log.isDebugEnabled()) log.debug("connection is invalid, trying to close it", ex);
try {
xaStatefulHolder.close();
} catch (Exception ex2) {
if (log.isDebugEnabled()) log.debug("exception while trying to close invalid connection, ignoring it", ex2);
}
objects.remove(xaStatefulHolder);
if (log.isDebugEnabled()) log.debug("removed invalid connection " + xaStatefulHolder + " from " + this);
if (log.isDebugEnabled()) log.debug("waiting " + bean.getAcquisitionInterval() + "s before trying to acquire a connection again from " + this);
long waitTime = bean.getAcquisitionInterval() * 1000L;
if (waitTime > 0) {
try {
wait(waitTime);
} catch (InterruptedException ex2) {
// ignore
}
}
// check for timeout
long now = MonotonicClock.currentTimeMillis();
remainingTime -= (now - before);
if (remainingTime <= 0) {
throw new BitronixRuntimeException("cannot get valid connection from " + this + " after trying for " + bean.getAcquisitionTimeout() + "s", ex);
}
}
} // while true
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getConnectionHandle"
|
"public synchronized Object getConnectionHandle(boolean recycle) throws Exception {
if (failed) {
try {
if (log.isDebugEnabled()) log.debug("resource '" + bean.getUniqueName() + "' is marked as failed, resetting and recovering it before trying connection acquisition");
close();
init();
IncrementalRecoverer.recover(xaResourceProducer);
}
catch (RecoveryException ex) {
throw new BitronixRuntimeException("incremental recovery failed when trying to acquire a connection from failed resource '" + bean.getUniqueName() + "'", ex);
}
catch (Exception ex) {
throw new BitronixRuntimeException("pool reset failed when trying to acquire a connection from failed resource '" + bean.getUniqueName() + "'", ex);
}
}
long remainingTime = bean.getAcquisitionTimeout() * 1000L;
<MASK>long before = MonotonicClock.currentTimeMillis();</MASK>
while (true) {
XAStatefulHolder xaStatefulHolder = null;
if (recycle) {
if (bean.getShareTransactionConnections()) {
xaStatefulHolder = getSharedXAStatefulHolder();
}
else {
xaStatefulHolder = getNotAccessible();
}
}
if (xaStatefulHolder == null) {
xaStatefulHolder = getInPool();
}
if (log.isDebugEnabled()) log.debug("found " + Decoder.decodeXAStatefulHolderState(xaStatefulHolder.getState()) + " connection " + xaStatefulHolder + " from " + this);
try {
// getConnection() here could throw an exception, if it doesn't the connection is
// still alive and we can share it (if sharing is enabled)
Object connectionHandle = xaStatefulHolder.getConnectionHandle();
if (bean.getShareTransactionConnections()) {
putSharedXAStatefulHolder(xaStatefulHolder);
}
growUntilMinPoolSize();
return connectionHandle;
} catch (Exception ex) {
if (log.isDebugEnabled()) log.debug("connection is invalid, trying to close it", ex);
try {
xaStatefulHolder.close();
} catch (Exception ex2) {
if (log.isDebugEnabled()) log.debug("exception while trying to close invalid connection, ignoring it", ex2);
}
objects.remove(xaStatefulHolder);
if (log.isDebugEnabled()) log.debug("removed invalid connection " + xaStatefulHolder + " from " + this);
if (log.isDebugEnabled()) log.debug("waiting " + bean.getAcquisitionInterval() + "s before trying to acquire a connection again from " + this);
long waitTime = bean.getAcquisitionInterval() * 1000L;
if (waitTime > 0) {
try {
wait(waitTime);
} catch (InterruptedException ex2) {
// ignore
}
}
// check for timeout
long now = MonotonicClock.currentTimeMillis();
remainingTime -= (now - before);
if (remainingTime <= 0) {
throw new BitronixRuntimeException("cannot get valid connection from " + this + " after trying for " + bean.getAcquisitionTimeout() + "s", ex);
}
}
} // while true
}"
|
Inversion-Mutation
|
megadiff
|
"public FitSphere(final Vector3D[] points) {
Vector3D mean = Vector3D.ZERO;
for(Vector3D point : points)
mean = mean.add(point.scalarMultiply(1D/(double)points.length));
ReportingUtils.logMessage("MEAN: " + mean.toString());
final Vector3D endMean = new Vector3D(mean.getX(), mean.getY(), mean.getZ());
double[] params = new double[PARAMLEN];
params[RADIUS] = 0.5*points[0].subtract(points[points.length-1]).getNorm();
Vector3D centerGuess = points[points.length/2].subtract(mean).add(mean.subtract(points[points.length/2]).normalize().scalarMultiply(params[RADIUS]));
params[XC] = centerGuess.getX(); params[YC] = centerGuess.getY(); params[ZC] = centerGuess.getZ();
double[] steps = new double[PARAMLEN];
steps[XC] = steps[YC] = steps[ZC] = 0.001;
steps[RADIUS] = 0.00001;
ReportingUtils.logMessage("Initial parameters: " + Arrays.toString(params) + ", steps: " + Arrays.toString(steps));
MultivariateRealFunction MRF = new MultivariateRealFunction() {
@Override
public double value(double[] params) {
Vector3D center = new Vector3D(params[XC], params[YC], params[ZC]);
double err = 0;
for(Vector3D point : points)
err += Math.pow(point.subtract(endMean).subtract(center).getNorm() - params[RADIUS], 2D);
// ReportingUtils.logMessage("value(" + Arrays.toString(params) + "): endMean=" + endMean.toString() + ", err=" + err);
return err;
}
};
SimplexOptimizer opt = new SimplexOptimizer(1e-6, -1);
NelderMeadSimplex nm = new NelderMeadSimplex(steps);
opt.setSimplex(nm);
double[] result = null;
try {
result = opt.optimize(5000000, MRF, GoalType.MINIMIZE, params).getPoint();
error = Math.sqrt(MRF.value(result));
} catch(Throwable t) {
ReportingUtils.logError(t, "Optimization failed!");
}
ReportingUtils.logMessage("Fit: " + Arrays.toString(result));
center = new Vector3D(result[XC], result[YC], result[ZC]).add(mean);
radius = result[RADIUS];
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "FitSphere"
|
"public FitSphere(final Vector3D[] points) {
Vector3D mean = Vector3D.ZERO;
for(Vector3D point : points)
mean = mean.add(point.scalarMultiply(1D/(double)points.length));
ReportingUtils.logMessage("MEAN: " + mean.toString());
final Vector3D endMean = new Vector3D(mean.getX(), mean.getY(), mean.getZ());
double[] params = new double[PARAMLEN];
params[RADIUS] = 0.5*points[0].subtract(points[points.length-1]).getNorm();
Vector3D centerGuess = points[points.length/2].subtract(mean).add(mean.subtract(points[points.length/2]).normalize().scalarMultiply(params[RADIUS]));
params[XC] = centerGuess.getX(); params[YC] = centerGuess.getY(); params[ZC] = centerGuess.getZ();
double[] steps = new double[PARAMLEN];
steps[XC] = steps[YC] = steps[ZC] = 0.001;
steps[RADIUS] = 0.00001;
ReportingUtils.logMessage("Initial parameters: " + Arrays.toString(params) + ", steps: " + Arrays.toString(steps));
MultivariateRealFunction MRF = new MultivariateRealFunction() {
@Override
public double value(double[] params) {
Vector3D center = new Vector3D(params[XC], params[YC], params[ZC]);
double err = 0;
for(Vector3D point : points)
err += Math.pow(point.subtract(endMean).subtract(center).getNorm() - params[RADIUS], 2D);
// ReportingUtils.logMessage("value(" + Arrays.toString(params) + "): endMean=" + endMean.toString() + ", err=" + err);
return err;
}
};
SimplexOptimizer opt = new SimplexOptimizer(1e-6, -1);
NelderMeadSimplex nm = new NelderMeadSimplex(steps);
opt.setSimplex(nm);
double[] result = null;
try {
result = opt.optimize(5000000, MRF, GoalType.MINIMIZE, params).getPoint();
} catch(Throwable t) {
ReportingUtils.logError(t, "Optimization failed!");
}
ReportingUtils.logMessage("Fit: " + Arrays.toString(result));
center = new Vector3D(result[XC], result[YC], result[ZC]).add(mean);
radius = result[RADIUS];
<MASK>error = Math.sqrt(MRF.value(result));</MASK>
}"
|
Inversion-Mutation
|
megadiff
|
"public boolean checkPolicyUpdate(ContentObject co)
throws RepositoryException {
if (_info.getPolicyName().isPrefixOf(co.name())) {
ByteArrayInputStream bais = new ByteArrayInputStream(co.content());
try {
if (_policy.update(bais, true)) {
ContentName policyName = VersioningProfile.addVersion(
ContentName.fromNative(REPO_NAMESPACE + "/" + _info.getLocalName() + "/" + REPO_POLICY));
ContentObject policyCo = new ContentObject(policyName, co.signedInfo(), co.content(), co.signature());
saveContent(policyCo);
return true;
}
} catch (Exception e) {
Library.logStackTrace(Level.WARNING, e);
e.printStackTrace();
}
}
return false;
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "checkPolicyUpdate"
|
"public boolean checkPolicyUpdate(ContentObject co)
throws RepositoryException {
if (_info.getPolicyName().isPrefixOf(co.name())) {
ByteArrayInputStream bais = new ByteArrayInputStream(co.content());
try {
if (_policy.update(bais, true)) {
ContentName policyName = VersioningProfile.addVersion(
ContentName.fromNative(REPO_NAMESPACE + "/" + _info.getLocalName() + "/" + REPO_POLICY));
ContentObject policyCo = new ContentObject(policyName, co.signedInfo(), co.content(), co.signature());
saveContent(policyCo);
}
} catch (Exception e) {
Library.logStackTrace(Level.WARNING, e);
e.printStackTrace();
}
<MASK>return true;</MASK>
}
return false;
}"
|
Inversion-Mutation
|
megadiff
|
"private void search(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo) throws Exception {
String virtualWiki = pageInfo.getVirtualWikiName();
String searchField = request.getParameter("text");
if (request.getParameter("text") == null) {
pageInfo.setPageTitle(new WikiMessage("search.title"));
} else {
pageInfo.setPageTitle(new WikiMessage("searchresult.title", searchField));
}
next.addObject("searchConfig", WikiConfiguration.getCurrentSearchConfiguration());
// forward back to the search page if the request is blank or null
if (StringUtils.isBlank(searchField)) {
pageInfo.setContentJsp(JSP_SEARCH);
pageInfo.setSpecial(true);
return;
}
// grab search engine instance and find
List<SearchResultEntry> results = WikiBase.getSearchEngine().findResults(virtualWiki, searchField);
next.addObject("searchField", searchField);
next.addObject("results", results);
pageInfo.setContentJsp(JSP_SEARCH_RESULTS);
pageInfo.setSpecial(true);
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "search"
|
"private void search(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo) throws Exception {
String virtualWiki = pageInfo.getVirtualWikiName();
String searchField = request.getParameter("text");
if (request.getParameter("text") == null) {
pageInfo.setPageTitle(new WikiMessage("search.title"));
} else {
pageInfo.setPageTitle(new WikiMessage("searchresult.title", searchField));
}
// forward back to the search page if the request is blank or null
if (StringUtils.isBlank(searchField)) {
pageInfo.setContentJsp(JSP_SEARCH);
pageInfo.setSpecial(true);
return;
}
<MASK>next.addObject("searchConfig", WikiConfiguration.getCurrentSearchConfiguration());</MASK>
// grab search engine instance and find
List<SearchResultEntry> results = WikiBase.getSearchEngine().findResults(virtualWiki, searchField);
next.addObject("searchField", searchField);
next.addObject("results", results);
pageInfo.setContentJsp(JSP_SEARCH_RESULTS);
pageInfo.setSpecial(true);
}"
|
Inversion-Mutation
|
megadiff
|
"@Test
public void hybridFilter() {
bytesIn = 0;
final int messageSize = 1000;
IOConnector<SocketAddress> connector =
new SocketEndpoint(BIND_ADDRESS, TransportType.RELIABLE,
Executors.newCachedThreadPool()).createConnector();
IOHandler handler = new IOHandlerAdapter() {
public void connected(IOHandle handle) {
IOFilterTest.this.connectedHandle = handle;
byte[] message = new byte[messageSize];
try {
handle.sendBytes(message);
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
public void bytesReceived(byte[] buffer, IOHandle handle) {
bytesIn += buffer.length;
System.err.println("Got " + buffer.length +
" bytes, total = " + bytesIn);
}
public void disconnected(IOHandle handle) {
IOFilterTest.this.connectedHandle = null;
}
};
connector.connect(handler);
synchronized(this) {
try {
wait(DELAY);
}
catch (InterruptedException ie) {}
}
Assert.assertEquals(messageSize, bytesIn);
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "hybridFilter"
|
"@Test
public void hybridFilter() {
bytesIn = 0;
final int messageSize = 1000;
IOConnector<SocketAddress> connector =
new SocketEndpoint(BIND_ADDRESS, TransportType.RELIABLE,
Executors.newCachedThreadPool()).createConnector();
IOHandler handler = new IOHandlerAdapter() {
public void connected(IOHandle handle) {
IOFilterTest.this.connectedHandle = handle;
byte[] message = new byte[messageSize];
try {
handle.sendBytes(message);
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
public void bytesReceived(byte[] buffer, IOHandle handle) {
System.err.println("Got " + buffer.length +
" bytes, total = " + bytesIn);
<MASK>bytesIn += buffer.length;</MASK>
}
public void disconnected(IOHandle handle) {
IOFilterTest.this.connectedHandle = null;
}
};
connector.connect(handler);
synchronized(this) {
try {
wait(DELAY);
}
catch (InterruptedException ie) {}
}
Assert.assertEquals(messageSize, bytesIn);
}"
|
Inversion-Mutation
|
megadiff
|
"public void bytesReceived(byte[] buffer, IOHandle handle) {
bytesIn += buffer.length;
System.err.println("Got " + buffer.length +
" bytes, total = " + bytesIn);
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "bytesReceived"
|
"public void bytesReceived(byte[] buffer, IOHandle handle) {
System.err.println("Got " + buffer.length +
" bytes, total = " + bytesIn);
<MASK>bytesIn += buffer.length;</MASK>
}"
|
Inversion-Mutation
|
megadiff
|
"private void showMessage(int typingOption, final Message message) {
if (message != null) {
int currentUid = getSharedPreferences(PREFS_NAME, 0).getInt("currentUid", 0);
boolean isNewMessage = message.uid != currentUid;
Log.v(TAG, "Saving new currentUid = " + message.uid);
getSharedPreferences(PREFS_NAME, 0).edit().putInt("currentUid", message.uid).commit();
final TextView t = (TextView) findViewById(R.id.textView);
final TextView signature = (TextView) findViewById(R.id.signature);
// make sure system takes care of links in messages
t.setMovementMethod(LinkMovementMethod.getInstance());
if (isNewMessage || typingOption == TYPING_FORCE_SHOW) {
t.setText("");
signature.setText("");
final Animation fadeinAniDelayed = AnimationUtils.loadAnimation(this, R.anim.fade_in_delayed);
// typewriter effect
typeHandler.removeCallbacksAndMessages(null);
typeHandler.postDelayed(new Runnable() {
int index = 0;
String str = message.text;
@Override
public void run() {
// skip insides of HTML tags
if (index < str.length() && str.charAt(index) == '<') {
int closingIndex = str.indexOf('>', index);
if (closingIndex > index)
index = closingIndex;
}
// TODO: use text adding instead of setting, then at the end set text to use HTML tags?
t.setText(Html.fromHtml((String) str.subSequence(0, index++)));
if (index <= str.length()) {
typeHandler.postDelayed(this, 10);
} else {
// the small print should just fade in
signature.startAnimation(fadeinAniDelayed);
signature.setText(message.getTimeString());
}
}
}, 10);
} else {
// no typewriter effect
t.setText(Html.fromHtml(message.text));
signature.setText(message.getTimeString());
}
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "showMessage"
|
"private void showMessage(int typingOption, final Message message) {
if (message != null) {
int currentUid = getSharedPreferences(PREFS_NAME, 0).getInt("currentUid", 0);
boolean isNewMessage = message.uid != currentUid;
Log.v(TAG, "Saving new currentUid = " + message.uid);
getSharedPreferences(PREFS_NAME, 0).edit().putInt("currentUid", message.uid).commit();
final TextView t = (TextView) findViewById(R.id.textView);
final TextView signature = (TextView) findViewById(R.id.signature);
// make sure system takes care of links in messages
t.setMovementMethod(LinkMovementMethod.getInstance());
if (isNewMessage || typingOption == TYPING_FORCE_SHOW) {
t.setText("");
signature.setText("");
final Animation fadeinAniDelayed = AnimationUtils.loadAnimation(this, R.anim.fade_in_delayed);
// typewriter effect
typeHandler.removeCallbacksAndMessages(null);
typeHandler.postDelayed(new Runnable() {
int index = 0;
String str = message.text;
@Override
public void run() {
// skip insides of HTML tags
if (index < str.length() && str.charAt(index) == '<') {
int closingIndex = str.indexOf('>', index);
if (closingIndex > index)
index = closingIndex;
}
// TODO: use text adding instead of setting, then at the end set text to use HTML tags?
t.setText(Html.fromHtml((String) str.subSequence(0, index++)));
if (index <= str.length()) {
typeHandler.postDelayed(this, 10);
} else {
// the small print should just fade in
<MASK>signature.setText(message.getTimeString());</MASK>
signature.startAnimation(fadeinAniDelayed);
}
}
}, 10);
} else {
// no typewriter effect
t.setText(Html.fromHtml(message.text));
<MASK>signature.setText(message.getTimeString());</MASK>
}
}
}"
|
Inversion-Mutation
|
megadiff
|
"@Override
public void run() {
// skip insides of HTML tags
if (index < str.length() && str.charAt(index) == '<') {
int closingIndex = str.indexOf('>', index);
if (closingIndex > index)
index = closingIndex;
}
// TODO: use text adding instead of setting, then at the end set text to use HTML tags?
t.setText(Html.fromHtml((String) str.subSequence(0, index++)));
if (index <= str.length()) {
typeHandler.postDelayed(this, 10);
} else {
// the small print should just fade in
signature.startAnimation(fadeinAniDelayed);
signature.setText(message.getTimeString());
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
|
"@Override
public void run() {
// skip insides of HTML tags
if (index < str.length() && str.charAt(index) == '<') {
int closingIndex = str.indexOf('>', index);
if (closingIndex > index)
index = closingIndex;
}
// TODO: use text adding instead of setting, then at the end set text to use HTML tags?
t.setText(Html.fromHtml((String) str.subSequence(0, index++)));
if (index <= str.length()) {
typeHandler.postDelayed(this, 10);
} else {
// the small print should just fade in
<MASK>signature.setText(message.getTimeString());</MASK>
signature.startAnimation(fadeinAniDelayed);
}
}"
|
Inversion-Mutation
|
megadiff
|
"protected Runnable getAsyncWriteHandler() {
return new Runnable() {
public void run() {
AsyncWriteToken token = null;
try {
token = asyncWriteQueue.poll(5, TimeUnit.SECONDS);
if (token == null) {
if (!destroyed.get()) bc.getAsyncWriteService().submit(this);
return;
}
if (outOfOrderBroadcastSupported.get()) {
bc.getAsyncWriteService().submit(this);
}
synchronized (token.resource) {
executeAsyncWrite(token);
if (!outOfOrderBroadcastSupported.get()) {
// We want this thread to wait for the write operation to happens to kept the order
bc.getAsyncWriteService().submit(this);
}
}
} catch (InterruptedException ex) {
return;
} catch (Throwable ex) {
if (!started.get() || destroyed.get()) {
logger.trace("Failed to execute a write operation. Broadcaster is destroyed or not yet started for Broadcaster {}", getID(), ex);
return;
} else {
if (token != null) {
logger.warn("This message {} will be lost, adding it to the BroadcasterCache", token.msg);
cacheLostMessage(token.resource, token);
}
logger.debug("Failed to execute a write operation for Broadcaster {}", getID(), ex);
}
}
}
};
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getAsyncWriteHandler"
|
"protected Runnable getAsyncWriteHandler() {
return new Runnable() {
public void run() {
AsyncWriteToken token = null;
try {
token = asyncWriteQueue.poll(5, TimeUnit.SECONDS);
if (token == null) {
if (!destroyed.get()) bc.getAsyncWriteService().submit(this);
return;
}
if (outOfOrderBroadcastSupported.get()) {
bc.getAsyncWriteService().submit(this);
}
synchronized (token.resource) {
if (!outOfOrderBroadcastSupported.get()) {
// We want this thread to wait for the write operation to happens to kept the order
bc.getAsyncWriteService().submit(this);
}
<MASK>executeAsyncWrite(token);</MASK>
}
} catch (InterruptedException ex) {
return;
} catch (Throwable ex) {
if (!started.get() || destroyed.get()) {
logger.trace("Failed to execute a write operation. Broadcaster is destroyed or not yet started for Broadcaster {}", getID(), ex);
return;
} else {
if (token != null) {
logger.warn("This message {} will be lost, adding it to the BroadcasterCache", token.msg);
cacheLostMessage(token.resource, token);
}
logger.debug("Failed to execute a write operation for Broadcaster {}", getID(), ex);
}
}
}
};
}"
|
Inversion-Mutation
|
megadiff
|
"public void run() {
AsyncWriteToken token = null;
try {
token = asyncWriteQueue.poll(5, TimeUnit.SECONDS);
if (token == null) {
if (!destroyed.get()) bc.getAsyncWriteService().submit(this);
return;
}
if (outOfOrderBroadcastSupported.get()) {
bc.getAsyncWriteService().submit(this);
}
synchronized (token.resource) {
executeAsyncWrite(token);
if (!outOfOrderBroadcastSupported.get()) {
// We want this thread to wait for the write operation to happens to kept the order
bc.getAsyncWriteService().submit(this);
}
}
} catch (InterruptedException ex) {
return;
} catch (Throwable ex) {
if (!started.get() || destroyed.get()) {
logger.trace("Failed to execute a write operation. Broadcaster is destroyed or not yet started for Broadcaster {}", getID(), ex);
return;
} else {
if (token != null) {
logger.warn("This message {} will be lost, adding it to the BroadcasterCache", token.msg);
cacheLostMessage(token.resource, token);
}
logger.debug("Failed to execute a write operation for Broadcaster {}", getID(), ex);
}
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
|
"public void run() {
AsyncWriteToken token = null;
try {
token = asyncWriteQueue.poll(5, TimeUnit.SECONDS);
if (token == null) {
if (!destroyed.get()) bc.getAsyncWriteService().submit(this);
return;
}
if (outOfOrderBroadcastSupported.get()) {
bc.getAsyncWriteService().submit(this);
}
synchronized (token.resource) {
if (!outOfOrderBroadcastSupported.get()) {
// We want this thread to wait for the write operation to happens to kept the order
bc.getAsyncWriteService().submit(this);
}
<MASK>executeAsyncWrite(token);</MASK>
}
} catch (InterruptedException ex) {
return;
} catch (Throwable ex) {
if (!started.get() || destroyed.get()) {
logger.trace("Failed to execute a write operation. Broadcaster is destroyed or not yet started for Broadcaster {}", getID(), ex);
return;
} else {
if (token != null) {
logger.warn("This message {} will be lost, adding it to the BroadcasterCache", token.msg);
cacheLostMessage(token.resource, token);
}
logger.debug("Failed to execute a write operation for Broadcaster {}", getID(), ex);
}
}
}"
|
Inversion-Mutation
|
megadiff
|
"public void testServerStartup()
throws Exception
{
String myName = toString();
boolean serverCameUp = serverCameUp();
String serverOutput = getServerOutput();
boolean outputOK = ( serverOutput.indexOf( _outcome.expectedServerOutput() ) >= 0 );
assertEquals( myName + ": serverCameUp = " + serverCameUp, _outcome.serverShouldComeUp(), serverCameUp );
if (!(runsWithEmma() || runsWithJaCoCo())) {
// With Emma we run without the security manager, so we can't
// assert on seeing it.
assertTrue( myName + "\nExpected: " +
_outcome.expectedServerOutput() +
"\nBut saw: " + serverOutput , outputOK );
}
//
// make sure that the default policy lets us connect to the server if the hostname was
// wildcarded (DERBY-2811)
//
if ( _authenticationRequired && ( _wildCardHost != null ) ) { connectToServer(); }
//
// make sure that we can run sysinfo and turn on tracing (DERBY-3086)
//
runsysinfo();
enableTracing();
setTraceDirectory();
disableTracing();
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "testServerStartup"
|
"public void testServerStartup()
throws Exception
{
String myName = toString();
<MASK>String serverOutput = getServerOutput();</MASK>
boolean serverCameUp = serverCameUp();
boolean outputOK = ( serverOutput.indexOf( _outcome.expectedServerOutput() ) >= 0 );
assertEquals( myName + ": serverCameUp = " + serverCameUp, _outcome.serverShouldComeUp(), serverCameUp );
if (!(runsWithEmma() || runsWithJaCoCo())) {
// With Emma we run without the security manager, so we can't
// assert on seeing it.
assertTrue( myName + "\nExpected: " +
_outcome.expectedServerOutput() +
"\nBut saw: " + serverOutput , outputOK );
}
//
// make sure that the default policy lets us connect to the server if the hostname was
// wildcarded (DERBY-2811)
//
if ( _authenticationRequired && ( _wildCardHost != null ) ) { connectToServer(); }
//
// make sure that we can run sysinfo and turn on tracing (DERBY-3086)
//
runsysinfo();
enableTracing();
setTraceDirectory();
disableTracing();
}"
|
Inversion-Mutation
|
megadiff
|
"public void execute() throws MojoExecutionException, MojoFailureException {
logGroovyVersion("console");
try {
// get classes we need with reflection
Class consoleClass = Class.forName("groovy.ui.Console");
Class bindingClass = Class.forName("groovy.lang.Binding");
// create console to run
Object binding = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(bindingClass));
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(bindingClass, "setVariable", String.class, Object.class), binding, "settings", settings);
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(bindingClass, "setVariable", String.class, Object.class), binding, "project", project);
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(bindingClass, "setVariable", String.class, Object.class), binding, "session", session);
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(bindingClass, "setVariable", String.class, Object.class), binding, "pluginArtifacts", pluginArtifacts);
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(bindingClass, "setVariable", String.class, Object.class), binding, "localRepository", localRepository);
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(bindingClass, "setVariable", String.class, Object.class), binding, "reactorProjects", reactorProjects);
// this is intentionally after the default properties so that the user can override if desired
for (String key : properties.stringPropertyNames()) {
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(bindingClass, "setVariable", String.class, Object.class), binding, key, properties.getProperty(key));
}
Object console = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(consoleClass, ClassLoader.class, bindingClass), bindingClass.getClassLoader(), binding);
// run the console
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(consoleClass, "run"), console);
// TODO: replace the active wait with a passive one
while (((JFrame) ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(consoleClass, "getFrame"), console)).isVisible()) {
// do nothing, wait for console window to be closed
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// do nothing, the sleep is only here to not eat as many CPU cycles
}
}
} catch (ClassNotFoundException e) {
throw new MojoExecutionException("Unable to get a Groovy class from classpath. Do you have Groovy as a compile dependency in your project?", e);
} catch (InvocationTargetException e) {
throw new MojoExecutionException("Error occurred while calling a method on a Groovy class from classpath.", e);
} catch (IllegalAccessException e) {
throw new MojoExecutionException("Unable to access a method on a Groovy class from classpath.", e);
} catch (InstantiationException e) {
throw new MojoExecutionException("Error occurred while instantiating a Groovy class from classpath.", e);
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "execute"
|
"public void execute() throws MojoExecutionException, MojoFailureException {
logGroovyVersion("console");
try {
// get classes we need with reflection
Class consoleClass = Class.forName("groovy.ui.Console");
Class bindingClass = Class.forName("groovy.lang.Binding");
// create console to run
Object binding = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(bindingClass));
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(bindingClass, "setVariable", String.class, Object.class), binding, "settings", settings);
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(bindingClass, "setVariable", String.class, Object.class), binding, "project", project);
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(bindingClass, "setVariable", String.class, Object.class), binding, "session", session);
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(bindingClass, "setVariable", String.class, Object.class), binding, "pluginArtifacts", pluginArtifacts);
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(bindingClass, "setVariable", String.class, Object.class), binding, "localRepository", localRepository);
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(bindingClass, "setVariable", String.class, Object.class), binding, "reactorProjects", reactorProjects);
<MASK>Object console = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(consoleClass, ClassLoader.class, bindingClass), bindingClass.getClassLoader(), binding);</MASK>
// this is intentionally after the default properties so that the user can override if desired
for (String key : properties.stringPropertyNames()) {
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(bindingClass, "setVariable", String.class, Object.class), binding, key, properties.getProperty(key));
}
// run the console
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(consoleClass, "run"), console);
// TODO: replace the active wait with a passive one
while (((JFrame) ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(consoleClass, "getFrame"), console)).isVisible()) {
// do nothing, wait for console window to be closed
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// do nothing, the sleep is only here to not eat as many CPU cycles
}
}
} catch (ClassNotFoundException e) {
throw new MojoExecutionException("Unable to get a Groovy class from classpath. Do you have Groovy as a compile dependency in your project?", e);
} catch (InvocationTargetException e) {
throw new MojoExecutionException("Error occurred while calling a method on a Groovy class from classpath.", e);
} catch (IllegalAccessException e) {
throw new MojoExecutionException("Unable to access a method on a Groovy class from classpath.", e);
} catch (InstantiationException e) {
throw new MojoExecutionException("Error occurred while instantiating a Groovy class from classpath.", e);
}
}"
|
Inversion-Mutation
|
megadiff
|
"private void makeKnownIdentitiesList(OwnIdentity treeOwner) throws DuplicateScoreException, DuplicateTrustException {
String nickFilter = request.getPartAsStringFailsafe("nickfilter", 100).trim();
String sortBy = request.isPartSet("sortby") ? request.getPartAsStringFailsafe("sortby", 100).trim() : "Nickname";
String sortType = request.isPartSet("sorttype") ? request.getPartAsStringFailsafe("sorttype", 100).trim() : "Ascending";
HTMLNode knownIdentitiesBox = addContentBox(l10n().getString("KnownIdentitiesPage.KnownIdentities.Header"));
knownIdentitiesBox = pr.addFormChild(knownIdentitiesBox, uri.toString(), "Filters").addChild("p");
knownIdentitiesBox.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "OwnerID", treeOwner.getID()});
InfoboxNode filtersBoxNode = getContentBox(l10n().getString("KnownIdentitiesPage.FiltersAndSorting.Header"));
{ // Filters box
knownIdentitiesBox.addChild(filtersBoxNode.outer);
HTMLNode filtersBox = filtersBoxNode.content;
filtersBox.addChild("#", l10n().getString("KnownIdentitiesPage.FiltersAndSorting.ShowOnlyNicksContaining") + " : ");
filtersBox.addChild("input", new String[] {"type", "size", "name", "value"}, new String[]{"text", "15", "nickfilter", nickFilter});
filtersBox.addChild("#", " " + l10n().getString("KnownIdentitiesPage.FiltersAndSorting.SortIdentitiesBy") + " : ");
HTMLNode option = filtersBox.addChild("select", new String[]{"name", "id"}, new String[]{"sortby", "sortby"});
TreeMap<String, String> options = new TreeMap<String, String>();
options.put(SortBy.Nickname.toString(), l10n().getString("KnownIdentitiesPage.FiltersAndSorting.SortIdentitiesBy.Nickname"));
options.put(SortBy.Score.toString(), l10n().getString("KnownIdentitiesPage.FiltersAndSorting.SortIdentitiesBy.Score"));
options.put(SortBy.LocalTrust.toString(), l10n().getString("KnownIdentitiesPage.FiltersAndSorting.SortIdentitiesBy.LocalTrust"));
for(String e : options.keySet()) {
HTMLNode newOption = option.addChild("option", "value", e, options.get(e));
if(e.equals(sortBy)) {
newOption.addAttribute("selected", "selected");
}
}
option = filtersBox.addChild("select", new String[]{"name", "id"}, new String[]{"sorttype", "sorttype"});
options = new TreeMap<String, String>();
options.put("Ascending", l10n().getString("KnownIdentitiesPage.FiltersAndSorting.SortIdentitiesBy.Ascending"));
options.put("Descending", l10n().getString("KnownIdentitiesPage.FiltersAndSorting.SortIdentitiesBy.Descending"));
for(String e : options.keySet()) {
HTMLNode newOption = option.addChild("option", "value", e, options.get(e));
if(e.equals(sortType)) {
newOption.addAttribute("selected", "selected");
}
}
filtersBox.addChild("input", new String[]{"type", "value"}, new String[]{"submit", l10n().getString("KnownIdentitiesPage.FiltersAndSorting.SortIdentitiesBy.SubmitButton")});
}
// Display the list of known identities
HTMLNode identitiesTable = knownIdentitiesBox.addChild("table", "border", "0");
identitiesTable.addChild(getKnownIdentitiesListTableHeader());
WebOfTrust.SortOrder sortInstruction = WebOfTrust.SortOrder.valueOf("By" + sortBy + sortType);
long currentTime = CurrentTimeUTC.getInMillis();
long editionSum = 0;
synchronized(wot) {
for(Identity id : wot.getAllIdentitiesFilteredAndSorted(treeOwner, nickFilter, sortInstruction)) {
if(id == treeOwner) continue;
HTMLNode row=identitiesTable.addChild("tr");
// NickName
HTMLNode nameLink = row.addChild("td", new String[] {"title", "style"}, new String[] {id.getRequestURI().toString(), "cursor: help;"})
.addChild("a", "href", identitiesPageURI+"?id=" + id.getID());
String nickName = id.getNickname();
if(nickName != null) {
nameLink.addChild("#", nickName + "@" + id.getID().substring(0, 5) + "...");
}
else
nameLink.addChild("span", "class", "alert-error").addChild("#", l10n().getString("KnownIdentitiesPage.KnownIdentities.Table.NicknameNotDownloadedYet"));
// Added date
row.addChild("td", CommonWebUtils.formatTimeDelta(currentTime - id.getAddedDate().getTime(), l10n()));
// Last fetched date
Date lastFetched = id.getLastFetchedDate();
if(!lastFetched.equals(new Date(0)))
row.addChild("td", CommonWebUtils.formatTimeDelta(currentTime - lastFetched.getTime(), l10n()));
else
row.addChild("td", l10n().getString("Common.Never"));
// Publish TrustList
row.addChild("td", new String[] { "align" }, new String[] { "center" } , id.doesPublishTrustList() ? l10n().getString("Common.Yes") : l10n().getString("Common.No"));
//Score
try {
final Score score = wot.getScore((OwnIdentity)treeOwner, id);
final int scoreValue = score.getScore();
final int rank = score.getRank();
row.addChild("td", new String[] { "align", "style" }, new String[] { "center", "background-color:" + KnownIdentitiesPage.getTrustColor(scoreValue) + ";" } ,
Integer.toString(scoreValue) +" ("+
(rank != Integer.MAX_VALUE ? rank : l10n().getString("KnownIdentitiesPage.KnownIdentities.Table.InfiniteRank"))
+")");
}
catch (NotInTrustTreeException e) {
// This only happen with identities added manually by the user
row.addChild("td", l10n().getString("KnownIdentitiesPage.KnownIdentities.Table.NoScore"));
}
// Own Trust
row.addChild(getReceivedTrustCell(treeOwner, id));
// Checkbox
row.addChild(getSetTrustCell(id));
// Nb Trusters
HTMLNode trustersCell = row.addChild("td", new String[] { "align" }, new String[] { "center" });
trustersCell.addChild(new HTMLNode("a", "href", identitiesPageURI + "?id="+id.getID(),
Long.toString(wot.getReceivedTrusts(id).size())));
// Nb Trustees
HTMLNode trusteesCell = row.addChild("td", new String[] { "align" }, new String[] { "center" });
trusteesCell.addChild(new HTMLNode("a", "href", identitiesPageURI + "?id="+id.getID(),
Long.toString(wot.getGivenTrusts(id).size())));
// TODO: Show in advanced mode only once someone finally fixes the "Switch to advanced mode" link on FProxy to work on ALL pages.
final long edition = id.getEdition();
editionSum += edition;
row.addChild("td", "align", "center", Long.toString(edition));
row.addChild("td", "align", "center", Long.toString(id.getLatestEditionHint()));
}
}
identitiesTable.addChild(getKnownIdentitiesListTableHeader());
knownIdentitiesBox.addChild("#", l10n().getString("KnownIdentitiesPage.KnownIdentities.FetchProgress", "editionCount", Long.toString(editionSum)));
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "makeKnownIdentitiesList"
|
"private void makeKnownIdentitiesList(OwnIdentity treeOwner) throws DuplicateScoreException, DuplicateTrustException {
String nickFilter = request.getPartAsStringFailsafe("nickfilter", 100).trim();
String sortBy = request.isPartSet("sortby") ? request.getPartAsStringFailsafe("sortby", 100).trim() : "Nickname";
String sortType = request.isPartSet("sorttype") ? request.getPartAsStringFailsafe("sorttype", 100).trim() : "Ascending";
HTMLNode knownIdentitiesBox = addContentBox(l10n().getString("KnownIdentitiesPage.KnownIdentities.Header"));
knownIdentitiesBox = pr.addFormChild(knownIdentitiesBox, uri.toString(), "Filters").addChild("p");
knownIdentitiesBox.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "OwnerID", treeOwner.getID()});
InfoboxNode filtersBoxNode = getContentBox(l10n().getString("KnownIdentitiesPage.FiltersAndSorting.Header"));
{ // Filters box
knownIdentitiesBox.addChild(filtersBoxNode.outer);
HTMLNode filtersBox = filtersBoxNode.content;
filtersBox.addChild("#", l10n().getString("KnownIdentitiesPage.FiltersAndSorting.ShowOnlyNicksContaining") + " : ");
<MASK>filtersBox.addChild("#", " " + l10n().getString("KnownIdentitiesPage.FiltersAndSorting.SortIdentitiesBy") + " : ");</MASK>
filtersBox.addChild("input", new String[] {"type", "size", "name", "value"}, new String[]{"text", "15", "nickfilter", nickFilter});
HTMLNode option = filtersBox.addChild("select", new String[]{"name", "id"}, new String[]{"sortby", "sortby"});
TreeMap<String, String> options = new TreeMap<String, String>();
options.put(SortBy.Nickname.toString(), l10n().getString("KnownIdentitiesPage.FiltersAndSorting.SortIdentitiesBy.Nickname"));
options.put(SortBy.Score.toString(), l10n().getString("KnownIdentitiesPage.FiltersAndSorting.SortIdentitiesBy.Score"));
options.put(SortBy.LocalTrust.toString(), l10n().getString("KnownIdentitiesPage.FiltersAndSorting.SortIdentitiesBy.LocalTrust"));
for(String e : options.keySet()) {
HTMLNode newOption = option.addChild("option", "value", e, options.get(e));
if(e.equals(sortBy)) {
newOption.addAttribute("selected", "selected");
}
}
option = filtersBox.addChild("select", new String[]{"name", "id"}, new String[]{"sorttype", "sorttype"});
options = new TreeMap<String, String>();
options.put("Ascending", l10n().getString("KnownIdentitiesPage.FiltersAndSorting.SortIdentitiesBy.Ascending"));
options.put("Descending", l10n().getString("KnownIdentitiesPage.FiltersAndSorting.SortIdentitiesBy.Descending"));
for(String e : options.keySet()) {
HTMLNode newOption = option.addChild("option", "value", e, options.get(e));
if(e.equals(sortType)) {
newOption.addAttribute("selected", "selected");
}
}
filtersBox.addChild("input", new String[]{"type", "value"}, new String[]{"submit", l10n().getString("KnownIdentitiesPage.FiltersAndSorting.SortIdentitiesBy.SubmitButton")});
}
// Display the list of known identities
HTMLNode identitiesTable = knownIdentitiesBox.addChild("table", "border", "0");
identitiesTable.addChild(getKnownIdentitiesListTableHeader());
WebOfTrust.SortOrder sortInstruction = WebOfTrust.SortOrder.valueOf("By" + sortBy + sortType);
long currentTime = CurrentTimeUTC.getInMillis();
long editionSum = 0;
synchronized(wot) {
for(Identity id : wot.getAllIdentitiesFilteredAndSorted(treeOwner, nickFilter, sortInstruction)) {
if(id == treeOwner) continue;
HTMLNode row=identitiesTable.addChild("tr");
// NickName
HTMLNode nameLink = row.addChild("td", new String[] {"title", "style"}, new String[] {id.getRequestURI().toString(), "cursor: help;"})
.addChild("a", "href", identitiesPageURI+"?id=" + id.getID());
String nickName = id.getNickname();
if(nickName != null) {
nameLink.addChild("#", nickName + "@" + id.getID().substring(0, 5) + "...");
}
else
nameLink.addChild("span", "class", "alert-error").addChild("#", l10n().getString("KnownIdentitiesPage.KnownIdentities.Table.NicknameNotDownloadedYet"));
// Added date
row.addChild("td", CommonWebUtils.formatTimeDelta(currentTime - id.getAddedDate().getTime(), l10n()));
// Last fetched date
Date lastFetched = id.getLastFetchedDate();
if(!lastFetched.equals(new Date(0)))
row.addChild("td", CommonWebUtils.formatTimeDelta(currentTime - lastFetched.getTime(), l10n()));
else
row.addChild("td", l10n().getString("Common.Never"));
// Publish TrustList
row.addChild("td", new String[] { "align" }, new String[] { "center" } , id.doesPublishTrustList() ? l10n().getString("Common.Yes") : l10n().getString("Common.No"));
//Score
try {
final Score score = wot.getScore((OwnIdentity)treeOwner, id);
final int scoreValue = score.getScore();
final int rank = score.getRank();
row.addChild("td", new String[] { "align", "style" }, new String[] { "center", "background-color:" + KnownIdentitiesPage.getTrustColor(scoreValue) + ";" } ,
Integer.toString(scoreValue) +" ("+
(rank != Integer.MAX_VALUE ? rank : l10n().getString("KnownIdentitiesPage.KnownIdentities.Table.InfiniteRank"))
+")");
}
catch (NotInTrustTreeException e) {
// This only happen with identities added manually by the user
row.addChild("td", l10n().getString("KnownIdentitiesPage.KnownIdentities.Table.NoScore"));
}
// Own Trust
row.addChild(getReceivedTrustCell(treeOwner, id));
// Checkbox
row.addChild(getSetTrustCell(id));
// Nb Trusters
HTMLNode trustersCell = row.addChild("td", new String[] { "align" }, new String[] { "center" });
trustersCell.addChild(new HTMLNode("a", "href", identitiesPageURI + "?id="+id.getID(),
Long.toString(wot.getReceivedTrusts(id).size())));
// Nb Trustees
HTMLNode trusteesCell = row.addChild("td", new String[] { "align" }, new String[] { "center" });
trusteesCell.addChild(new HTMLNode("a", "href", identitiesPageURI + "?id="+id.getID(),
Long.toString(wot.getGivenTrusts(id).size())));
// TODO: Show in advanced mode only once someone finally fixes the "Switch to advanced mode" link on FProxy to work on ALL pages.
final long edition = id.getEdition();
editionSum += edition;
row.addChild("td", "align", "center", Long.toString(edition));
row.addChild("td", "align", "center", Long.toString(id.getLatestEditionHint()));
}
}
identitiesTable.addChild(getKnownIdentitiesListTableHeader());
knownIdentitiesBox.addChild("#", l10n().getString("KnownIdentitiesPage.KnownIdentities.FetchProgress", "editionCount", Long.toString(editionSum)));
}"
|
Inversion-Mutation
|
megadiff
|
"public void setVoiceInput(VoiceInput voiceInput, SubtypeSwitcher switcher) {
if (mVoiceInput == null && voiceInput != null) {
mVoiceInput = voiceInput;
}
switcher.setVoiceInputConnector(this);
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setVoiceInput"
|
"public void setVoiceInput(VoiceInput voiceInput, SubtypeSwitcher switcher) {
if (mVoiceInput == null && voiceInput != null) {
mVoiceInput = voiceInput;
<MASK>switcher.setVoiceInputConnector(this);</MASK>
}
}"
|
Inversion-Mutation
|
megadiff
|
"private void attachListeners() {
this.boardView.setBoardViewListener(new BoardViewListener() {
@Override
public void onConfigChange(String command, String value) {
Log.d("monopd", "BoardView tapped config change " + command + " = " + value);
Bundle state = new Bundle();
state.putString("command", command);
state.putString("value", value);
BoardActivity.this.sendToNetThread(BoardNetworkAction.MSG_CONFIG, state);
}
@Override
public void onStartGame() {
Log.d("monopd", "BoardView tapped start game");
BoardActivity.this.sendToNetThread(BoardNetworkAction.MSG_GAME_START, null);
}
@Override
public void onResize(int width, int height) {
Log.d("monopd", "BoardView resized to " + width + "," + height);
redrawRegions();
}
});
this.chatSendBox.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_ENTER) {
String text = BoardActivity.this.chatSendBox.getText().toString();
if (text.length() > 0) {
BoardActivity.this.sendCommand(text);
BoardActivity.this.chatSendBox.setText("");
}
}
return false;
}
});
this.chatList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> listView, View itemView, int position, long id) {
ChatItem item = BoardActivity.this.chatListAdapter.getItem(position);
if (item.getPlayerId() > 0) {
BoardActivity.this.boardView.overlayPlayerInfo(BoardActivity.this.players.get(item.getPlayerId()));
} else if (item.getEstateId() > 0) {
BoardActivity.this.boardView.overlayEstateInfo(BoardActivity.this.estates.get(item.getEstateId()));
}
}
});
this.netRunnable.setActivity(this, new MonoProtocolGameListener() {
@Override
public void onException(String description, Exception ex) {
Log.v("monopd", "net: Received onException() from MonoProtocolHandler");
Bundle state = new Bundle();
state.putString("error", description + ": " + ex.getMessage());
showDialog(R.id.dialog_conn_error, state);
}
@Override
public void onClose(boolean remote) {
Log.d("monopd", "net: onClose(" + remote + ")");
if (remote) {
Bundle state = new Bundle();
state.putString("error", "Connection lost.");
showDialog(R.id.dialog_conn_error, state);
}
}
@Override
public void onServer(String version) {
Log.v("monopd", "net: Received onServer() from MonoProtocolHandler");
}
@Override
public void onClient(int playerId, String cookie) {
Log.v("monopd", "net: Received onClient() from MonoProtocolHandler");
BoardActivity.this.playerId = playerId;
BoardActivity.this.cookie = cookie;
}
@Override
public void onPlayerUpdate(final int playerId, HashMap<String, String> data) {
Log.v("monopd", "net: Received onPlayerUpdate() from MonoProtocolHandler");
final HashMap<String, String> map = new HashMap<String, String>(data);
runOnUiThread(new Runnable() {
@Override
public void run() {
boolean changingLocation = false;
boolean changingMaster = false;
boolean wasMaster = false;
Player player = players.get(playerId);
if (player == null) {
player = new Player(playerId);
switch (status) {
case ERROR:
case RECONNECT:
case CREATE:
case JOIN:
// ignore playerupdates before game state change!
return;
case CONFIG:
case RUN:
case INIT:
// add to player list
for (int i = 0; i < 4; i++) {
if (playerIds[i] == 0) {
playerIds[i] = playerId;
break;
}
}
break;
}
}
for (String key : map.keySet()) {
String value = map.get(key);
XmlAttribute attr = playerAttributes.get(key);
if (attr == null) {
Log.w("monopd", "player." + key + " was unknown. Value = " + value);
} else {
if (key.equals("location")) {
changingLocation = true;
}
if (key.equals("master")) {
changingMaster = true;
wasMaster = player.isMaster();
}
attr.set(player, value);
}
}
players.put(playerId, player);
updatePlayerView();
boardView.drawEstateOwnerRegions(estates, playerIds, players);
if (changingLocation) {
animateMove(player);
}
if (changingMaster) {
if (player.getPlayerId() == BoardActivity.this.playerId && player.isMaster() != isMaster) {
isMaster = player.isMaster();
}
//if (player.isMaster() && !wasMaster) {
// writeMessage(player.getNick() + " is now game master.", Color.YELLOW, playerId, -1, false);
//}
}
}
});
}
@Override
public void onPlayerDelete(final int playerId) {
runOnUiThread(new Runnable() {
@Override
public void run() {
players.delete(playerId);
boolean deleted = false;
for (int i = 0; i < 4; i++) {
if (playerIds[i] == playerId) {
deleted = true;
}
if (deleted) {
if (i < 3) {
playerIds[i] = playerIds[i + 1];
} else {
playerIds[i] = 0;
/*for (int j = 0; j < players.size(); j++) {
int playerIdJ = players.keyAt(j);
boolean foundPlayerJ = false;
for (int k = 0; k < 4; k++) {
if (playerIdJ == playerIds[k] || players.get(playerIdJ).getNick().equals("_metaserver_")) {
foundPlayerJ = true;
}
}
if (!foundPlayerJ) {
playerIds[i] = playerIdJ;
break;
}
}*/
}
}
}
updatePlayerView();
}
});
}
@Override
public void onEstateUpdate(final int estateId, final HashMap<String, String> data) {
Log.v("monopd", "net: Received onEstateUpdate() from MonoProtocolHandler");
final HashMap<String, String> map = new HashMap<String, String>(data);
runOnUiThread(new Runnable() {
@Override
public void run() {
Estate estate;
boolean isNew = false;
if (estateId < estates.size()) {
estate = estates.get(estateId);
} else {
isNew = true;
estate = new Estate(estateId);
}
for (String key : map.keySet()) {
String value = map.get(key);
XmlAttribute attr = BoardActivity.estateAttributes.get(key);
if (attr == null) {
Log.w("monopd", "estate." + key + " was unknown. Value = " + value);
} else {
attr.set(estate, value);
}
}
if (isNew) {
if (estateId > estates.size()) {
estates.add(estates.size(), estate);
} else {
estates.add(estateId, estate);
}
} else {
estates.set(estateId, estate);
}
boardView.drawEstateOwnerRegions(estates, playerIds, players);
}
});
}
@Override
public void onGameUpdate(final int gameId, final String status) {
Log.v("monopd", "net: Received onGameUpdate() from MonoProtocolHandler");
BoardActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
if (gameId > 0) {
gameItem.setGameId(gameId);
}
BoardActivity.this.status = GameStatus.fromString(status);
BoardActivity.this.boardView.setStatus(BoardActivity.this.status);
redrawRegions();
switch (BoardActivity.this.status) {
case CONFIG:
writeMessage("Entered lobby. The game master can now choose game configuration.", Color.YELLOW, -1, -1, false);
break;
case INIT:
writeMessage("Starting game...", Color.YELLOW, -1, -1, false);
saveCookie();
break;
case RUN:
initPlayerColors();
break;
}
}
});
}
@Override
public void onConfigUpdate(final List<Configurable> configList) {
Log.v("monopd", "net: Received onConfigUpdate() from MonoProtocolHandler");
nextItem: for (final Configurable toAdd : configList) {
for (int i = 0; i < BoardActivity.this.configurables.size(); i++) {
if (toAdd.getCommand().equals(BoardActivity.this.configurables.get(i).getCommand())) {
final int iClosure = i;
BoardActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
BoardActivity.this.configurables.set(iClosure, toAdd);
}
});
continue nextItem;
}
}
BoardActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
BoardActivity.this.configurables.add(toAdd);
}
});
}
BoardActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
if (boardView.isRunning()) {
boardView.drawConfigRegions(configurables, isMaster);
}
}
});
}
@Override
public void onChatMessage(final int playerId, final String author, final String text) {
Log.v("monopd", "net: Received onChatMessage() from MonoProtocolHandler");
BoardActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
if (author.length() > 0) {
writeMessage("<" + author + "> " + text, Color.WHITE, playerId, -1, false);
// handle !ping, !date, !version
if (text.startsWith("!")) {
boolean doCommand = false;
int spacePos = text.indexOf(' ');
if (spacePos > 0) {
String requestName = text.substring(spacePos).trim();
if (requestName.length() == 0 || requestName.equals(nickname)) {
doCommand = true;
}
} else {
doCommand = true;
spacePos = text.length();
}
if (doCommand) {
String command = text.substring(1, spacePos);
if (command.equals("ping")) {
sendCommand("pong");
} else if (command.equals("version")) {
sendCommand(clientName + " " + clientVersion);
} else if (command.equals("date")) {
sendCommand(DateFormat.getDateTimeInstance().format(new Date()));
}
}
}
}
}
});
}
@Override
public void onErrorMessage(final String text) {
Log.v("monopd", "net: Received onErrorMessage() from MonoProtocolHandler");
BoardActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
writeMessage("ERROR: " + text, Color.RED, -1, -1, false);
}
});
}
@Override
public void onDisplayMessage(final int estateId, final String text, final boolean clearText,
final boolean clearButtons) {
Log.v("monopd", "net: Received onDisplayMessage() from MonoProtocolHandler");
if (text.length() == 0) {
return;
}
BoardActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
writeMessage("GAME: " + text, Color.CYAN, -1, ((estateId == -1) ? 0 : estateId), clearButtons);
}
});
}
@Override
public void onPlayerListUpdate(String type, List<Player> list) {
Log.v("monopd", "net: Received onPlayerListUpdate() from MonoProtocolHandler");
/*if (type.equals("full")) {
//Log.d("monopd", "players: Full list update");
final int[] newPlayerIds = new int[4];
for (int i = 0; i < list.size() && i < 4; i++) {
newPlayerIds[i] = list.get(i).getPlayerId();
}
BoardActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
setPlayerView(newPlayerIds);
}
});
} else if (type.equals("edit")) {
// Log.d("monopd", "players: Edit " +
// list.get(0).getNick());
BoardActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
BoardActivity.this.updatePlayerView();
}
});
} else if (type.equals("add")) {
// Log.d("monopd", "players: Add " +
// list.get(0).getNick());
final int[] newPlayerIds = BoardActivity.this.playerIds;
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < 4; j++) {
final int playerId = list.get(i).getPlayerId();
if (newPlayerIds[j] == 0 || newPlayerIds[j] == playerId) {
BoardActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
writeMessage(players.get(playerId).getNick() + " joined the game.", Color.YELLOW, playerId, -1, false);
}
});
newPlayerIds[j] = playerId;
break;
}
}
}
BoardActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
BoardActivity.this.setPlayerView(newPlayerIds);
}
});
} else if (type.equals("del")) {
//Log.d("monopd", "players: Delete "
// + BoardActivity.this.players.get(list.get(0).getPlayerId()).getNick());
final int[] newPlayerIds = BoardActivity.this.playerIds;
for (int i = 0; i < list.size(); i++) {
boolean moveBack = false;
for (int j = 0; j < 4; j++) {
if (!moveBack && newPlayerIds[j] == list.get(i).getPlayerId()) {
final int playerIdClosure = newPlayerIds[j];
BoardActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
writeMessage(players.get(playerIdClosure).getNick() + " left the game.", Color.YELLOW, playerIdClosure, -1, false);
}
});
moveBack = true;
}
if (moveBack) {
newPlayerIds[j] = j < 3 ? newPlayerIds[j + 1] : 0;
}
}
}
BoardActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
BoardActivity.this.setPlayerView(newPlayerIds);
}
});
} else {
Log.w("monopd", "unrecognized playerlistupdate type: " + type + " " + list.get(0).getNick());
}*/
}
@Override
public void setHandler(Handler netHandler) {
BoardActivity.this.netHandler = netHandler;
}
@Override
public void onGameItemUpdate(GameItem item) {
if (gameItem.getGameId() == item.getGameId()) {
if (item.getPlayers() > 0) {
gameItem.setPlayers(item.getPlayers());
}
if (item.getType() != null) {
gameItem.setType(item.getType());
}
if (item.getTypeName() != null) {
gameItem.setTypeName(item.getTypeName());
}
if (item.getDescription() != null) {
gameItem.setDescription(item.getDescription());
}
gameItem.setCanJoin(item.canJoin());
}
}
});
this.setTitle(String.format(this.getString(R.string.title_activity_board), gameItem.getDescription()));
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "attachListeners"
|
"private void attachListeners() {
this.boardView.setBoardViewListener(new BoardViewListener() {
@Override
public void onConfigChange(String command, String value) {
Log.d("monopd", "BoardView tapped config change " + command + " = " + value);
Bundle state = new Bundle();
state.putString("command", command);
state.putString("value", value);
BoardActivity.this.sendToNetThread(BoardNetworkAction.MSG_CONFIG, state);
}
@Override
public void onStartGame() {
Log.d("monopd", "BoardView tapped start game");
BoardActivity.this.sendToNetThread(BoardNetworkAction.MSG_GAME_START, null);
}
@Override
public void onResize(int width, int height) {
Log.d("monopd", "BoardView resized to " + width + "," + height);
redrawRegions();
}
});
this.chatSendBox.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_ENTER) {
String text = BoardActivity.this.chatSendBox.getText().toString();
if (text.length() > 0) {
BoardActivity.this.sendCommand(text);
BoardActivity.this.chatSendBox.setText("");
}
}
return false;
}
});
this.chatList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> listView, View itemView, int position, long id) {
ChatItem item = BoardActivity.this.chatListAdapter.getItem(position);
if (item.getPlayerId() > 0) {
BoardActivity.this.boardView.overlayPlayerInfo(BoardActivity.this.players.get(item.getPlayerId()));
} else if (item.getEstateId() > 0) {
BoardActivity.this.boardView.overlayEstateInfo(BoardActivity.this.estates.get(item.getEstateId()));
}
}
});
this.netRunnable.setActivity(this, new MonoProtocolGameListener() {
@Override
public void onException(String description, Exception ex) {
Log.v("monopd", "net: Received onException() from MonoProtocolHandler");
Bundle state = new Bundle();
state.putString("error", description + ": " + ex.getMessage());
showDialog(R.id.dialog_conn_error, state);
}
@Override
public void onClose(boolean remote) {
Log.d("monopd", "net: onClose(" + remote + ")");
if (remote) {
Bundle state = new Bundle();
state.putString("error", "Connection lost.");
showDialog(R.id.dialog_conn_error, state);
}
}
@Override
public void onServer(String version) {
Log.v("monopd", "net: Received onServer() from MonoProtocolHandler");
}
@Override
public void onClient(int playerId, String cookie) {
Log.v("monopd", "net: Received onClient() from MonoProtocolHandler");
BoardActivity.this.playerId = playerId;
BoardActivity.this.cookie = cookie;
}
@Override
public void onPlayerUpdate(final int playerId, HashMap<String, String> data) {
Log.v("monopd", "net: Received onPlayerUpdate() from MonoProtocolHandler");
final HashMap<String, String> map = new HashMap<String, String>(data);
runOnUiThread(new Runnable() {
@Override
public void run() {
boolean changingLocation = false;
boolean changingMaster = false;
boolean wasMaster = false;
Player player = players.get(playerId);
if (player == null) {
player = new Player(playerId);
switch (status) {
case ERROR:
case RECONNECT:
case CREATE:
case JOIN:
// ignore playerupdates before game state change!
return;
case CONFIG:
case RUN:
case INIT:
// add to player list
for (int i = 0; i < 4; i++) {
if (playerIds[i] == 0) {
playerIds[i] = playerId;
break;
}
}
break;
}
}
for (String key : map.keySet()) {
String value = map.get(key);
XmlAttribute attr = playerAttributes.get(key);
if (attr == null) {
Log.w("monopd", "player." + key + " was unknown. Value = " + value);
} else {
if (key.equals("location")) {
changingLocation = true;
}
if (key.equals("master")) {
changingMaster = true;
wasMaster = player.isMaster();
}
attr.set(player, value);
}
}
players.put(playerId, player);
updatePlayerView();
boardView.drawEstateOwnerRegions(estates, playerIds, players);
if (changingLocation) {
animateMove(player);
}
if (changingMaster) {
if (player.getPlayerId() == BoardActivity.this.playerId && player.isMaster() != isMaster) {
isMaster = player.isMaster();
}
//if (player.isMaster() && !wasMaster) {
// writeMessage(player.getNick() + " is now game master.", Color.YELLOW, playerId, -1, false);
//}
}
}
});
}
@Override
public void onPlayerDelete(final int playerId) {
runOnUiThread(new Runnable() {
@Override
public void run() {
players.delete(playerId);
boolean deleted = false;
for (int i = 0; i < 4; i++) {
if (playerIds[i] == playerId) {
deleted = true;
}
if (deleted) {
if (i < 3) {
playerIds[i] = playerIds[i + 1];
} else {
playerIds[i] = 0;
/*for (int j = 0; j < players.size(); j++) {
int playerIdJ = players.keyAt(j);
boolean foundPlayerJ = false;
for (int k = 0; k < 4; k++) {
if (playerIdJ == playerIds[k] || players.get(playerIdJ).getNick().equals("_metaserver_")) {
foundPlayerJ = true;
}
}
if (!foundPlayerJ) {
playerIds[i] = playerIdJ;
break;
}
}*/
}
}
}
updatePlayerView();
}
});
}
@Override
public void onEstateUpdate(final int estateId, final HashMap<String, String> data) {
Log.v("monopd", "net: Received onEstateUpdate() from MonoProtocolHandler");
final HashMap<String, String> map = new HashMap<String, String>(data);
runOnUiThread(new Runnable() {
@Override
public void run() {
Estate estate;
boolean isNew = false;
if (estateId < estates.size()) {
estate = estates.get(estateId);
} else {
isNew = true;
estate = new Estate(estateId);
}
for (String key : map.keySet()) {
String value = map.get(key);
XmlAttribute attr = BoardActivity.estateAttributes.get(key);
if (attr == null) {
Log.w("monopd", "estate." + key + " was unknown. Value = " + value);
} else {
attr.set(estate, value);
}
}
if (isNew) {
if (estateId > estates.size()) {
estates.add(estates.size(), estate);
} else {
estates.add(estateId, estate);
}
} else {
estates.set(estateId, estate);
}
boardView.drawEstateOwnerRegions(estates, playerIds, players);
}
});
}
@Override
public void onGameUpdate(final int gameId, final String status) {
Log.v("monopd", "net: Received onGameUpdate() from MonoProtocolHandler");
BoardActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
if (gameId > 0) {
gameItem.setGameId(gameId);
}
BoardActivity.this.status = GameStatus.fromString(status);
BoardActivity.this.boardView.setStatus(BoardActivity.this.status);
redrawRegions();
switch (BoardActivity.this.status) {
case CONFIG:
writeMessage("Entered lobby. The game master can now choose game configuration.", Color.YELLOW, -1, -1, false);
break;
case INIT:
writeMessage("Starting game...", Color.YELLOW, -1, -1, false);
<MASK>initPlayerColors();</MASK>
saveCookie();
break;
case RUN:
break;
}
}
});
}
@Override
public void onConfigUpdate(final List<Configurable> configList) {
Log.v("monopd", "net: Received onConfigUpdate() from MonoProtocolHandler");
nextItem: for (final Configurable toAdd : configList) {
for (int i = 0; i < BoardActivity.this.configurables.size(); i++) {
if (toAdd.getCommand().equals(BoardActivity.this.configurables.get(i).getCommand())) {
final int iClosure = i;
BoardActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
BoardActivity.this.configurables.set(iClosure, toAdd);
}
});
continue nextItem;
}
}
BoardActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
BoardActivity.this.configurables.add(toAdd);
}
});
}
BoardActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
if (boardView.isRunning()) {
boardView.drawConfigRegions(configurables, isMaster);
}
}
});
}
@Override
public void onChatMessage(final int playerId, final String author, final String text) {
Log.v("monopd", "net: Received onChatMessage() from MonoProtocolHandler");
BoardActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
if (author.length() > 0) {
writeMessage("<" + author + "> " + text, Color.WHITE, playerId, -1, false);
// handle !ping, !date, !version
if (text.startsWith("!")) {
boolean doCommand = false;
int spacePos = text.indexOf(' ');
if (spacePos > 0) {
String requestName = text.substring(spacePos).trim();
if (requestName.length() == 0 || requestName.equals(nickname)) {
doCommand = true;
}
} else {
doCommand = true;
spacePos = text.length();
}
if (doCommand) {
String command = text.substring(1, spacePos);
if (command.equals("ping")) {
sendCommand("pong");
} else if (command.equals("version")) {
sendCommand(clientName + " " + clientVersion);
} else if (command.equals("date")) {
sendCommand(DateFormat.getDateTimeInstance().format(new Date()));
}
}
}
}
}
});
}
@Override
public void onErrorMessage(final String text) {
Log.v("monopd", "net: Received onErrorMessage() from MonoProtocolHandler");
BoardActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
writeMessage("ERROR: " + text, Color.RED, -1, -1, false);
}
});
}
@Override
public void onDisplayMessage(final int estateId, final String text, final boolean clearText,
final boolean clearButtons) {
Log.v("monopd", "net: Received onDisplayMessage() from MonoProtocolHandler");
if (text.length() == 0) {
return;
}
BoardActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
writeMessage("GAME: " + text, Color.CYAN, -1, ((estateId == -1) ? 0 : estateId), clearButtons);
}
});
}
@Override
public void onPlayerListUpdate(String type, List<Player> list) {
Log.v("monopd", "net: Received onPlayerListUpdate() from MonoProtocolHandler");
/*if (type.equals("full")) {
//Log.d("monopd", "players: Full list update");
final int[] newPlayerIds = new int[4];
for (int i = 0; i < list.size() && i < 4; i++) {
newPlayerIds[i] = list.get(i).getPlayerId();
}
BoardActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
setPlayerView(newPlayerIds);
}
});
} else if (type.equals("edit")) {
// Log.d("monopd", "players: Edit " +
// list.get(0).getNick());
BoardActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
BoardActivity.this.updatePlayerView();
}
});
} else if (type.equals("add")) {
// Log.d("monopd", "players: Add " +
// list.get(0).getNick());
final int[] newPlayerIds = BoardActivity.this.playerIds;
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < 4; j++) {
final int playerId = list.get(i).getPlayerId();
if (newPlayerIds[j] == 0 || newPlayerIds[j] == playerId) {
BoardActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
writeMessage(players.get(playerId).getNick() + " joined the game.", Color.YELLOW, playerId, -1, false);
}
});
newPlayerIds[j] = playerId;
break;
}
}
}
BoardActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
BoardActivity.this.setPlayerView(newPlayerIds);
}
});
} else if (type.equals("del")) {
//Log.d("monopd", "players: Delete "
// + BoardActivity.this.players.get(list.get(0).getPlayerId()).getNick());
final int[] newPlayerIds = BoardActivity.this.playerIds;
for (int i = 0; i < list.size(); i++) {
boolean moveBack = false;
for (int j = 0; j < 4; j++) {
if (!moveBack && newPlayerIds[j] == list.get(i).getPlayerId()) {
final int playerIdClosure = newPlayerIds[j];
BoardActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
writeMessage(players.get(playerIdClosure).getNick() + " left the game.", Color.YELLOW, playerIdClosure, -1, false);
}
});
moveBack = true;
}
if (moveBack) {
newPlayerIds[j] = j < 3 ? newPlayerIds[j + 1] : 0;
}
}
}
BoardActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
BoardActivity.this.setPlayerView(newPlayerIds);
}
});
} else {
Log.w("monopd", "unrecognized playerlistupdate type: " + type + " " + list.get(0).getNick());
}*/
}
@Override
public void setHandler(Handler netHandler) {
BoardActivity.this.netHandler = netHandler;
}
@Override
public void onGameItemUpdate(GameItem item) {
if (gameItem.getGameId() == item.getGameId()) {
if (item.getPlayers() > 0) {
gameItem.setPlayers(item.getPlayers());
}
if (item.getType() != null) {
gameItem.setType(item.getType());
}
if (item.getTypeName() != null) {
gameItem.setTypeName(item.getTypeName());
}
if (item.getDescription() != null) {
gameItem.setDescription(item.getDescription());
}
gameItem.setCanJoin(item.canJoin());
}
}
});
this.setTitle(String.format(this.getString(R.string.title_activity_board), gameItem.getDescription()));
}"
|
Inversion-Mutation
|
megadiff
|
"@Override
public void onGameUpdate(final int gameId, final String status) {
Log.v("monopd", "net: Received onGameUpdate() from MonoProtocolHandler");
BoardActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
if (gameId > 0) {
gameItem.setGameId(gameId);
}
BoardActivity.this.status = GameStatus.fromString(status);
BoardActivity.this.boardView.setStatus(BoardActivity.this.status);
redrawRegions();
switch (BoardActivity.this.status) {
case CONFIG:
writeMessage("Entered lobby. The game master can now choose game configuration.", Color.YELLOW, -1, -1, false);
break;
case INIT:
writeMessage("Starting game...", Color.YELLOW, -1, -1, false);
saveCookie();
break;
case RUN:
initPlayerColors();
break;
}
}
});
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onGameUpdate"
|
"@Override
public void onGameUpdate(final int gameId, final String status) {
Log.v("monopd", "net: Received onGameUpdate() from MonoProtocolHandler");
BoardActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
if (gameId > 0) {
gameItem.setGameId(gameId);
}
BoardActivity.this.status = GameStatus.fromString(status);
BoardActivity.this.boardView.setStatus(BoardActivity.this.status);
redrawRegions();
switch (BoardActivity.this.status) {
case CONFIG:
writeMessage("Entered lobby. The game master can now choose game configuration.", Color.YELLOW, -1, -1, false);
break;
case INIT:
writeMessage("Starting game...", Color.YELLOW, -1, -1, false);
<MASK>initPlayerColors();</MASK>
saveCookie();
break;
case RUN:
break;
}
}
});
}"
|
Inversion-Mutation
|
megadiff
|
"@Override
public void run() {
if (gameId > 0) {
gameItem.setGameId(gameId);
}
BoardActivity.this.status = GameStatus.fromString(status);
BoardActivity.this.boardView.setStatus(BoardActivity.this.status);
redrawRegions();
switch (BoardActivity.this.status) {
case CONFIG:
writeMessage("Entered lobby. The game master can now choose game configuration.", Color.YELLOW, -1, -1, false);
break;
case INIT:
writeMessage("Starting game...", Color.YELLOW, -1, -1, false);
saveCookie();
break;
case RUN:
initPlayerColors();
break;
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
|
"@Override
public void run() {
if (gameId > 0) {
gameItem.setGameId(gameId);
}
BoardActivity.this.status = GameStatus.fromString(status);
BoardActivity.this.boardView.setStatus(BoardActivity.this.status);
redrawRegions();
switch (BoardActivity.this.status) {
case CONFIG:
writeMessage("Entered lobby. The game master can now choose game configuration.", Color.YELLOW, -1, -1, false);
break;
case INIT:
writeMessage("Starting game...", Color.YELLOW, -1, -1, false);
<MASK>initPlayerColors();</MASK>
saveCookie();
break;
case RUN:
break;
}
}"
|
Inversion-Mutation
|
megadiff
|
"public boolean readRecord(PactRecord target, byte[] bytes, int offset, int numBytes) {
PactString str = this.theString;
if (this.ascii) {
str.setValueAscii(bytes, offset, numBytes);
}
else {
ByteBuffer byteWrapper = this.byteWrapper;
if (bytes != byteWrapper.array()) {
byteWrapper = ByteBuffer.wrap(bytes, 0, bytes.length);
this.byteWrapper = byteWrapper;
}
byteWrapper.limit(offset + numBytes);
byteWrapper.position(offset);
try {
CharBuffer result = this.decoder.decode(byteWrapper);
str.setValue(result);
}
catch (CharacterCodingException e) {
byte[] copy = new byte[numBytes];
System.arraycopy(bytes, offset, copy, 0, numBytes);
LOG.warn("Line could not be encoded: " + Arrays.toString(copy), e);
return false;
}
}
target.clear();
target.setField(this.pos, str);
return true;
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "readRecord"
|
"public boolean readRecord(PactRecord target, byte[] bytes, int offset, int numBytes) {
PactString str = this.theString;
if (this.ascii) {
str.setValueAscii(bytes, offset, numBytes);
}
else {
ByteBuffer byteWrapper = this.byteWrapper;
if (bytes != byteWrapper.array()) {
byteWrapper = ByteBuffer.wrap(bytes, 0, bytes.length);
this.byteWrapper = byteWrapper;
}
<MASK>byteWrapper.position(offset);</MASK>
byteWrapper.limit(offset + numBytes);
try {
CharBuffer result = this.decoder.decode(byteWrapper);
str.setValue(result);
}
catch (CharacterCodingException e) {
byte[] copy = new byte[numBytes];
System.arraycopy(bytes, offset, copy, 0, numBytes);
LOG.warn("Line could not be encoded: " + Arrays.toString(copy), e);
return false;
}
}
target.clear();
target.setField(this.pos, str);
return true;
}"
|
Inversion-Mutation
|
megadiff
|
"public Module(ModuleView view, ModuleConfiguration moduleConfiguration) {
this.identifier = moduleConfiguration.getBaseIdentifier();
this.view = view;
this.properties = new ModuleProperties(this);
inputConnectedPoints = new ObservableList<>(this);
outputConnectedPoints = new ObservableList<>(this);
initializeDefaultValues();
initialize();
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "Module"
|
"public Module(ModuleView view, ModuleConfiguration moduleConfiguration) {
this.identifier = moduleConfiguration.getBaseIdentifier();
this.view = view;
this.properties = new ModuleProperties(this);
inputConnectedPoints = new ObservableList<>(this);
outputConnectedPoints = new ObservableList<>(this);
<MASK>initialize();</MASK>
initializeDefaultValues();
}"
|
Inversion-Mutation
|
megadiff
|
"public static void main(String[] args)
{
// Configurable params
int nrChiefs = 1;
int nrTeams = 5;
int nrThievesPerTeam = 3;
int nrTotalThieves = 7;
int nrRooms = 5;
int maxDistanceBetweenThieves = 1;
int maxDistanceBetweenRoomAndOutside = 10;
int maxPowerPerThief = 5;
int maxCanvasInRoom = 20;
String logFileName = "log.txt";
// Initializing the necessary entities
Random random = new Random();
Logger logger = new Logger(logFileName);
Team[] teams = new Team[nrTeams];
for (int x = 0; x < nrTeams; x++) {
teams[x] = new Team(x + 1, nrThievesPerTeam);
}
Room[] rooms = new Room[nrRooms];
for (int x = 0; x < nrRooms; x++) {
rooms[x] = new Room(x + 1, random.nextInt(maxCanvasInRoom - 1) + 1, new Corridor((random.nextInt(maxDistanceBetweenRoomAndOutside - 1) + 1), maxDistanceBetweenThieves, logger), logger);
}
SharedSite site = new SharedSite(rooms, teams, logger, (nrChiefs > 1));
Thief[] thieves = new Thief[nrTotalThieves];
for (int x = 0; x < nrTotalThieves; x++) {
Thief thief = new Thief(x + 1, random.nextInt(maxPowerPerThief - 1) + 1, site);
thieves[x] = thief;
}
Chief[] chiefs = new Chief[nrChiefs];
for (int x = 0; x < nrChiefs; x++) {
Chief chief = new Chief(x + 1, site);
chiefs[x] = chief;
}
// Initialize the logger
logger.initialize(chiefs, thieves, teams, rooms);
// Start the threads
for (int x = 0; x < nrTotalThieves; x++) {
thieves[x].start();
}
for (int x = 0; x < nrChiefs; x++) {
chiefs[x].start();
}
// Wait for the chiefs to join
for (int x = 0; x < nrChiefs; x++) {
try {
chiefs[x].join();
} catch (InterruptedException e) {}
}
logger.terminateLog(site.getNrCollectedCanvas());
System.out.println("Program terminated successfully, please check the log file.");
System.exit(0);
}"
|
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)
{
// Configurable params
int nrChiefs = 1;
int nrTeams = 5;
int nrThievesPerTeam = 3;
int nrTotalThieves = 7;
int nrRooms = 5;
int maxDistanceBetweenThieves = 1;
int maxDistanceBetweenRoomAndOutside = 10;
int maxPowerPerThief = 5;
int maxCanvasInRoom = 20;
String logFileName = "log.txt";
Random random = new Random();
Logger logger = new Logger(logFileName);
<MASK>// Initializing the necessary entities</MASK>
Team[] teams = new Team[nrTeams];
for (int x = 0; x < nrTeams; x++) {
teams[x] = new Team(x + 1, nrThievesPerTeam);
}
Room[] rooms = new Room[nrRooms];
for (int x = 0; x < nrRooms; x++) {
rooms[x] = new Room(x + 1, random.nextInt(maxCanvasInRoom - 1) + 1, new Corridor((random.nextInt(maxDistanceBetweenRoomAndOutside - 1) + 1), maxDistanceBetweenThieves, logger), logger);
}
SharedSite site = new SharedSite(rooms, teams, logger, (nrChiefs > 1));
Thief[] thieves = new Thief[nrTotalThieves];
for (int x = 0; x < nrTotalThieves; x++) {
Thief thief = new Thief(x + 1, random.nextInt(maxPowerPerThief - 1) + 1, site);
thieves[x] = thief;
}
Chief[] chiefs = new Chief[nrChiefs];
for (int x = 0; x < nrChiefs; x++) {
Chief chief = new Chief(x + 1, site);
chiefs[x] = chief;
}
// Initialize the logger
logger.initialize(chiefs, thieves, teams, rooms);
// Start the threads
for (int x = 0; x < nrTotalThieves; x++) {
thieves[x].start();
}
for (int x = 0; x < nrChiefs; x++) {
chiefs[x].start();
}
// Wait for the chiefs to join
for (int x = 0; x < nrChiefs; x++) {
try {
chiefs[x].join();
} catch (InterruptedException e) {}
}
logger.terminateLog(site.getNrCollectedCanvas());
System.out.println("Program terminated successfully, please check the log file.");
System.exit(0);
}"
|
Inversion-Mutation
|
megadiff
|
"boolean save() {
createHandler();
String title = mTitle.getText().toString().trim();
String unfilteredUrl;
if (mIsUrlEditable) {
unfilteredUrl =
BrowserActivity.fixUrl(mAddress.getText().toString());
} else {
unfilteredUrl = mOriginalUrl;
}
boolean emptyTitle = title.length() == 0;
boolean emptyUrl = unfilteredUrl.trim().length() == 0;
Resources r = getResources();
if (emptyTitle || emptyUrl) {
if (emptyTitle) {
mTitle.setError(r.getText(R.string.bookmark_needs_title));
}
if (emptyUrl) {
if (mIsUrlEditable) {
mAddress.setError(r.getText(R.string.bookmark_needs_url));
} else {
Toast.makeText(AddBookmarkPage.this, R.string.bookmark_needs_url,
Toast.LENGTH_LONG).show();
}
}
return false;
}
String url = unfilteredUrl.trim();
try {
// We allow bookmarks with a javascript: scheme, but these will in most cases
// fail URI parsing, so don't try it if that's the kind of bookmark we have.
if (!url.toLowerCase().startsWith("javascript:")) {
URI uriObj = new URI(url);
String scheme = uriObj.getScheme();
if (!Bookmarks.urlHasAcceptableScheme(url)) {
// If the scheme was non-null, let the user know that we
// can't save their bookmark. If it was null, we'll assume
// they meant http when we parse it in the WebAddress class.
if (scheme != null) {
if (mIsUrlEditable) {
mAddress.setError(r.getText(R.string.bookmark_cannot_save_url));
} else {
Toast.makeText(AddBookmarkPage.this, R.string.bookmark_cannot_save_url,
Toast.LENGTH_LONG).show();
}
return false;
}
WebAddress address;
try {
address = new WebAddress(unfilteredUrl);
} catch (ParseException e) {
throw new URISyntaxException("", "");
}
if (address.mHost.length() == 0) {
throw new URISyntaxException("", "");
}
url = address.toString();
}
}
} catch (URISyntaxException e) {
if (mIsUrlEditable) {
mAddress.setError(r.getText(R.string.bookmark_url_not_valid));
} else {
Toast.makeText(AddBookmarkPage.this, R.string.bookmark_url_not_valid,
Toast.LENGTH_LONG).show();
}
return false;
}
if (mEditingExisting) {
mMap.putString("title", title);
mMap.putString("url", url);
mMap.putBoolean("invalidateThumbnail", !url.equals(mOriginalUrl));
setResult(RESULT_OK, (new Intent()).setAction(
getIntent().toString()).putExtras(mMap));
} else {
// Post a message to write to the DB.
Bundle bundle = new Bundle();
bundle.putString("title", title);
bundle.putString("url", url);
bundle.putParcelable("thumbnail", mThumbnail);
bundle.putBoolean("invalidateThumbnail", !url.equals(mOriginalUrl));
bundle.putString("touchIconUrl", mTouchIconUrl);
Message msg = Message.obtain(mHandler, SAVE_BOOKMARK);
msg.setData(bundle);
// Start a new thread so as to not slow down the UI
Thread t = new Thread(new SaveBookmarkRunnable(msg));
t.start();
setResult(RESULT_OK);
LogTag.logBookmarkAdded(url, "bookmarkview");
}
return true;
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "save"
|
"boolean save() {
createHandler();
String title = mTitle.getText().toString().trim();
String unfilteredUrl;
if (mIsUrlEditable) {
unfilteredUrl =
BrowserActivity.fixUrl(mAddress.getText().toString());
} else {
unfilteredUrl = mOriginalUrl;
}
boolean emptyTitle = title.length() == 0;
boolean emptyUrl = unfilteredUrl.trim().length() == 0;
Resources r = getResources();
if (emptyTitle || emptyUrl) {
if (emptyTitle) {
mTitle.setError(r.getText(R.string.bookmark_needs_title));
}
if (emptyUrl) {
if (mIsUrlEditable) {
mAddress.setError(r.getText(R.string.bookmark_needs_url));
} else {
Toast.makeText(AddBookmarkPage.this, R.string.bookmark_needs_url,
Toast.LENGTH_LONG).show();
}
<MASK>return false;</MASK>
}
}
String url = unfilteredUrl.trim();
try {
// We allow bookmarks with a javascript: scheme, but these will in most cases
// fail URI parsing, so don't try it if that's the kind of bookmark we have.
if (!url.toLowerCase().startsWith("javascript:")) {
URI uriObj = new URI(url);
String scheme = uriObj.getScheme();
if (!Bookmarks.urlHasAcceptableScheme(url)) {
// If the scheme was non-null, let the user know that we
// can't save their bookmark. If it was null, we'll assume
// they meant http when we parse it in the WebAddress class.
if (scheme != null) {
if (mIsUrlEditable) {
mAddress.setError(r.getText(R.string.bookmark_cannot_save_url));
} else {
Toast.makeText(AddBookmarkPage.this, R.string.bookmark_cannot_save_url,
Toast.LENGTH_LONG).show();
}
<MASK>return false;</MASK>
}
WebAddress address;
try {
address = new WebAddress(unfilteredUrl);
} catch (ParseException e) {
throw new URISyntaxException("", "");
}
if (address.mHost.length() == 0) {
throw new URISyntaxException("", "");
}
url = address.toString();
}
}
} catch (URISyntaxException e) {
if (mIsUrlEditable) {
mAddress.setError(r.getText(R.string.bookmark_url_not_valid));
} else {
Toast.makeText(AddBookmarkPage.this, R.string.bookmark_url_not_valid,
Toast.LENGTH_LONG).show();
}
<MASK>return false;</MASK>
}
if (mEditingExisting) {
mMap.putString("title", title);
mMap.putString("url", url);
mMap.putBoolean("invalidateThumbnail", !url.equals(mOriginalUrl));
setResult(RESULT_OK, (new Intent()).setAction(
getIntent().toString()).putExtras(mMap));
} else {
// Post a message to write to the DB.
Bundle bundle = new Bundle();
bundle.putString("title", title);
bundle.putString("url", url);
bundle.putParcelable("thumbnail", mThumbnail);
bundle.putBoolean("invalidateThumbnail", !url.equals(mOriginalUrl));
bundle.putString("touchIconUrl", mTouchIconUrl);
Message msg = Message.obtain(mHandler, SAVE_BOOKMARK);
msg.setData(bundle);
// Start a new thread so as to not slow down the UI
Thread t = new Thread(new SaveBookmarkRunnable(msg));
t.start();
setResult(RESULT_OK);
LogTag.logBookmarkAdded(url, "bookmarkview");
}
return true;
}"
|
Inversion-Mutation
|
megadiff
|
"@Override
public void run() {
boolean closed = false;
String packet;
try {
mock.waitForStartup();
String http = "" + mock.getHttpPort() + '\0';
output.write(http.getBytes());
output.flush();
} catch (InterruptedException ex) {
closed = true;
} catch (IOException ex) {
closed = true;
}
while (!closed) {
try {
packet = input.readLine();
if (packet == null) {
closed = true;
} else if (mock != null) {
dispatchMockCommand(packet);
}
} catch (IOException e) {
// not exactly true, but who cares..
closed = true;
}
}
if (terminate) {
System.exit(1);
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
|
"@Override
public void run() {
boolean closed = false;
String packet;
<MASK>String http = "" + mock.getHttpPort() + '\0';</MASK>
try {
mock.waitForStartup();
output.write(http.getBytes());
output.flush();
} catch (InterruptedException ex) {
closed = true;
} catch (IOException ex) {
closed = true;
}
while (!closed) {
try {
packet = input.readLine();
if (packet == null) {
closed = true;
} else if (mock != null) {
dispatchMockCommand(packet);
}
} catch (IOException e) {
// not exactly true, but who cares..
closed = true;
}
}
if (terminate) {
System.exit(1);
}
}"
|
Inversion-Mutation
|
megadiff
|
"private void showPreviews(final View anchor, int start, int end) {
//check first if it's already open
final PopupWindow window = (PopupWindow) anchor.getTag();
if (window != null) return;
Resources resources = getResources();
Workspace workspace = mWorkspace;
CellLayout cell = ((CellLayout) workspace.getChildAt(start));
float max;
ViewGroup preview;
if(newPreviews){
max = 3;
preview= new PreviewsHolder(this);
}else{
max = workspace.getChildCount();
preview = new LinearLayout(this);
}
Rect r = new Rect();
//ADW: seems sometimes this throws an out of memory error.... so...
try{
resources.getDrawable(R.drawable.preview_background).getPadding(r);
}catch(OutOfMemoryError e){}
int extraW = (int) ((r.left + r.right) * max);
int extraH = r.top + r.bottom;
int aW = cell.getWidth() - extraW;
float w = aW / max;
int width = cell.getWidth();
int height = cell.getHeight();
int x = cell.getLeftPadding();
int y = cell.getTopPadding();
//width -= (x + cell.getRightPadding());
//height -= (y + cell.getBottomPadding());
if(width!=0 && height!=0){
showingPreviews=true;
float scale = w / width;
int count = end - start;
final float sWidth = width * scale;
float sHeight = height * scale;
PreviewTouchHandler handler = new PreviewTouchHandler(anchor);
ArrayList<Bitmap> bitmaps = new ArrayList<Bitmap>(count);
for (int i = start; i < end; i++) {
ImageView image = new ImageView(this);
cell = (CellLayout) workspace.getChildAt(i);
Bitmap bitmap = Bitmap.createBitmap((int) sWidth, (int) sHeight,
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
c.scale(scale, scale);
c.translate(-cell.getLeftPadding(), -cell.getTopPadding());
cell.dispatchDraw(c);
image.setBackgroundDrawable(resources.getDrawable(R.drawable.preview_background));
image.setImageBitmap(bitmap);
image.setTag(i);
image.setOnClickListener(handler);
image.setOnFocusChangeListener(handler);
image.setFocusable(true);
if (i == mWorkspace.getCurrentScreen()) image.requestFocus();
preview.addView(image,
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
bitmaps.add(bitmap);
}
PopupWindow p = new PopupWindow(this);
p.setContentView(preview);
if(newPreviews){
p.setWidth(width);
p.setHeight(height);
p.setAnimationStyle(R.style.AnimationPreview);
}else{
p.setWidth((int) (sWidth * count + extraW));
p.setHeight((int) (sHeight + extraH));
p.setAnimationStyle(R.style.AnimationPreview);
}
p.setOutsideTouchable(true);
p.setFocusable(true);
p.setBackgroundDrawable(new ColorDrawable(0));
if(newPreviews){
p.showAtLocation(anchor, Gravity.BOTTOM, 0, 0);
}else{
p.showAsDropDown(anchor, 0, 0);
}
p.setOnDismissListener(new PopupWindow.OnDismissListener() {
public void onDismiss() {
dismissPreview(anchor);
}
});
anchor.setTag(p);
anchor.setTag(R.id.workspace, preview);
anchor.setTag(R.id.icon, bitmaps);
if(fullScreenPreviews){
hideDesktop(true);
mWorkspace.lock();
mDesktopLocked=true;
mWorkspace.invalidate();
}
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "showPreviews"
|
"private void showPreviews(final View anchor, int start, int end) {
//check first if it's already open
final PopupWindow window = (PopupWindow) anchor.getTag();
if (window != null) return;
<MASK>showingPreviews=true;</MASK>
Resources resources = getResources();
Workspace workspace = mWorkspace;
CellLayout cell = ((CellLayout) workspace.getChildAt(start));
float max;
ViewGroup preview;
if(newPreviews){
max = 3;
preview= new PreviewsHolder(this);
}else{
max = workspace.getChildCount();
preview = new LinearLayout(this);
}
Rect r = new Rect();
//ADW: seems sometimes this throws an out of memory error.... so...
try{
resources.getDrawable(R.drawable.preview_background).getPadding(r);
}catch(OutOfMemoryError e){}
int extraW = (int) ((r.left + r.right) * max);
int extraH = r.top + r.bottom;
int aW = cell.getWidth() - extraW;
float w = aW / max;
int width = cell.getWidth();
int height = cell.getHeight();
int x = cell.getLeftPadding();
int y = cell.getTopPadding();
//width -= (x + cell.getRightPadding());
//height -= (y + cell.getBottomPadding());
if(width!=0 && height!=0){
float scale = w / width;
int count = end - start;
final float sWidth = width * scale;
float sHeight = height * scale;
PreviewTouchHandler handler = new PreviewTouchHandler(anchor);
ArrayList<Bitmap> bitmaps = new ArrayList<Bitmap>(count);
for (int i = start; i < end; i++) {
ImageView image = new ImageView(this);
cell = (CellLayout) workspace.getChildAt(i);
Bitmap bitmap = Bitmap.createBitmap((int) sWidth, (int) sHeight,
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
c.scale(scale, scale);
c.translate(-cell.getLeftPadding(), -cell.getTopPadding());
cell.dispatchDraw(c);
image.setBackgroundDrawable(resources.getDrawable(R.drawable.preview_background));
image.setImageBitmap(bitmap);
image.setTag(i);
image.setOnClickListener(handler);
image.setOnFocusChangeListener(handler);
image.setFocusable(true);
if (i == mWorkspace.getCurrentScreen()) image.requestFocus();
preview.addView(image,
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
bitmaps.add(bitmap);
}
PopupWindow p = new PopupWindow(this);
p.setContentView(preview);
if(newPreviews){
p.setWidth(width);
p.setHeight(height);
p.setAnimationStyle(R.style.AnimationPreview);
}else{
p.setWidth((int) (sWidth * count + extraW));
p.setHeight((int) (sHeight + extraH));
p.setAnimationStyle(R.style.AnimationPreview);
}
p.setOutsideTouchable(true);
p.setFocusable(true);
p.setBackgroundDrawable(new ColorDrawable(0));
if(newPreviews){
p.showAtLocation(anchor, Gravity.BOTTOM, 0, 0);
}else{
p.showAsDropDown(anchor, 0, 0);
}
p.setOnDismissListener(new PopupWindow.OnDismissListener() {
public void onDismiss() {
dismissPreview(anchor);
}
});
anchor.setTag(p);
anchor.setTag(R.id.workspace, preview);
anchor.setTag(R.id.icon, bitmaps);
if(fullScreenPreviews){
hideDesktop(true);
mWorkspace.lock();
mDesktopLocked=true;
mWorkspace.invalidate();
}
}
}"
|
Inversion-Mutation
|
megadiff
|
"@Test
public void test()
{
boolean staticSet = false;
ORB myORB = null;
RootOA myOA = null;
Map<String, String> properties = opPropertyManager.getOrbPortabilityEnvironmentBean().getOrbInitializationProperties();
properties.put( PostInitLoader.generateORBPropertyName("com.arjuna.orbportability.orb", ORB_NAME), "com.arjuna.ats.jts.utils.ORBSetup");
opPropertyManager.getOrbPortabilityEnvironmentBean().setOrbInitializationProperties(properties);
try
{
myORB = ORB.getInstance(ORB_NAME);
myOA = OA.getRootOA(myORB);
if (staticSet)
{
ORBManager.setORB(myORB);
}
try
{
myORB.initORB(new String[] {}, null);
myOA.initOA();
assertEquals(myORB, ORBManager.getORB());
}
catch (FatalError e)
{
if (staticSet)
{
System.out.println("FatalError thrown as expected");
}
else
{
fail("Error: "+e);
e.printStackTrace(System.err);
}
}
myOA.destroy();
myORB.destroy();
}
catch (Throwable e)
{
fail("Error: "+e);
e.printStackTrace(System.err);
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "test"
|
"@Test
public void test()
{
boolean staticSet = false;
ORB myORB = null;
RootOA myOA = null;
Map<String, String> properties = opPropertyManager.getOrbPortabilityEnvironmentBean().getOrbInitializationProperties();
properties.put( PostInitLoader.generateORBPropertyName("com.arjuna.orbportability.orb", ORB_NAME), "com.arjuna.ats.jts.utils.ORBSetup");
opPropertyManager.getOrbPortabilityEnvironmentBean().setOrbInitializationProperties(properties);
try
{
myORB = ORB.getInstance(ORB_NAME);
myOA = OA.getRootOA(myORB);
if (staticSet)
{
ORBManager.setORB(myORB);
}
try
{
myORB.initORB(new String[] {}, null);
myOA.initOA();
assertEquals(myORB, ORBManager.getORB());
}
catch (FatalError e)
{
if (staticSet)
{
System.out.println("FatalError thrown as expected");
}
else
{
fail("Error: "+e);
e.printStackTrace(System.err);
}
}
<MASK>myORB.destroy();</MASK>
myOA.destroy();
}
catch (Throwable e)
{
fail("Error: "+e);
e.printStackTrace(System.err);
}
}"
|
Inversion-Mutation
|
megadiff
|
"@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tymy_list);
app = (TymyReader) getApplication();
tlu = new TymyListUtil();
pb = (ProgressBar) findViewById(R.id.progress_bar);
TymyListActivity oldState = (TymyListActivity) getLastNonConfigurationInstance();
if (oldState == null) {
// activity was started => load configuration
app.loadTymyCfg();
tymyPrefList = app.getTymyPrefList();
adapter = new SimpleAdapter(this, tymyList, R.layout.two_line_list_discs, from, to);
refreshListView();
//refresh discussions from web
// reloadTymyDsList(); // reload i seznamu diskusi, muze byt pomaljesi
reloadTymyNewItems(); // reload pouze poctu novych prispevku
} else {
// Configuration was changed, reload data
tymyList = oldState.tymyList;
tymyPrefList = oldState.tymyPrefList;
updateNewItemsTymy = oldState.updateNewItemsTymy;
// pb = oldState.pb;
// pb.setVisibility(oldState.pb.getVisibility());
adapter = oldState.adapter;
refreshListView();
}
// Set-up adapter for tymyList
lv = getListView();
lv.setAdapter(adapter);
registerForContextMenu(getListView());
if (!app.isOnline()) {
Toast.makeText(this, R.string.no_connection, Toast.LENGTH_LONG).show();
}
}"
|
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);
setContentView(R.layout.tymy_list);
app = (TymyReader) getApplication();
tlu = new TymyListUtil();
TymyListActivity oldState = (TymyListActivity) getLastNonConfigurationInstance();
if (oldState == null) {
// activity was started => load configuration
app.loadTymyCfg();
tymyPrefList = app.getTymyPrefList();
<MASK>pb = (ProgressBar) findViewById(R.id.progress_bar);</MASK>
adapter = new SimpleAdapter(this, tymyList, R.layout.two_line_list_discs, from, to);
refreshListView();
//refresh discussions from web
// reloadTymyDsList(); // reload i seznamu diskusi, muze byt pomaljesi
reloadTymyNewItems(); // reload pouze poctu novych prispevku
} else {
// Configuration was changed, reload data
tymyList = oldState.tymyList;
tymyPrefList = oldState.tymyPrefList;
updateNewItemsTymy = oldState.updateNewItemsTymy;
// pb = oldState.pb;
// pb.setVisibility(oldState.pb.getVisibility());
adapter = oldState.adapter;
refreshListView();
}
// Set-up adapter for tymyList
lv = getListView();
lv.setAdapter(adapter);
registerForContextMenu(getListView());
if (!app.isOnline()) {
Toast.makeText(this, R.string.no_connection, Toast.LENGTH_LONG).show();
}
}"
|
Inversion-Mutation
|
megadiff
|
"@Override
public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) {
if (!(sender instanceof Player)) {
return true;
}
if (!sender.hasPermission("authme." + label.toLowerCase())) {
sender.sendMessage(m._("no_perm"));
return true;
}
Player player = (Player) sender;
String name = player.getName().toLowerCase();
String ip = player.getAddress().getAddress().getHostAddress();
if (PlayerCache.getInstance().isAuthenticated(name)) {
player.sendMessage(m._("logged_in"));
return true;
}
if (args.length == 0) {
player.sendMessage(m._("usage_log"));
return true;
}
if (!database.isAuthAvailable(player.getName().toLowerCase())) {
player.sendMessage(m._("user_unknown"));
return true;
}
String hash = database.getAuth(name).getHash();
try {
if (PasswordSecurity.comparePasswordWithHash(args[0], hash)) {
PlayerAuth auth = new PlayerAuth(name, hash, ip, new Date());
database.updateSession(auth);
PlayerCache.getInstance().addPlayer(auth);
LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name);
if (limbo != null) {
player.setGameMode(GameMode.getByValue(limbo.getGameMode()));
player.getInventory().setContents(limbo.getInventory());
player.getInventory().setArmorContents(limbo.getArmour());
if (settings.isTeleportToSpawnEnabled()) {
player.teleport(limbo.getLoc());
}
sender.getServer().getScheduler().cancelTask(limbo.getTimeoutTaskId());
LimboCache.getInstance().deleteLimboPlayer(name);
}
player.sendMessage(m._("login"));
ConsoleLogger.info(player.getDisplayName() + " logged in!");
} else {
ConsoleLogger.info(player.getDisplayName() + " used the wrong password");
if (settings.isKickOnWrongPasswordEnabled()) {
player.kickPlayer(m._("wrong_pwd"));
} else {
player.sendMessage(m._("wrong_pwd"));
}
}
} catch (NoSuchAlgorithmException ex) {
ConsoleLogger.showError(ex.getMessage());
sender.sendMessage(m._("error"));
}
return true;
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCommand"
|
"@Override
public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) {
if (!(sender instanceof Player)) {
return true;
}
if (!sender.hasPermission("authme." + label.toLowerCase())) {
sender.sendMessage(m._("no_perm"));
return true;
}
Player player = (Player) sender;
String name = player.getName().toLowerCase();
String ip = player.getAddress().getAddress().getHostAddress();
if (PlayerCache.getInstance().isAuthenticated(name)) {
player.sendMessage(m._("logged_in"));
return true;
}
if (args.length == 0) {
player.sendMessage(m._("usage_log"));
return true;
}
if (!database.isAuthAvailable(player.getName().toLowerCase())) {
player.sendMessage(m._("user_unknown"));
return true;
}
String hash = database.getAuth(name).getHash();
try {
if (PasswordSecurity.comparePasswordWithHash(args[0], hash)) {
PlayerAuth auth = new PlayerAuth(name, hash, ip, new Date());
database.updateSession(auth);
PlayerCache.getInstance().addPlayer(auth);
LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name);
if (limbo != null) {
player.getInventory().setContents(limbo.getInventory());
player.getInventory().setArmorContents(limbo.getArmour());
<MASK>player.setGameMode(GameMode.getByValue(limbo.getGameMode()));</MASK>
if (settings.isTeleportToSpawnEnabled()) {
player.teleport(limbo.getLoc());
}
sender.getServer().getScheduler().cancelTask(limbo.getTimeoutTaskId());
LimboCache.getInstance().deleteLimboPlayer(name);
}
player.sendMessage(m._("login"));
ConsoleLogger.info(player.getDisplayName() + " logged in!");
} else {
ConsoleLogger.info(player.getDisplayName() + " used the wrong password");
if (settings.isKickOnWrongPasswordEnabled()) {
player.kickPlayer(m._("wrong_pwd"));
} else {
player.sendMessage(m._("wrong_pwd"));
}
}
} catch (NoSuchAlgorithmException ex) {
ConsoleLogger.showError(ex.getMessage());
sender.sendMessage(m._("error"));
}
return true;
}"
|
Inversion-Mutation
|
megadiff
|
"@Override
public IEnergyNetwork merge(IEnergyNetwork network)
{
IEnergyNetwork newNetwork = super.merge(network);
if (newNetwork != null)
{
long newBuffer = getBuffer() + ((EnergyNetwork) network).getBuffer();
newNetwork.setBuffer(newBuffer);
return newNetwork;
}
return null;
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "merge"
|
"@Override
public IEnergyNetwork merge(IEnergyNetwork network)
{
<MASK>long newBuffer = getBuffer() + ((EnergyNetwork) network).getBuffer();</MASK>
IEnergyNetwork newNetwork = super.merge(network);
if (newNetwork != null)
{
newNetwork.setBuffer(newBuffer);
return newNetwork;
}
return null;
}"
|
Inversion-Mutation
|
megadiff
|
"public Table addRemoteTable(String remoteSchema, String remoteTableName, String baseSchema, Properties properties, Pattern excludeIndirectColumns, Pattern excludeColumns) throws SQLException {
String fullName = remoteSchema + "." + remoteTableName;
Table remoteTable = remoteTables.get(fullName);
if (remoteTable == null) {
if (properties != null)
remoteTable = new RemoteTable(this, remoteSchema, remoteTableName, baseSchema, properties, excludeIndirectColumns, excludeColumns);
else
remoteTable = new ExplicitRemoteTable(this, remoteSchema, remoteTableName, baseSchema);
logger.fine("Adding remote table " + fullName);
remoteTables.put(fullName, remoteTable);
remoteTable.connectForeignKeys(tables, excludeIndirectColumns, excludeColumns);
}
return remoteTable;
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addRemoteTable"
|
"public Table addRemoteTable(String remoteSchema, String remoteTableName, String baseSchema, Properties properties, Pattern excludeIndirectColumns, Pattern excludeColumns) throws SQLException {
String fullName = remoteSchema + "." + remoteTableName;
Table remoteTable = remoteTables.get(fullName);
if (remoteTable == null) {
if (properties != null)
remoteTable = new RemoteTable(this, remoteSchema, remoteTableName, baseSchema, properties, excludeIndirectColumns, excludeColumns);
else
remoteTable = new ExplicitRemoteTable(this, remoteSchema, remoteTableName, baseSchema);
logger.fine("Adding remote table " + fullName);
<MASK>remoteTable.connectForeignKeys(tables, excludeIndirectColumns, excludeColumns);</MASK>
remoteTables.put(fullName, remoteTable);
}
return remoteTable;
}"
|
Inversion-Mutation
|
megadiff
|
"public reportHTML (HashMap<BlackboardArtifact,ArrayList<BlackboardAttribute>> report){
try{
Case currentCase = Case.getCurrentCase(); // get the most updated case
SleuthkitCase skCase = currentCase.getSleuthkitCase();
String caseName = currentCase.getName();
Integer imagecount = currentCase.getImageIDs().length;
Integer filesystemcount = currentCase.getRootObjectsCount();
DateFormat datetimeFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
Date date = new Date();
String datetime = datetimeFormat.format(date);
String datenotime = dateFormat.format(date);
//Add html header info
formatted_Report.append("<html><head>Autopsy Report for Case:").append(caseName).append("</head><body><div id=\"main\"><div id=\"content\">");
// Add summary information now
formatted_Report.append("<h1>Report for Case: ").append(caseName).append("</h1>");
formatted_Report.append("<h3>Case Summary</h3><p>XML Report Generated by Autopsy 3 on ").append(datetime).append("<br /><ul>");
formatted_Report.append("<li># of Images: ").append(imagecount).append("</li>");
formatted_Report.append("<li>FileSystems: ").append(filesystemcount).append("</li>");
StringBuilder nodeGen = new StringBuilder("<h3>General Information</h3>");
StringBuilder nodeWebBookmark = new StringBuilder("<h3>Web Bookmarks</h3>");
StringBuilder nodeWebCookie = new StringBuilder("<h3>Web Cookies</h3>");
StringBuilder nodeWebHistory = new StringBuilder("<h3>Web History</h3>");
StringBuilder nodeWebDownload = new StringBuilder("<h3>Web Downloads</h3>");
StringBuilder nodeRecentObjects = new StringBuilder("<h3>Recent Documents</h3>");
StringBuilder nodeTrackPoint = new StringBuilder("<h3>Track Points</h3>");
StringBuilder nodeInstalled = new StringBuilder("<h3>Installed Programs</h3>");
StringBuilder nodeKeyword = new StringBuilder("<h3>Keyword Search Hits</h3>");
StringBuilder nodeHash = new StringBuilder("<h3>Hashset Hits</h3>");
for (Entry<BlackboardArtifact,ArrayList<BlackboardAttribute>> entry : report.entrySet()) {
StringBuilder artifact = new StringBuilder("<p>Artifact");
Long objId = entry.getKey().getObjectID();
Content cont = skCase.getContentById(objId);
Long filesize = cont.getSize();
artifact.append(" ID: " + objId.toString());
artifact.append("<br /> Name: <strong>").append(cont.accept(new NameVisitor())).append("</strong>");
artifact.append("<br />Path: ").append(cont.accept(new PathVisitor()));
artifact.append("<br /> Size: ").append(filesize.toString());
artifact.append("</p><ul style=\"list-style-type: none;\">");
// Get all the attributes for this guy
for (BlackboardAttribute tempatt : entry.getValue())
{
StringBuilder attribute = new StringBuilder("<li style=\"list-style-type: none;\">Type: ").append(tempatt.getAttributeTypeDisplayName()).append("</li>");
attribute.append("<li style=\"list-style-type: none;\">Value: ").append(tempatt.getValueString()).append("</li>");
attribute.append("<li style=\"list-style-type: none;\"> Context: ").append(tempatt.getContext()).append("</li>");
artifact.append(attribute);
}
artifact.append("</ul>");
if(entry.getKey().getArtifactTypeID() == 1){
nodeGen.append(artifact);
}
if(entry.getKey().getArtifactTypeID() == 2){
nodeWebBookmark.append(artifact);
}
if(entry.getKey().getArtifactTypeID() == 3){
nodeWebCookie.append(artifact);
}
if(entry.getKey().getArtifactTypeID() == 4){
nodeWebHistory.append(artifact);
}
if(entry.getKey().getArtifactTypeID() == 5){
nodeWebDownload.append(artifact);
}
if(entry.getKey().getArtifactTypeID() == 6){
nodeRecentObjects.append(artifact);
}
if(entry.getKey().getArtifactTypeID() == 7){
nodeTrackPoint.append(artifact);
}
if(entry.getKey().getArtifactTypeID() == 8){
nodeInstalled.append(artifact);
}
if(entry.getKey().getArtifactTypeID() == 9){
nodeKeyword.append(artifact);
}
if(entry.getKey().getArtifactTypeID() == 10){
nodeHash.append(artifact);
}
}
//Add them back in order
formatted_Report.append(nodeGen);
formatted_Report.append(nodeWebBookmark);
formatted_Report.append(nodeWebCookie);
formatted_Report.append(nodeWebHistory);
formatted_Report.append(nodeWebDownload);
formatted_Report.append(nodeRecentObjects);
formatted_Report.append(nodeTrackPoint);
formatted_Report.append(nodeInstalled);
formatted_Report.append(nodeKeyword);
formatted_Report.append(nodeHash);
//end of master loop
formatted_Report.append("</div></div></body></html>");
}
catch(Exception e)
{
Logger.getLogger(reportHTML.class.getName()).log(Level.INFO, "Exception occurred", e);
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "reportHTML"
|
"public reportHTML (HashMap<BlackboardArtifact,ArrayList<BlackboardAttribute>> report){
try{
Case currentCase = Case.getCurrentCase(); // get the most updated case
SleuthkitCase skCase = currentCase.getSleuthkitCase();
String caseName = currentCase.getName();
Integer imagecount = currentCase.getImageIDs().length;
Integer filesystemcount = currentCase.getRootObjectsCount();
DateFormat datetimeFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
Date date = new Date();
String datetime = datetimeFormat.format(date);
String datenotime = dateFormat.format(date);
//Add html header info
formatted_Report.append("<html><head>Autopsy Report for Case:").append(caseName).append("</head><body><div id=\"main\"><div id=\"content\">");
// Add summary information now
formatted_Report.append("<h1>Report for Case: ").append(caseName).append("</h1>");
formatted_Report.append("<h3>Case Summary</h3><p>XML Report Generated by Autopsy 3 on ").append(datetime).append("<br /><ul>");
formatted_Report.append("<li># of Images: ").append(imagecount).append("</li>");
formatted_Report.append("<li>FileSystems: ").append(filesystemcount).append("</li>");
StringBuilder nodeGen = new StringBuilder("<h3>General Information</h3>");
StringBuilder nodeWebBookmark = new StringBuilder("<h3>Web Bookmarks</h3>");
StringBuilder nodeWebCookie = new StringBuilder("<h3>Web Cookies</h3>");
StringBuilder nodeWebHistory = new StringBuilder("<h3>Web History</h3>");
StringBuilder nodeWebDownload = new StringBuilder("<h3>Web Downloads</h3>");
StringBuilder nodeRecentObjects = new StringBuilder("<h3>Recent Documents</h3>");
StringBuilder nodeTrackPoint = new StringBuilder("<h3>Track Points</h3>");
StringBuilder nodeInstalled = new StringBuilder("<h3>Installed Programs</h3>");
StringBuilder nodeKeyword = new StringBuilder("<h3>Keyword Search Hits</h3>");
StringBuilder nodeHash = new StringBuilder("<h3>Hashset Hits</h3>");
for (Entry<BlackboardArtifact,ArrayList<BlackboardAttribute>> entry : report.entrySet()) {
StringBuilder artifact = new StringBuilder("<p>Artifact");
Long objId = entry.getKey().getObjectID();
Content cont = skCase.getContentById(objId);
Long filesize = cont.getSize();
artifact.append(" ID: " + objId.toString());
artifact.append("<br /> Name: <strong>").append(cont.accept(new NameVisitor())).append("</strong>");
artifact.append("<br />Path: ").append(cont.accept(new PathVisitor()));
artifact.append("<br /> Size: ").append(filesize.toString());
artifact.append("</p><ul style=\"list-style-type: none;\">");
// Get all the attributes for this guy
for (BlackboardAttribute tempatt : entry.getValue())
{
StringBuilder attribute = new StringBuilder("<li style=\"list-style-type: none;\">Type: ").append(tempatt.getAttributeTypeDisplayName()).append("</li>");
attribute.append("<li style=\"list-style-type: none;\">Value: ").append(tempatt.getValueString()).append("</li>");
attribute.append("<li style=\"list-style-type: none;\"> Context: ").append(tempatt.getContext()).append("</li>");
artifact.append(attribute);
<MASK>}</MASK>
artifact.append("</ul>");
if(entry.getKey().getArtifactTypeID() == 1){
nodeGen.append(artifact);
<MASK>}</MASK>
if(entry.getKey().getArtifactTypeID() == 2){
nodeWebBookmark.append(artifact);
<MASK>}</MASK>
if(entry.getKey().getArtifactTypeID() == 3){
nodeWebCookie.append(artifact);
<MASK>}</MASK>
if(entry.getKey().getArtifactTypeID() == 4){
nodeWebHistory.append(artifact);
<MASK>}</MASK>
if(entry.getKey().getArtifactTypeID() == 5){
nodeWebDownload.append(artifact);
<MASK>}</MASK>
if(entry.getKey().getArtifactTypeID() == 6){
nodeRecentObjects.append(artifact);
<MASK>}</MASK>
if(entry.getKey().getArtifactTypeID() == 7){
nodeTrackPoint.append(artifact);
<MASK>}</MASK>
if(entry.getKey().getArtifactTypeID() == 8){
nodeInstalled.append(artifact);
<MASK>}</MASK>
if(entry.getKey().getArtifactTypeID() == 9){
nodeKeyword.append(artifact);
<MASK>}</MASK>
if(entry.getKey().getArtifactTypeID() == 10){
nodeHash.append(artifact);
<MASK>}</MASK>
//Add them back in order
formatted_Report.append(nodeGen);
formatted_Report.append(nodeWebBookmark);
formatted_Report.append(nodeWebCookie);
formatted_Report.append(nodeWebHistory);
formatted_Report.append(nodeWebDownload);
formatted_Report.append(nodeRecentObjects);
formatted_Report.append(nodeTrackPoint);
formatted_Report.append(nodeInstalled);
formatted_Report.append(nodeKeyword);
formatted_Report.append(nodeHash);
//end of master loop
<MASK>}</MASK>
formatted_Report.append("</div></div></body></html>");
<MASK>}</MASK>
catch(Exception e)
{
Logger.getLogger(reportHTML.class.getName()).log(Level.INFO, "Exception occurred", e);
<MASK>}</MASK>
<MASK>}</MASK>"
|
Inversion-Mutation
|
megadiff
|
"public void navigateAndInitiateEmergencyRnr(String program) {
navigateRnr();
myFacilityRadioButton.click();
testWebDriver.sleep(1000);
testWebDriver.waitForElementToAppear(programDropDown);
testWebDriver.selectByVisibleText(rnrTypeSelectBox, "Emergency");
testWebDriver.selectByVisibleText(programDropDown, program);
testWebDriver.waitForAjax();
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "navigateAndInitiateEmergencyRnr"
|
"public void navigateAndInitiateEmergencyRnr(String program) {
navigateRnr();
myFacilityRadioButton.click();
testWebDriver.sleep(1000);
testWebDriver.waitForElementToAppear(programDropDown);
<MASK>testWebDriver.selectByVisibleText(programDropDown, program);</MASK>
testWebDriver.selectByVisibleText(rnrTypeSelectBox, "Emergency");
testWebDriver.waitForAjax();
}"
|
Inversion-Mutation
|
megadiff
|
"@Override
public void onPause() {
Log.d("GeoBeagle", "GeoBeagle onPause");
mGeoBeagleDelegate.onPause();
super.onPause();
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onPause"
|
"@Override
public void onPause() {
<MASK>super.onPause();</MASK>
Log.d("GeoBeagle", "GeoBeagle onPause");
mGeoBeagleDelegate.onPause();
}"
|
Inversion-Mutation
|
megadiff
|
"public static SimpleTweet generateSimpleTweet(Status status){
SimpleTweet simpleTweet = initializeSimpleTweet();
try{
/*Setting contributors in SimpleTweet*/
ArrayList<Long> contributors = new ArrayList<Long>();
for (long contributor : status.getContributors())
contributors.add(contributor);
simpleTweet.setContributors(contributors);
/*Setting basic elements in SimpleTweet*/
simpleTweet.setCreatedAt(status.getCreatedAt().toString());
simpleTweet.setCurrentUserRetweetId(status.getCurrentUserRetweetId());
simpleTweet.setId(status.getId());
simpleTweet.setInReplyToScreenName(status.getInReplyToScreenName());
simpleTweet.setInReplyToStatusId(status.getInReplyToStatusId());
simpleTweet.setInReplyToUserId(status.getInReplyToUserId());
simpleTweet.setRetweetCount(status.getRetweetCount());
simpleTweet.setSource(status.getSource());
simpleTweet.setText(status.getText());
simpleTweet.setIsFavorited(status.isFavorited());
simpleTweet.setIsPossiblySensitive(status.isPossiblySensitive());
simpleTweet.setIsRetweet(status.isRetweet());
simpleTweet.setIsRetweetedByMe(status.isRetweetedByMe());
simpleTweet.setIsTruncated(status.isTruncated());
/*Setting basic GeoLocation elements*/
if (status.getGeoLocation() != null){
simpleTweet.setCoordinatesLatitude(status.getGeoLocation().getLatitude());
simpleTweet.setCoordinatesLongitude(status.getGeoLocation().getLongitude());
}
/*Setting SimpleHashtagEntities*/
ArrayList<SimpleHashtagEntity> hashtagEntities =
new ArrayList<SimpleHashtagEntity>();
for (HashtagEntity hashtagEntity : status.getHashtagEntities()){
SimpleHashtagEntity simpleHashtagEntity = new SimpleHashtagEntity();
simpleHashtagEntity.setEnd(hashtagEntity.getEnd());
simpleHashtagEntity.setStart(hashtagEntity.getStart());
simpleHashtagEntity.setText(hashtagEntity.getText());
hashtagEntities.add(simpleHashtagEntity);
}
simpleTweet.setHashTagEntities(hashtagEntities);
/*Setting SimpleURLEntities*/
ArrayList<SimpleURLEntity> urlEntities =
new ArrayList<SimpleURLEntity>();
for (URLEntity urlEntity : status.getURLEntities()){
SimpleURLEntity simpleURLEntity = new SimpleURLEntity();
simpleURLEntity.setEnd(urlEntity.getEnd());
simpleURLEntity.setStart(urlEntity.getStart());
simpleURLEntity.setURL(urlEntity.getURL());
simpleURLEntity.setDisplayURL(urlEntity.getDisplayURL());
simpleURLEntity.setExpandedURL(urlEntity.getExpandedURL());
urlEntities.add(simpleURLEntity);
}
simpleTweet.setUrlEntities(urlEntities);
/*Setting SimpleUserMentionEntities*/
ArrayList<SimpleUserMentionEntity> userMentionEntities =
new ArrayList<SimpleUserMentionEntity>();
for (UserMentionEntity userMentionEntity : status.getUserMentionEntities()){
SimpleUserMentionEntity simpleUserMentionEntity = new SimpleUserMentionEntity();
simpleUserMentionEntity.setEnd(userMentionEntity.getEnd());
simpleUserMentionEntity.setStart(userMentionEntity.getStart());
simpleUserMentionEntity.setId(userMentionEntity.getId());
simpleUserMentionEntity.setName(userMentionEntity.getName());
simpleUserMentionEntity.setScreenName(userMentionEntity.getScreenName());
userMentionEntities.add(simpleUserMentionEntity);
}
simpleTweet.setUserMentionEntities(userMentionEntities);
/*Setting SimpleMediaEntities*/
ArrayList<SimpleMediaEntity> mediaEntities =
new ArrayList<SimpleMediaEntity>();
for (MediaEntity mediaEntity : status.getMediaEntities()){
SimpleMediaEntity simpleMediaEntity = new SimpleMediaEntity();
simpleMediaEntity.setId(mediaEntity.getId());
simpleMediaEntity.setType(mediaEntity.getType());
simpleMediaEntity.setMediaURL(mediaEntity.getMediaURL());
simpleMediaEntity.setMediaURLHttps(mediaEntity.getMediaURLHttps());
mediaEntities.add(simpleMediaEntity);
}
simpleTweet.setMediaEntities(mediaEntities);
/*Setting SimpleUser*/
SimpleUser simpleUser = new SimpleUser();
simpleUser.setId(status.getUser().getId());
simpleUser.setScreenName(status.getUser().getScreenName());
simpleUser.setCreatedAt(status.getUser().getCreatedAt().toString());
simpleUser.setFollowersCount(status.getUser().getFollowersCount());
simpleUser.setFriendsCount(status.getUser().getFriendsCount());
simpleUser.setListedCount(status.getUser().getListedCount());
simpleUser.setProfileImageURL(status.getUser().getProfileImageURL());
simpleUser.setStatusesCount(status.getUser().getStatusesCount());
simpleUser.setVerified(status.getUser().isVerified());
simpleTweet.setUser(simpleUser);
/*Setting SimplePlace*/
if (status.getPlace() != null){
SimplePlace simplePlace = new SimplePlace();
simplePlace.setURL(status.getPlace().getURL());
simplePlace.setStreetAddress(status.getPlace().getStreetAddress());
simplePlace.setPlaceType(status.getPlace().getPlaceType());
simplePlace.setName(status.getPlace().getName());
simplePlace.setFullName(status.getPlace().getFullName());
simplePlace.setId(status.getPlace().getId());
simplePlace.setCountry(status.getPlace().getCountry());
simplePlace.setCountryCode(status.getPlace().getCountryCode());
ArrayList<SimpleGeoLocation> geoLocationArrayList =
new ArrayList<SimpleGeoLocation>();
GeoLocation[][] geoLocations = status.getPlace().getBoundingBoxCoordinates();
if (geoLocations != null){
for (int i = 0; i < geoLocations.length; i++){
for (int j = 0; j < geoLocations[i].length; j++){
SimpleGeoLocation simpleGeoLocation
= new SimpleGeoLocation(geoLocations[i][j].getLatitude(),
geoLocations[i][j].getLongitude());
geoLocationArrayList.add(simpleGeoLocation);
}
}
}
simplePlace.setBoundingBox(geoLocationArrayList);
simpleTweet.setPlace(simplePlace);
}
}catch (Exception exception){
logger.error("Exception while converting a Status object to a SimpleTweet object",
exception);
crisisMailer.sendEmailAlert(exception);
}
return simpleTweet;
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "generateSimpleTweet"
|
"public static SimpleTweet generateSimpleTweet(Status status){
SimpleTweet simpleTweet = initializeSimpleTweet();
try{
/*Setting contributors in SimpleTweet*/
ArrayList<Long> contributors = new ArrayList<Long>();
for (long contributor : status.getContributors())
contributors.add(contributor);
simpleTweet.setContributors(contributors);
/*Setting basic elements in SimpleTweet*/
simpleTweet.setCreatedAt(status.getCreatedAt().toString());
simpleTweet.setCurrentUserRetweetId(status.getCurrentUserRetweetId());
simpleTweet.setId(status.getId());
simpleTweet.setInReplyToScreenName(status.getInReplyToScreenName());
simpleTweet.setInReplyToStatusId(status.getInReplyToStatusId());
simpleTweet.setInReplyToUserId(status.getInReplyToUserId());
simpleTweet.setRetweetCount(status.getRetweetCount());
simpleTweet.setSource(status.getSource());
simpleTweet.setText(status.getText());
simpleTweet.setIsFavorited(status.isFavorited());
simpleTweet.setIsPossiblySensitive(status.isPossiblySensitive());
simpleTweet.setIsRetweet(status.isRetweet());
simpleTweet.setIsRetweetedByMe(status.isRetweetedByMe());
simpleTweet.setIsTruncated(status.isTruncated());
/*Setting basic GeoLocation elements*/
if (status.getGeoLocation() != null){
simpleTweet.setCoordinatesLatitude(status.getGeoLocation().getLatitude());
simpleTweet.setCoordinatesLongitude(status.getGeoLocation().getLongitude());
}
/*Setting SimpleHashtagEntities*/
ArrayList<SimpleHashtagEntity> hashtagEntities =
new ArrayList<SimpleHashtagEntity>();
for (HashtagEntity hashtagEntity : status.getHashtagEntities()){
SimpleHashtagEntity simpleHashtagEntity = new SimpleHashtagEntity();
simpleHashtagEntity.setEnd(hashtagEntity.getEnd());
simpleHashtagEntity.setStart(hashtagEntity.getStart());
simpleHashtagEntity.setText(hashtagEntity.getText());
hashtagEntities.add(simpleHashtagEntity);
}
simpleTweet.setHashTagEntities(hashtagEntities);
/*Setting SimpleURLEntities*/
ArrayList<SimpleURLEntity> urlEntities =
new ArrayList<SimpleURLEntity>();
for (URLEntity urlEntity : status.getURLEntities()){
SimpleURLEntity simpleURLEntity = new SimpleURLEntity();
simpleURLEntity.setEnd(urlEntity.getEnd());
simpleURLEntity.setStart(urlEntity.getStart());
simpleURLEntity.setURL(urlEntity.getURL());
simpleURLEntity.setDisplayURL(urlEntity.getDisplayURL());
simpleURLEntity.setExpandedURL(urlEntity.getExpandedURL());
urlEntities.add(simpleURLEntity);
}
simpleTweet.setUrlEntities(urlEntities);
/*Setting SimpleUserMentionEntities*/
ArrayList<SimpleUserMentionEntity> userMentionEntities =
new ArrayList<SimpleUserMentionEntity>();
for (UserMentionEntity userMentionEntity : status.getUserMentionEntities()){
SimpleUserMentionEntity simpleUserMentionEntity = new SimpleUserMentionEntity();
simpleUserMentionEntity.setEnd(userMentionEntity.getEnd());
simpleUserMentionEntity.setStart(userMentionEntity.getStart());
simpleUserMentionEntity.setId(userMentionEntity.getId());
simpleUserMentionEntity.setName(userMentionEntity.getName());
simpleUserMentionEntity.setScreenName(userMentionEntity.getScreenName());
userMentionEntities.add(simpleUserMentionEntity);
}
simpleTweet.setUserMentionEntities(userMentionEntities);
/*Setting SimpleMediaEntities*/
ArrayList<SimpleMediaEntity> mediaEntities =
new ArrayList<SimpleMediaEntity>();
for (MediaEntity mediaEntity : status.getMediaEntities()){
SimpleMediaEntity simpleMediaEntity = new SimpleMediaEntity();
simpleMediaEntity.setId(mediaEntity.getId());
simpleMediaEntity.setType(mediaEntity.getType());
simpleMediaEntity.setMediaURL(mediaEntity.getMediaURL());
simpleMediaEntity.setMediaURLHttps(mediaEntity.getMediaURLHttps());
mediaEntities.add(simpleMediaEntity);
}
simpleTweet.setMediaEntities(mediaEntities);
/*Setting SimpleUser*/
SimpleUser simpleUser = new SimpleUser();
simpleUser.setId(status.getUser().getId());
simpleUser.setScreenName(status.getUser().getScreenName());
simpleUser.setCreatedAt(status.getUser().getCreatedAt().toString());
simpleUser.setFollowersCount(status.getUser().getFollowersCount());
simpleUser.setFriendsCount(status.getUser().getFriendsCount());
simpleUser.setListedCount(status.getUser().getListedCount());
simpleUser.setProfileImageURL(status.getUser().getProfileImageURL());
simpleUser.setStatusesCount(status.getUser().getStatusesCount());
simpleUser.setVerified(status.getUser().isVerified());
simpleTweet.setUser(simpleUser);
/*Setting SimplePlace*/
if (status.getPlace() != null){
SimplePlace simplePlace = new SimplePlace();
simplePlace.setURL(status.getPlace().getURL());
simplePlace.setStreetAddress(status.getPlace().getStreetAddress());
simplePlace.setPlaceType(status.getPlace().getPlaceType());
simplePlace.setName(status.getPlace().getName());
simplePlace.setFullName(status.getPlace().getFullName());
simplePlace.setId(status.getPlace().getId());
simplePlace.setCountry(status.getPlace().getCountry());
simplePlace.setCountryCode(status.getPlace().getCountryCode());
ArrayList<SimpleGeoLocation> geoLocationArrayList =
new ArrayList<SimpleGeoLocation>();
GeoLocation[][] geoLocations = status.getPlace().getBoundingBoxCoordinates();
if (geoLocations != null){
for (int i = 0; i < geoLocations.length; i++){
for (int j = 0; j < geoLocations[i].length; j++){
SimpleGeoLocation simpleGeoLocation
= new SimpleGeoLocation(geoLocations[i][j].getLatitude(),
geoLocations[i][j].getLongitude());
geoLocationArrayList.add(simpleGeoLocation);
}
}
<MASK>simplePlace.setBoundingBox(geoLocationArrayList);</MASK>
}
simpleTweet.setPlace(simplePlace);
}
}catch (Exception exception){
logger.error("Exception while converting a Status object to a SimpleTweet object",
exception);
crisisMailer.sendEmailAlert(exception);
}
return simpleTweet;
}"
|
Inversion-Mutation
|
megadiff
|
"@Override
public void onEnable() {
instance = this;
configManager = new ConfigManager();
groupMediator = new GroupMediator();
jaLogger = new JukeAlertLogger();
snitchManager = new SnitchManager();
registerEvents();
registerCommands();
snitchManager.loadSnitches();
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onEnable"
|
"@Override
public void onEnable() {
instance = this;
configManager = new ConfigManager();
jaLogger = new JukeAlertLogger();
snitchManager = new SnitchManager();
<MASK>groupMediator = new GroupMediator();</MASK>
registerEvents();
registerCommands();
snitchManager.loadSnitches();
}"
|
Inversion-Mutation
|
megadiff
|
"Dialog createDialog() {
final View layout = View.inflate(Launcher.this, R.layout.rename_folder, null);
mInput = (EditText) layout.findViewById(R.id.folder_name);
AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
builder.setIcon(0);
builder.setTitle(getString(R.string.rename_folder_title));
builder.setCancelable(true);
builder.setOnCancelListener(new Dialog.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
cleanup();
}
});
builder.setNegativeButton(getString(R.string.cancel_action),
new Dialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
cleanup();
}
}
);
builder.setPositiveButton(getString(R.string.rename_action),
new Dialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
changeFolderName();
}
}
);
builder.setView(layout);
final AlertDialog dialog = builder.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
public void onShow(DialogInterface dialog) {
mWaitingForResult = true;
mInput.requestFocus();
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(mInput, 0);
}
});
return dialog;
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createDialog"
|
"Dialog createDialog() {
<MASK>mWaitingForResult = true;</MASK>
final View layout = View.inflate(Launcher.this, R.layout.rename_folder, null);
mInput = (EditText) layout.findViewById(R.id.folder_name);
AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
builder.setIcon(0);
builder.setTitle(getString(R.string.rename_folder_title));
builder.setCancelable(true);
builder.setOnCancelListener(new Dialog.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
cleanup();
}
});
builder.setNegativeButton(getString(R.string.cancel_action),
new Dialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
cleanup();
}
}
);
builder.setPositiveButton(getString(R.string.rename_action),
new Dialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
changeFolderName();
}
}
);
builder.setView(layout);
final AlertDialog dialog = builder.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
public void onShow(DialogInterface dialog) {
mInput.requestFocus();
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(mInput, 0);
}
});
return dialog;
}"
|
Inversion-Mutation
|
megadiff
|
"@Override
public List<BeanMetaData> getBeans()
{
ArrayList<BeanMetaData> result = new ArrayList<BeanMetaData>();
//Create AspectBinding
AbstractBeanMetaData binding = new AbstractBeanMetaData();
if (name == null)
{
name = GUID.asString();
}
binding.setName(name);
BeanMetaDataUtil.setSimpleProperty(binding, "name", name);
binding.setBean(AspectBinding.class.getName());
BeanMetaDataUtil.setSimpleProperty(binding, "pointcut", pointcut);
if (cflow != null)
{
BeanMetaDataUtil.setSimpleProperty(binding, "cflow", cflow);
}
util.setAspectManagerProperty(binding, "manager");
result.add(binding);
if (interceptors.size() > 0)
{
AbstractListMetaData almd = new AbstractListMetaData();
int i = 0;
for (BaseInterceptorData interceptor : interceptors)
{
AbstractBeanMetaData bmd = new AbstractBeanMetaData(interceptor.getBeanClassName());
String intName = name + "$" + i++;
bmd.setName(intName);
util.setAspectManagerProperty(bmd, "manager");
BeanMetaDataUtil.DependencyBuilder builder = new BeanMetaDataUtil.DependencyBuilder(bmd, "binding", name).setState("Instantiated");
BeanMetaDataUtil.setDependencyProperty(builder);
if (interceptor instanceof AdviceData)
{
BeanMetaDataUtil.DependencyBuilder db = new BeanMetaDataUtil.DependencyBuilder(bmd, "aspect", interceptor.getRefName());
BeanMetaDataUtil.setDependencyProperty(db);
if (((AdviceData)interceptor).getAdviceMethod() != null)
{
BeanMetaDataUtil.setSimpleProperty(bmd, "aspectMethod", ((AdviceData)interceptor).getAdviceMethod());
}
BeanMetaDataUtil.setSimpleProperty(bmd, "type", ((AdviceData)interceptor).getType());
}
else
{
BeanMetaDataUtil.DependencyBuilder db = new BeanMetaDataUtil.DependencyBuilder(bmd, "stack", interceptor.getRefName());
BeanMetaDataUtil.setDependencyProperty(db);
}
result.add(bmd);
almd.add(new AbstractInjectionValueMetaData(intName));
}
BeanMetaDataUtil.setSimpleProperty(binding, "advices", almd);
}
return result;
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getBeans"
|
"@Override
public List<BeanMetaData> getBeans()
{
ArrayList<BeanMetaData> result = new ArrayList<BeanMetaData>();
//Create AspectBinding
AbstractBeanMetaData binding = new AbstractBeanMetaData();
if (name == null)
{
name = GUID.asString();
}
binding.setName(name);
BeanMetaDataUtil.setSimpleProperty(binding, "name", name);
binding.setBean(AspectBinding.class.getName());
BeanMetaDataUtil.setSimpleProperty(binding, "pointcut", pointcut);
if (cflow != null)
{
BeanMetaDataUtil.setSimpleProperty(binding, "cflow", cflow);
}
util.setAspectManagerProperty(binding, "manager");
result.add(binding);
if (interceptors.size() > 0)
{
AbstractListMetaData almd = new AbstractListMetaData();
int i = 0;
for (BaseInterceptorData interceptor : interceptors)
{
AbstractBeanMetaData bmd = new AbstractBeanMetaData(interceptor.getBeanClassName());
String intName = name + "$" + i++;
bmd.setName(intName);
util.setAspectManagerProperty(bmd, "manager");
BeanMetaDataUtil.DependencyBuilder builder = new BeanMetaDataUtil.DependencyBuilder(bmd, "binding", name).setState("Instantiated");
BeanMetaDataUtil.setDependencyProperty(builder);
if (interceptor instanceof AdviceData)
{
BeanMetaDataUtil.DependencyBuilder db = new BeanMetaDataUtil.DependencyBuilder(bmd, "aspect", interceptor.getRefName());
BeanMetaDataUtil.setDependencyProperty(db);
if (((AdviceData)interceptor).getAdviceMethod() != null)
{
BeanMetaDataUtil.setSimpleProperty(bmd, "aspectMethod", ((AdviceData)interceptor).getAdviceMethod());
}
BeanMetaDataUtil.setSimpleProperty(bmd, "type", ((AdviceData)interceptor).getType());
}
else
{
BeanMetaDataUtil.DependencyBuilder db = new BeanMetaDataUtil.DependencyBuilder(bmd, "stack", interceptor.getRefName());
BeanMetaDataUtil.setDependencyProperty(db);
}
result.add(bmd);
almd.add(new AbstractInjectionValueMetaData(intName));
<MASK>BeanMetaDataUtil.setSimpleProperty(binding, "advices", almd);</MASK>
}
}
return result;
}"
|
Inversion-Mutation
|
megadiff
|
"@Override
protected void hideFakeTitleBar() {
if (isFakeTitleBarShowing()) {
mFakeTitleBar.setEditMode(false);
mTabBar.onHideTitleBar();
mContentView.removeView(mFakeTitleBar);
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "hideFakeTitleBar"
|
"@Override
protected void hideFakeTitleBar() {
if (isFakeTitleBarShowing()) {
mFakeTitleBar.setEditMode(false);
<MASK>mContentView.removeView(mFakeTitleBar);</MASK>
mTabBar.onHideTitleBar();
}
}"
|
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
|
"public FitSphere(final Vector3D[] points) {
Vector3D mean = Vector3D.ZERO;
for(Vector3D point : points)
mean = mean.add(point.scalarMultiply(1D/(double)points.length));
ReportingUtils.logMessage("MEAN: " + mean.toString());
final Vector3D endMean = new Vector3D(mean.getX(), mean.getY(), mean.getZ());
double[] params = new double[PARAMLEN];
params[RADIUS] = 0.5*points[0].subtract(points[points.length-1]).getNorm();
Vector3D centerGuess = points[points.length/2].subtract(mean).add(mean.subtract(points[points.length/2]).normalize().scalarMultiply(params[RADIUS]));
params[XC] = centerGuess.getX(); params[YC] = centerGuess.getY(); params[ZC] = centerGuess.getZ();
double[] steps = new double[PARAMLEN];
steps[XC] = steps[YC] = steps[ZC] = 0.001;
steps[RADIUS] = 0.00001;
ReportingUtils.logMessage("Initial parameters: " + Arrays.toString(params) + ", steps: " + Arrays.toString(steps));
MultivariateRealFunction MRF = new MultivariateRealFunction() {
@Override
public double value(double[] params) {
Vector3D center = new Vector3D(params[XC], params[YC], params[ZC]);
double err = 0;
for(Vector3D point : points)
err += Math.pow(point.subtract(endMean).subtract(center).getNorm() - params[RADIUS], 2D);
// ReportingUtils.logMessage("value(" + Arrays.toString(params) + "): endMean=" + endMean.toString() + ", err=" + err);
return err;
}
};
SimplexOptimizer opt = new SimplexOptimizer(1e-6, -1);
NelderMeadSimplex nm = new NelderMeadSimplex(steps);
opt.setSimplex(nm);
double[] result = null;
try {
result = opt.optimize(5000000, MRF, GoalType.MINIMIZE, params).getPoint();
error = Math.sqrt(MRF.value(result));
} catch(Throwable t) {
ReportingUtils.logError(t, "Optimization failed!");
}
ReportingUtils.logMessage("Fit: " + Arrays.toString(result));
center = new Vector3D(result[XC], result[YC], result[ZC]).add(mean);
radius = result[RADIUS];
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "FitSphere"
|
"public FitSphere(final Vector3D[] points) {
Vector3D mean = Vector3D.ZERO;
for(Vector3D point : points)
mean = mean.add(point.scalarMultiply(1D/(double)points.length));
ReportingUtils.logMessage("MEAN: " + mean.toString());
final Vector3D endMean = new Vector3D(mean.getX(), mean.getY(), mean.getZ());
double[] params = new double[PARAMLEN];
params[RADIUS] = 0.5*points[0].subtract(points[points.length-1]).getNorm();
Vector3D centerGuess = points[points.length/2].subtract(mean).add(mean.subtract(points[points.length/2]).normalize().scalarMultiply(params[RADIUS]));
params[XC] = centerGuess.getX(); params[YC] = centerGuess.getY(); params[ZC] = centerGuess.getZ();
double[] steps = new double[PARAMLEN];
steps[XC] = steps[YC] = steps[ZC] = 0.001;
steps[RADIUS] = 0.00001;
ReportingUtils.logMessage("Initial parameters: " + Arrays.toString(params) + ", steps: " + Arrays.toString(steps));
MultivariateRealFunction MRF = new MultivariateRealFunction() {
@Override
public double value(double[] params) {
Vector3D center = new Vector3D(params[XC], params[YC], params[ZC]);
double err = 0;
for(Vector3D point : points)
err += Math.pow(point.subtract(endMean).subtract(center).getNorm() - params[RADIUS], 2D);
// ReportingUtils.logMessage("value(" + Arrays.toString(params) + "): endMean=" + endMean.toString() + ", err=" + err);
return err;
}
};
SimplexOptimizer opt = new SimplexOptimizer(1e-6, -1);
NelderMeadSimplex nm = new NelderMeadSimplex(steps);
opt.setSimplex(nm);
double[] result = null;
try {
result = opt.optimize(5000000, MRF, GoalType.MINIMIZE, params).getPoint();
} catch(Throwable t) {
ReportingUtils.logError(t, "Optimization failed!");
}
ReportingUtils.logMessage("Fit: " + Arrays.toString(result));
center = new Vector3D(result[XC], result[YC], result[ZC]).add(mean);
radius = result[RADIUS];
<MASK>error = Math.sqrt(MRF.value(result));</MASK>
}"
|
Inversion-Mutation
|
megadiff
|
"public void draguearElemBarrio(String Elem,int posX, int posY) throws Exception{
if (posX < 0 || posX >= Mapa.tama() || posY < 0 || posY >= Mapa.tamb()){
throw new Exception("\nLa posicion no es correcta.\n");
}
Elemento e = DOMElem.getElemento(Elem);
int tamX,tamY;
if(e instanceof Vivienda){
Vivienda v = (Vivienda) e;
tamX = v.getTamanoX();
tamY = v.getTamanoY();
}
else if(e instanceof Publico){
Publico p = (Publico) e;
tamX = p.getTamanoX();
tamY = p.getTamanoY();
}
else{
Comercio c = (Comercio) e;
tamX = c.getTamanoX();
tamY = c.getTamanoY();
}
for(int i=posX; i<posX+tamX; ++i){
for(int j=posY; j<posY+tamY; ++j){
if (i < 0 || i >= Mapa.tama() || j < 0 || j >= Mapa.tamb()){
throw new Exception("\nEl elemento no cabe en esa posicion.\n");
}
Parcela aux = Mapa.pos(i, j);
if (aux.getoid() != 0){
throw new Exception("\nYa hay un Elemento o carretera en esa ubicacion.\n");
}
}
}
Mapa.expande(posX,posY,tamX,tamY,(int)e.getId(), null, true);
anadirElemBarrio(Elem, 1);
Pair<Integer,Integer> pos = new Pair(posX,posY);
ArrayList<Pair<Integer,Integer>> posiciones = B.getPosiciones();
posiciones.add(pos);
B.setPosiciones(posiciones);
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "draguearElemBarrio"
|
"public void draguearElemBarrio(String Elem,int posX, int posY) throws Exception{
if (posX < 0 || posX >= Mapa.tama() || posY < 0 || posY >= Mapa.tamb()){
throw new Exception("\nLa posicion no es correcta.\n");
}
<MASK>anadirElemBarrio(Elem, 1);</MASK>
Elemento e = DOMElem.getElemento(Elem);
int tamX,tamY;
if(e instanceof Vivienda){
Vivienda v = (Vivienda) e;
tamX = v.getTamanoX();
tamY = v.getTamanoY();
}
else if(e instanceof Publico){
Publico p = (Publico) e;
tamX = p.getTamanoX();
tamY = p.getTamanoY();
}
else{
Comercio c = (Comercio) e;
tamX = c.getTamanoX();
tamY = c.getTamanoY();
}
for(int i=posX; i<posX+tamX; ++i){
for(int j=posY; j<posY+tamY; ++j){
if (i < 0 || i >= Mapa.tama() || j < 0 || j >= Mapa.tamb()){
throw new Exception("\nEl elemento no cabe en esa posicion.\n");
}
Parcela aux = Mapa.pos(i, j);
if (aux.getoid() != 0){
throw new Exception("\nYa hay un Elemento o carretera en esa ubicacion.\n");
}
}
}
Mapa.expande(posX,posY,tamX,tamY,(int)e.getId(), null, true);
Pair<Integer,Integer> pos = new Pair(posX,posY);
ArrayList<Pair<Integer,Integer>> posiciones = B.getPosiciones();
posiciones.add(pos);
B.setPosiciones(posiciones);
}"
|
Inversion-Mutation
|
megadiff
|
"@Override
public void show() {
super.show();
stage.addActor(gamebgImage);
stage.addActor(borderImage);
stage.addActor(pipesImage);
stage.addActor(infoPanels);
stage.addActor(valve1Image);
stage.addActor(valve2Image);
stage.addActor(pump1Image);
stage.addActor(pump2Image);
stage.addActor(coolerImage);
stage.addActor(poweroutImage);
stage.addActor(reactorImage);
stage.addActor(turbineImage);
stage.addActor(condenserImage);
stage.addActor(mechanicImage);
stage.addActor(pauseImage);
stage.addActor(consolebackImage);
stage.addActor(crUpImage);
stage.addActor(crDownImage);
stage.addActor(pump1Button);
stage.addActor(pump2Button);
stage.addActor(valve1Button);
stage.addActor(valve2Button);
stage.addActor(piggyImage);
stage.addActor(sErrorImage);
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "show"
|
"@Override
public void show() {
super.show();
stage.addActor(gamebgImage);
stage.addActor(borderImage);
stage.addActor(pipesImage);
stage.addActor(valve1Image);
stage.addActor(valve2Image);
stage.addActor(pump1Image);
stage.addActor(pump2Image);
stage.addActor(coolerImage);
stage.addActor(poweroutImage);
stage.addActor(reactorImage);
stage.addActor(turbineImage);
stage.addActor(condenserImage);
stage.addActor(mechanicImage);
stage.addActor(pauseImage);
stage.addActor(consolebackImage);
stage.addActor(crUpImage);
stage.addActor(crDownImage);
stage.addActor(pump1Button);
stage.addActor(pump2Button);
stage.addActor(valve1Button);
stage.addActor(valve2Button);
stage.addActor(piggyImage);
stage.addActor(sErrorImage);
<MASK>stage.addActor(infoPanels);</MASK>
}"
|
Inversion-Mutation
|
megadiff
|
"private void process(IInvocationContext context, IProblemLocation problem, Collection<IRubyCompletionProposal> proposals) throws CoreException {
int id = problem.getProblemId();
if (id == 0) { // no proposals for none-problem locations
return;
}
switch (id) {
case IProblem.UnusedPrivateMethod:
case IProblem.UnusedPrivateField:
case IProblem.LocalVariableIsNeverUsed:
case IProblem.ArgumentIsNeverUsed:
LocalCorrectionsSubProcessor.addUnusedMemberProposal(context, problem, proposals);
break;
case MisspelledConstructorVisitor.PROBLEM_ID:
LocalCorrectionsSubProcessor.addReplacementProposal("initialize\n", "Rename to 'initialize'", problem, proposals);
break;
case ConstantNamingConvention.PROBLEM_ID:
IRubyScript script = context.getRubyScript();
String src = script.getSource();
String constName = src.substring(problem.getOffset(), problem.getOffset() + problem.getLength());
LocalCorrectionsSubProcessor.addReplacementProposal(constName.toUpperCase(), "Convert to all uppercase", problem, proposals);
break;
case MethodMissingWithoutRespondTo.PROBLEM_ID:
// FIXME Only do this stuff when we apply the proposal! Don't do all this work just to create the proposal...
script = context.getRubyScript();
src = script.getSource();
int offset = 0;
Node rootNode = ASTProvider.getASTProvider().getAST(script, ASTProvider.WAIT_YES, null);
Node typeNode = ClosestSpanningNodeLocator.Instance().findClosestSpanner(rootNode, problem.getOffset(), new INodeAcceptor() {
public boolean doesAccept(Node node) {
return node instanceof ClassNode || node instanceof ModuleNode;
}
});
if (typeNode instanceof ClassNode) {
ClassNode classNode = (ClassNode) typeNode;
offset = classNode.getBodyNode().getPosition().getStartOffset();
} else if (typeNode instanceof ModuleNode) {
ModuleNode classNode = (ModuleNode) typeNode;
offset = classNode.getBodyNode().getPosition().getStartOffset();
}
DefnNode methodNode = NodeFactory.createMethodNode("respond_to?", new String[] {"symbol", "include_private = false"}, null);
Node insert = NodeFactory.createBlockNode(true, NodeFactory.createNewLineNode(methodNode));
String text = ReWriteVisitor.createCodeFromNode(insert, src, getFormatHelper());
// Figure out indent at offset and apply that to each line of text and at end of text
String line = src.substring(0, src.indexOf("\n", offset));
line = line.substring(line.lastIndexOf("\n") + 1);
Map options = script.getRubyProject().getOptions(true);
String indent = Indents.extractIndentString(line, options);
text = indent + text;
text = text + "\n";
text = text.replaceAll("\\n", "\n" + indent);
LocalCorrectionsSubProcessor.addReplacementProposal(offset, 0, text, "Add respond_to? method stub", proposals);
break;
default:
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "process"
|
"private void process(IInvocationContext context, IProblemLocation problem, Collection<IRubyCompletionProposal> proposals) throws CoreException {
int id = problem.getProblemId();
if (id == 0) { // no proposals for none-problem locations
return;
}
switch (id) {
case IProblem.UnusedPrivateMethod:
case IProblem.UnusedPrivateField:
case IProblem.LocalVariableIsNeverUsed:
case IProblem.ArgumentIsNeverUsed:
LocalCorrectionsSubProcessor.addUnusedMemberProposal(context, problem, proposals);
break;
case MisspelledConstructorVisitor.PROBLEM_ID:
LocalCorrectionsSubProcessor.addReplacementProposal("initialize\n", "Rename to 'initialize'", problem, proposals);
break;
case ConstantNamingConvention.PROBLEM_ID:
IRubyScript script = context.getRubyScript();
String src = script.getSource();
String constName = src.substring(problem.getOffset(), problem.getOffset() + problem.getLength());
LocalCorrectionsSubProcessor.addReplacementProposal(constName.toUpperCase(), "Convert to all uppercase", problem, proposals);
break;
case MethodMissingWithoutRespondTo.PROBLEM_ID:
// FIXME Only do this stuff when we apply the proposal! Don't do all this work just to create the proposal...
script = context.getRubyScript();
src = script.getSource();
int offset = 0;
Node rootNode = ASTProvider.getASTProvider().getAST(script, ASTProvider.WAIT_YES, null);
Node typeNode = ClosestSpanningNodeLocator.Instance().findClosestSpanner(rootNode, problem.getOffset(), new INodeAcceptor() {
public boolean doesAccept(Node node) {
return node instanceof ClassNode || node instanceof ModuleNode;
}
});
if (typeNode instanceof ClassNode) {
ClassNode classNode = (ClassNode) typeNode;
offset = classNode.getBodyNode().getPosition().getStartOffset();
} else if (typeNode instanceof ModuleNode) {
ModuleNode classNode = (ModuleNode) typeNode;
offset = classNode.getBodyNode().getPosition().getStartOffset();
}
DefnNode methodNode = NodeFactory.createMethodNode("respond_to?", new String[] {"symbol", "include_private = false"}, null);
Node insert = NodeFactory.createBlockNode(true, NodeFactory.createNewLineNode(methodNode));
String text = ReWriteVisitor.createCodeFromNode(insert, src, getFormatHelper());
// Figure out indent at offset and apply that to each line of text and at end of text
String line = src.substring(0, src.indexOf("\n", offset));
line = line.substring(line.lastIndexOf("\n") + 1);
Map options = script.getRubyProject().getOptions(true);
String indent = Indents.extractIndentString(line, options);
text = indent + text;
<MASK>text = text.replaceAll("\\n", "\n" + indent);</MASK>
text = text + "\n";
LocalCorrectionsSubProcessor.addReplacementProposal(offset, 0, text, "Add respond_to? method stub", proposals);
break;
default:
}
}"
|
Inversion-Mutation
|
megadiff
|
"@cli.System.Security.SecuritySafeCriticalAttribute.Annotation
private void copyToBitmap(int width, int height, int[] pixelData)
{
long size = (long)width * (long)height;
if (size > pixelData.length)
{
throw new IllegalArgumentException();
}
bitmap = createBitmap(width, height);
synchronized( bitmap ) {
cli.System.Drawing.Rectangle rect = new cli.System.Drawing.Rectangle(0, 0, width, height);
cli.System.Drawing.Imaging.BitmapData data = bitmap.LockBits(rect, ImageLockMode.wrap(ImageLockMode.WriteOnly), PixelFormat.wrap(PixelFormat.Format32bppArgb));
cli.System.IntPtr pixelPtr = data.get_Scan0();
cli.System.Runtime.InteropServices.Marshal.Copy(pixelData, 0, pixelPtr, (int)size);
bitmap.UnlockBits(data);
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "copyToBitmap"
|
"@cli.System.Security.SecuritySafeCriticalAttribute.Annotation
private void copyToBitmap(int width, int height, int[] pixelData)
{
long size = (long)width * (long)height;
if (size > pixelData.length)
{
throw new IllegalArgumentException();
}
synchronized( bitmap ) {
<MASK>bitmap = createBitmap(width, height);</MASK>
cli.System.Drawing.Rectangle rect = new cli.System.Drawing.Rectangle(0, 0, width, height);
cli.System.Drawing.Imaging.BitmapData data = bitmap.LockBits(rect, ImageLockMode.wrap(ImageLockMode.WriteOnly), PixelFormat.wrap(PixelFormat.Format32bppArgb));
cli.System.IntPtr pixelPtr = data.get_Scan0();
cli.System.Runtime.InteropServices.Marshal.Copy(pixelData, 0, pixelPtr, (int)size);
bitmap.UnlockBits(data);
}
}"
|
Inversion-Mutation
|
megadiff
|
"@SuppressWarnings("PMD.ExcessiveMethodLength")
@Transactional(rollbackFor = {ConnectionException.class, ValidationException.class })
public void setDataElement(FileColumn fileColumn,
CommonDataElement dataElement,
Study study,
EntityTypeEnum entityType,
String keywords)
throws ConnectionException, ValidationException {
if (dataElement.getValueDomain() == null) {
retrieveValueDomain(dataElement);
}
AnnotationDefinition annotationDefinition = new AnnotationDefinition();
annotationDefinition.setCommonDataElement(dataElement);
addDefinitionToStudy(fileColumn.getFieldDescriptor(), study, entityType, annotationDefinition);
if (dataElement.getDefinition().length() > DEFINITION_LENGTH) {
dataElement.setDefinition(dataElement.getDefinition().substring(0, DEFINITION_LENGTH - 7) + "...");
}
annotationDefinition.setKeywords(dataElement.getLongName());
dao.save(annotationDefinition);
validateAnnotationDefinition(fileColumn, study, entityType, annotationDefinition);
dao.save(fileColumn);
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setDataElement"
|
"@SuppressWarnings("PMD.ExcessiveMethodLength")
@Transactional(rollbackFor = {ConnectionException.class, ValidationException.class })
public void setDataElement(FileColumn fileColumn,
CommonDataElement dataElement,
Study study,
EntityTypeEnum entityType,
String keywords)
throws ConnectionException, ValidationException {
if (dataElement.getValueDomain() == null) {
retrieveValueDomain(dataElement);
}
AnnotationDefinition annotationDefinition = new AnnotationDefinition();
annotationDefinition.setCommonDataElement(dataElement);
addDefinitionToStudy(fileColumn.getFieldDescriptor(), study, entityType, annotationDefinition);
if (dataElement.getDefinition().length() > DEFINITION_LENGTH) {
dataElement.setDefinition(dataElement.getDefinition().substring(0, DEFINITION_LENGTH - 7) + "...");
}
annotationDefinition.setKeywords(dataElement.getLongName());
<MASK>validateAnnotationDefinition(fileColumn, study, entityType, annotationDefinition);</MASK>
dao.save(annotationDefinition);
dao.save(fileColumn);
}"
|
Inversion-Mutation
|
megadiff
|
"public static void getItem(){
if(itemValue == 1){
if(player == 1){
if(player1Health < 3){
player1Health++;
}
}
else{
if(player2Health < 3){
player2Health++;
}
}
}
else if(itemValue == 2){
if(player == 1){
player2Health--;
}
else{
player1Health--;
}
}
else{
if(player == 1){
if(player2Health < 3){
player2Health++;
}
}
else{
if(player1Health < 3){
player1Health++;
}
}
}
updateHealth();
if(player1Health <= 0 || player2Health <= 0){
showBoom();
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getItem"
|
"public static void getItem(){
if(itemValue == 1){
if(player == 1){
if(player1Health < 3){
player1Health++;
}
}
else{
if(player2Health < 3){
player2Health++;
}
}
}
else if(itemValue == 2){
if(player == 1){
player2Health--;
}
else{
player1Health--;
}
}
else{
if(player == 1){
if(player2Health < 3){
player2Health++;
}
}
else{
if(player1Health < 3){
player1Health++;
}
}
}
if(player1Health <= 0 || player2Health <= 0){
showBoom();
}
<MASK>updateHealth();</MASK>
}"
|
Inversion-Mutation
|
megadiff
|
"public LdapService newInstance() throws Exception
{
DirectoryService service = new DefaultDirectoryService();
IntegrationUtils.doDelete( service.getWorkingDirectory() );
service.getChangeLog().setEnabled( true );
service.setShutdownHookEnabled( false );
JdbmPartition system = new JdbmPartition();
system.setId( "system" );
// @TODO need to make this configurable for the system partition
system.setCacheSize( 500 );
system.setSuffix( "ou=system" );
// Add indexed attributes for system partition
Set<Index<?,ServerEntry>> indexedAttrs = new HashSet<Index<?,ServerEntry>>();
indexedAttrs.add( new JdbmIndex<String,ServerEntry>( SchemaConstants.OBJECT_CLASS_AT ) );
indexedAttrs.add( new JdbmIndex<String,ServerEntry>( SchemaConstants.OU_AT ) );
system.setIndexedAttributes( indexedAttrs );
service.setSystemPartition( system );
// change the working directory to something that is unique
// on the system and somewhere either under target directory
// or somewhere in a temp area of the machine.
LdapService ldapService = new LdapService();
ldapService.setDirectoryService( service );
int port = AvailablePortFinder.getNextAvailable( 1024 );
ldapService.setTcpTransport( new TcpTransport( port ) );
ldapService.setSocketAcceptor( new NioSocketAcceptor() );
ldapService.getTcpTransport().setNbThreads( 3 );
ldapService.addExtendedOperationHandler( new StartTlsHandler() );
ldapService.addExtendedOperationHandler( new StoredProcedureExtendedOperationHandler() );
// Setup SASL Mechanisms
Map<String, MechanismHandler> mechanismHandlerMap = new HashMap<String,MechanismHandler>();
mechanismHandlerMap.put( SupportedSaslMechanisms.PLAIN, new SimpleMechanismHandler() );
CramMd5MechanismHandler cramMd5MechanismHandler = new CramMd5MechanismHandler();
mechanismHandlerMap.put( SupportedSaslMechanisms.CRAM_MD5, cramMd5MechanismHandler );
DigestMd5MechanismHandler digestMd5MechanismHandler = new DigestMd5MechanismHandler();
mechanismHandlerMap.put( SupportedSaslMechanisms.DIGEST_MD5, digestMd5MechanismHandler );
GssapiMechanismHandler gssapiMechanismHandler = new GssapiMechanismHandler();
mechanismHandlerMap.put( SupportedSaslMechanisms.GSSAPI, gssapiMechanismHandler );
NtlmMechanismHandler ntlmMechanismHandler = new NtlmMechanismHandler();
mechanismHandlerMap.put( SupportedSaslMechanisms.NTLM, ntlmMechanismHandler );
mechanismHandlerMap.put( SupportedSaslMechanisms.GSS_SPNEGO, ntlmMechanismHandler );
ldapService.setSaslMechanismHandlers( mechanismHandlerMap );
return ldapService;
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "newInstance"
|
"public LdapService newInstance() throws Exception
{
DirectoryService service = new DefaultDirectoryService();
IntegrationUtils.doDelete( service.getWorkingDirectory() );
service.getChangeLog().setEnabled( true );
service.setShutdownHookEnabled( false );
JdbmPartition system = new JdbmPartition();
system.setId( "system" );
// @TODO need to make this configurable for the system partition
system.setCacheSize( 500 );
system.setSuffix( "ou=system" );
// Add indexed attributes for system partition
Set<Index<?,ServerEntry>> indexedAttrs = new HashSet<Index<?,ServerEntry>>();
indexedAttrs.add( new JdbmIndex<String,ServerEntry>( SchemaConstants.OBJECT_CLASS_AT ) );
indexedAttrs.add( new JdbmIndex<String,ServerEntry>( SchemaConstants.OU_AT ) );
system.setIndexedAttributes( indexedAttrs );
service.setSystemPartition( system );
// change the working directory to something that is unique
// on the system and somewhere either under target directory
// or somewhere in a temp area of the machine.
LdapService ldapService = new LdapService();
ldapService.setDirectoryService( service );
<MASK>ldapService.setSocketAcceptor( new NioSocketAcceptor() );</MASK>
int port = AvailablePortFinder.getNextAvailable( 1024 );
ldapService.setTcpTransport( new TcpTransport( port ) );
ldapService.getTcpTransport().setNbThreads( 3 );
ldapService.addExtendedOperationHandler( new StartTlsHandler() );
ldapService.addExtendedOperationHandler( new StoredProcedureExtendedOperationHandler() );
// Setup SASL Mechanisms
Map<String, MechanismHandler> mechanismHandlerMap = new HashMap<String,MechanismHandler>();
mechanismHandlerMap.put( SupportedSaslMechanisms.PLAIN, new SimpleMechanismHandler() );
CramMd5MechanismHandler cramMd5MechanismHandler = new CramMd5MechanismHandler();
mechanismHandlerMap.put( SupportedSaslMechanisms.CRAM_MD5, cramMd5MechanismHandler );
DigestMd5MechanismHandler digestMd5MechanismHandler = new DigestMd5MechanismHandler();
mechanismHandlerMap.put( SupportedSaslMechanisms.DIGEST_MD5, digestMd5MechanismHandler );
GssapiMechanismHandler gssapiMechanismHandler = new GssapiMechanismHandler();
mechanismHandlerMap.put( SupportedSaslMechanisms.GSSAPI, gssapiMechanismHandler );
NtlmMechanismHandler ntlmMechanismHandler = new NtlmMechanismHandler();
mechanismHandlerMap.put( SupportedSaslMechanisms.NTLM, ntlmMechanismHandler );
mechanismHandlerMap.put( SupportedSaslMechanisms.GSS_SPNEGO, ntlmMechanismHandler );
ldapService.setSaslMechanismHandlers( mechanismHandlerMap );
return ldapService;
}"
|
Inversion-Mutation
|
megadiff
|
"@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onPlayerInteract(PlayerInteractEvent event) {
if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)) {
Player player = event.getPlayer();
ItemStack inHand = event.getItem();
if (inHand != null && inHand.getType().equals(Material.WOOD_HOE)) {
if (player.hasPermission("bo3tools.exportbo3")) {
Block clicked = event.getClickedBlock();
plugin.setMetadata(player, BO3Tools.BO3_CENTER_X, clicked.getX());
plugin.setMetadata(player, BO3Tools.BO3_CENTER_Y, clicked.getY());
plugin.setMetadata(player, BO3Tools.BO3_CENTER_Z, clicked.getZ());
player.sendMessage(BaseCommand.MESSAGE_COLOR + "Selected this block as the center of the next BO3 object created using /exportbo3.");
event.setCancelled(true);
}
}
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onPlayerInteract"
|
"@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onPlayerInteract(PlayerInteractEvent event) {
if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)) {
Player player = event.getPlayer();
ItemStack inHand = event.getItem();
if (inHand != null && inHand.getType().equals(Material.WOOD_HOE)) {
if (player.hasPermission("bo3tools.exportbo3")) {
Block clicked = event.getClickedBlock();
plugin.setMetadata(player, BO3Tools.BO3_CENTER_X, clicked.getX());
plugin.setMetadata(player, BO3Tools.BO3_CENTER_Y, clicked.getY());
plugin.setMetadata(player, BO3Tools.BO3_CENTER_Z, clicked.getZ());
player.sendMessage(BaseCommand.MESSAGE_COLOR + "Selected this block as the center of the next BO3 object created using /exportbo3.");
}
}
<MASK>event.setCancelled(true);</MASK>
}
}"
|
Inversion-Mutation
|
megadiff
|
"private static Item getItem(SQLiteDatabase db, long id) {
Cursor cursor = null;
try {
cursor = db.query(ItemTable, new String[] {
ItemID,
ItemImageURL,
ItemName,
ItemDescription,
},
new StringBuilder(ItemID).append(" = ").append(id).toString(),
null, null, null, null);
if(cursor.getCount() == 0) {
return null;
} else {
int idIndex = cursor.getColumnIndex(ItemID);
int imageURLIndex = cursor.getColumnIndex(ItemImageURL);
int nameIndex = cursor.getColumnIndex(ItemName);
int descriptionIndex = cursor.getColumnIndex(ItemDescription);
cursor.moveToFirst();
return new Item(
cursor.getLong(idIndex),
cursor.getString(nameIndex),
cursor.getString(imageURLIndex),
cursor.getString(descriptionIndex));
}
} finally {
if(cursor != null)
cursor.close();
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getItem"
|
"private static Item getItem(SQLiteDatabase db, long id) {
Cursor cursor = null;
try {
cursor = db.query(ItemTable, new String[] {
ItemID,
ItemImageURL,
ItemName,
ItemDescription,
},
new StringBuilder(ItemID).append(" = ").append(id).toString(),
null, null, null, null);
if(cursor.getCount() == 0) {
return null;
} else {
int idIndex = cursor.getColumnIndex(ItemID);
int imageURLIndex = cursor.getColumnIndex(ItemImageURL);
int nameIndex = cursor.getColumnIndex(ItemName);
int descriptionIndex = cursor.getColumnIndex(ItemDescription);
cursor.moveToFirst();
return new Item(
cursor.getLong(idIndex),
<MASK>cursor.getString(imageURLIndex),</MASK>
cursor.getString(nameIndex),
cursor.getString(descriptionIndex));
}
} finally {
if(cursor != null)
cursor.close();
}
}"
|
Inversion-Mutation
|
megadiff
|
"@Override
public void setEnabled(final boolean enabled) {
triggerList.setEnabled(enabled);
add.setEnabled(trigger.getSelectedIndex() != -1);
if (trigger.getModel().getSize() > 0 && enabled) {
trigger.setEnabled(enabled);
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setEnabled"
|
"@Override
public void setEnabled(final boolean enabled) {
triggerList.setEnabled(enabled);
if (trigger.getModel().getSize() > 0 && enabled) {
trigger.setEnabled(enabled);
<MASK>add.setEnabled(trigger.getSelectedIndex() != -1);</MASK>
}
}"
|
Inversion-Mutation
|
megadiff
|
"public void handleRefresh() {
ProgressDialog.Builder pb = new ProgressDialog.Builder(this);
pb.setMessage("Logging In...");
AlertDialog progressDialog = pb.create();
progressDialog.setOwnerActivity(this);
progressDialog.show();
try {
String username = ((EditText)findViewById(R.id.login_username)).getText().toString();
String password = ((EditText)findViewById(R.id.login_password)).getText().toString();
DrupalUser drupalUser = drupalSiteContext.login(username, password);
if (drupalUser != null) {
createBanner(drupalUser);
Intent intent = new Intent(this.getApplicationContext(), DrupalTaxonomyListActivity.class);
this.startActivity(intent);
progressDialog.dismiss();
} else {
// login failed
//
progressDialog.dismiss();
pb.setMessage("Invalid login");
progressDialog = pb.create();
progressDialog.show();
}
} catch (DrupalLoginException e) {
progressDialog.dismiss();
DrupalDialogHandler.showMessageDialog(this, e.getMessage());
} catch (DrupalFetchException e) {
progressDialog.dismiss();
DrupalDialogHandler.showMessageDialog(this, e.getMessage());
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handleRefresh"
|
"public void handleRefresh() {
ProgressDialog.Builder pb = new ProgressDialog.Builder(this);
pb.setMessage("Logging In...");
AlertDialog progressDialog = pb.create();
progressDialog.setOwnerActivity(this);
progressDialog.show();
try {
String username = ((EditText)findViewById(R.id.login_username)).getText().toString();
String password = ((EditText)findViewById(R.id.login_password)).getText().toString();
DrupalUser drupalUser = drupalSiteContext.login(username, password);
if (drupalUser != null) {
createBanner(drupalUser);
Intent intent = new Intent(this.getApplicationContext(), DrupalTaxonomyListActivity.class);
this.startActivity(intent);
} else {
// login failed
//
<MASK>progressDialog.dismiss();</MASK>
pb.setMessage("Invalid login");
progressDialog = pb.create();
progressDialog.show();
}
<MASK>progressDialog.dismiss();</MASK>
} catch (DrupalLoginException e) {
<MASK>progressDialog.dismiss();</MASK>
DrupalDialogHandler.showMessageDialog(this, e.getMessage());
} catch (DrupalFetchException e) {
<MASK>progressDialog.dismiss();</MASK>
DrupalDialogHandler.showMessageDialog(this, e.getMessage());
}
}"
|
Inversion-Mutation
|
megadiff
|
"public static void main(String[] args) {
// So jung kommen wir nicht mehr zusammen.
final CommandLineArguments commandLineArguments = new CommandLineArguments();
final JCommander jCommander = new JCommander(commandLineArguments, args);
jCommander.setProgramName("graylog2");
if (commandLineArguments.isShowHelp()) {
jCommander.usage();
System.exit(0);
}
if (commandLineArguments.isShowVersion()) {
System.out.println("Graylog2 Server " + Core.GRAYLOG2_VERSION);
System.out.println("JRE: " + Tools.getSystemInformation());
System.exit(0);
}
String configFile = commandLineArguments.getConfigFile();
LOG.info("Using config file: {}", configFile);
final Configuration configuration = new Configuration();
JadConfig jadConfig = new JadConfig(new PropertiesRepository(configFile), configuration);
LOG.info("Loading configuration");
try {
jadConfig.process();
} catch (RepositoryException e) {
LOG.error("Couldn't load configuration file " + configFile, e);
System.exit(1);
} catch (ValidationException e) {
LOG.error("Invalid configuration", e);
System.exit(1);
}
if (commandLineArguments.isInstallPlugin()) {
System.out.println("Plugin installation requested.");
PluginInstaller installer = new PluginInstaller(
commandLineArguments.getPluginShortname(),
commandLineArguments.getPluginVersion(),
configuration,
commandLineArguments.isForcePlugin()
);
installer.install();
System.exit(0);
}
// Are we in debug mode?
if (commandLineArguments.isDebug()) {
LOG.info("Running in Debug mode");
org.apache.log4j.Logger.getRootLogger().setLevel(Level.ALL);
org.apache.log4j.Logger.getLogger(Main.class.getPackage().getName()).setLevel(Level.ALL);
}
LOG.info("Graylog2 {} starting up. (JRE: {})", Core.GRAYLOG2_VERSION, Tools.getSystemInformation());
// If we only want to check our configuration, we just initialize the rules engine to check if the rules compile
if (commandLineArguments.isConfigTest()) {
Core server = new Core();
server.setConfiguration(configuration);
DroolsInitializer drools = new DroolsInitializer();
try {
drools.initialize(server, null);
} catch (InitializerConfigurationException e) {
LOG.error("Drools initialization failed.", e);
}
// rules have been checked, exit gracefully
System.exit(0);
}
// Do not use a PID file if the user requested not to
if (!commandLineArguments.isNoPidFile()) {
savePidFile(commandLineArguments.getPidFile());
}
// Le server object. This is where all the magic happens.
Core server = new Core();
server.initialize(configuration);
// Could it be that there is another master instance already?
if (configuration.isMaster() && server.cluster().masterCountExcept(server.getServerId()) != 0) {
LOG.warn("Detected another master in the cluster. Retrying in {} seconds to make sure it is not "
+ "an old stale instance.", Cluster.PING_TIMEOUT);
try {
Thread.sleep(Cluster.PING_TIMEOUT*1000);
} catch (InterruptedException e) { /* nope */ }
if (server.cluster().masterCountExcept(server.getServerId()) != 0) {
// All devils here.
String what = "Detected other master node in the cluster! Starting as non-master! "
+ "This is a mis-configuration you should fix.";
LOG.warn(what);
server.getActivityWriter().write(new Activity(what, Main.class));
configuration.setIsMaster(false);
} else {
LOG.warn("Stale master has gone. Starting as master.");
}
}
// Enable local mode?
if (commandLineArguments.isLocal() || commandLineArguments.isDebug()) {
// In local mode, systemstats are sent to localhost for example.
LOG.info("Running in local mode");
server.setLocalMode(true);
}
// Are we in stats mode?
if (commandLineArguments.isStats()) {
LOG.info("Printing system utilization information.");
server.setStatsMode(true);
}
// Register transports.
if (configuration.isTransportEmailEnabled()) { server.registerTransport(new EmailTransport()); }
if (configuration.isTransportJabberEnabled()) { server.registerTransport(new JabberTransport()); }
// Register initializers.
server.registerInitializer(new ServerValueWriterInitializer());
server.registerInitializer(new DroolsInitializer());
server.registerInitializer(new HostCounterCacheWriterInitializer());
server.registerInitializer(new MessageCounterInitializer());
server.registerInitializer(new AlarmScannerInitializer());
if (configuration.isEnableGraphiteOutput()) { server.registerInitializer(new GraphiteInitializer()); }
if (configuration.isEnableLibratoMetricsOutput()) { server.registerInitializer(new LibratoMetricsInitializer()); }
server.registerInitializer(new DeflectorThreadsInitializer());
server.registerInitializer(new AnonymousInformationCollectorInitializer());
if (configuration.performRetention() && commandLineArguments.performRetention()) {
server.registerInitializer(new IndexRetentionInitializer());
}
if (configuration.isAmqpEnabled()) {
server.registerInitializer(new AMQPSyncInitializer());
}
server.registerInitializer(new BufferWatermarkInitializer());
if (commandLineArguments.isStats()) { server.registerInitializer(new StatisticsPrinterInitializer()); }
server.registerInitializer(new MasterCacheWorkersInitializer());
// Register inputs.
if (configuration.isUseGELF()) {
server.registerInput(new GELFUDPInput());
server.registerInput(new GELFTCPInput());
}
if (configuration.isSyslogUdpEnabled()) { server.registerInput(new SyslogUDPInput()); }
if (configuration.isSyslogTcpEnabled()) { server.registerInput(new SyslogTCPInput()); }
if (configuration.isAmqpEnabled()) { server.registerInput(new AMQPInput()); }
if (configuration.isHttpEnabled()) { server.registerInput(new GELFHttpInput()); }
// Register message filters.
server.registerFilter(new BlacklistFilter());
if (configuration.isEnableTokenizerFilter()) { server.registerFilter(new TokenizerFilter()); }
server.registerFilter(new StreamMatcherFilter());
server.registerFilter(new RewriteFilter());
server.registerFilter(new CounterUpdateFilter());
// Register outputs.
server.registerOutput(new ElasticSearchOutput());
try {
server.startRestApi();
} catch(Exception e) {
LOG.error("Could not start REST API. Terminating.", e);
System.exit(1);
}
// Blocks until we shut down.
server.run();
LOG.info("Graylog2 {} exiting.", Core.GRAYLOG2_VERSION);
}"
|
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) {
// So jung kommen wir nicht mehr zusammen.
final CommandLineArguments commandLineArguments = new CommandLineArguments();
final JCommander jCommander = new JCommander(commandLineArguments, args);
jCommander.setProgramName("graylog2");
if (commandLineArguments.isShowHelp()) {
jCommander.usage();
System.exit(0);
}
if (commandLineArguments.isShowVersion()) {
System.out.println("Graylog2 Server " + Core.GRAYLOG2_VERSION);
System.out.println("JRE: " + Tools.getSystemInformation());
System.exit(0);
}
String configFile = commandLineArguments.getConfigFile();
LOG.info("Using config file: {}", configFile);
final Configuration configuration = new Configuration();
JadConfig jadConfig = new JadConfig(new PropertiesRepository(configFile), configuration);
LOG.info("Loading configuration");
try {
jadConfig.process();
} catch (RepositoryException e) {
LOG.error("Couldn't load configuration file " + configFile, e);
System.exit(1);
} catch (ValidationException e) {
LOG.error("Invalid configuration", e);
System.exit(1);
}
if (commandLineArguments.isInstallPlugin()) {
System.out.println("Plugin installation requested.");
PluginInstaller installer = new PluginInstaller(
commandLineArguments.getPluginShortname(),
commandLineArguments.getPluginVersion(),
configuration,
commandLineArguments.isForcePlugin()
);
installer.install();
System.exit(0);
}
// Are we in debug mode?
if (commandLineArguments.isDebug()) {
LOG.info("Running in Debug mode");
org.apache.log4j.Logger.getRootLogger().setLevel(Level.ALL);
org.apache.log4j.Logger.getLogger(Main.class.getPackage().getName()).setLevel(Level.ALL);
}
LOG.info("Graylog2 {} starting up. (JRE: {})", Core.GRAYLOG2_VERSION, Tools.getSystemInformation());
// If we only want to check our configuration, we just initialize the rules engine to check if the rules compile
if (commandLineArguments.isConfigTest()) {
Core server = new Core();
server.setConfiguration(configuration);
DroolsInitializer drools = new DroolsInitializer();
try {
drools.initialize(server, null);
} catch (InitializerConfigurationException e) {
LOG.error("Drools initialization failed.", e);
}
// rules have been checked, exit gracefully
System.exit(0);
}
// Do not use a PID file if the user requested not to
if (!commandLineArguments.isNoPidFile()) {
savePidFile(commandLineArguments.getPidFile());
}
// Le server object. This is where all the magic happens.
Core server = new Core();
server.initialize(configuration);
// Could it be that there is another master instance already?
if (configuration.isMaster() && server.cluster().masterCountExcept(server.getServerId()) != 0) {
LOG.warn("Detected another master in the cluster. Retrying in {} seconds to make sure it is not "
+ "an old stale instance.", Cluster.PING_TIMEOUT);
try {
Thread.sleep(Cluster.PING_TIMEOUT*1000);
} catch (InterruptedException e) { /* nope */ }
if (server.cluster().masterCountExcept(server.getServerId()) != 0) {
// All devils here.
String what = "Detected other master node in the cluster! Starting as non-master! "
+ "This is a mis-configuration you should fix.";
LOG.warn(what);
server.getActivityWriter().write(new Activity(what, Main.class));
configuration.setIsMaster(false);
} else {
LOG.warn("Stale master has gone. Starting as master.");
}
}
// Enable local mode?
if (commandLineArguments.isLocal() || commandLineArguments.isDebug()) {
// In local mode, systemstats are sent to localhost for example.
LOG.info("Running in local mode");
server.setLocalMode(true);
}
// Are we in stats mode?
if (commandLineArguments.isStats()) {
LOG.info("Printing system utilization information.");
server.setStatsMode(true);
}
// Register transports.
if (configuration.isTransportEmailEnabled()) { server.registerTransport(new EmailTransport()); }
if (configuration.isTransportJabberEnabled()) { server.registerTransport(new JabberTransport()); }
// Register initializers.
server.registerInitializer(new ServerValueWriterInitializer());
server.registerInitializer(new DroolsInitializer());
server.registerInitializer(new HostCounterCacheWriterInitializer());
server.registerInitializer(new MessageCounterInitializer());
server.registerInitializer(new AlarmScannerInitializer());
if (configuration.isEnableGraphiteOutput()) { server.registerInitializer(new GraphiteInitializer()); }
if (configuration.isEnableLibratoMetricsOutput()) { server.registerInitializer(new LibratoMetricsInitializer()); }
server.registerInitializer(new DeflectorThreadsInitializer());
server.registerInitializer(new AnonymousInformationCollectorInitializer());
if (configuration.performRetention() && commandLineArguments.performRetention()) {
server.registerInitializer(new IndexRetentionInitializer());
}
if (configuration.isAmqpEnabled()) {
server.registerInitializer(new AMQPSyncInitializer());
}
server.registerInitializer(new BufferWatermarkInitializer());
if (commandLineArguments.isStats()) { server.registerInitializer(new StatisticsPrinterInitializer()); }
server.registerInitializer(new MasterCacheWorkersInitializer());
// Register inputs.
if (configuration.isUseGELF()) {
server.registerInput(new GELFUDPInput());
server.registerInput(new GELFTCPInput());
}
if (configuration.isSyslogUdpEnabled()) { server.registerInput(new SyslogUDPInput()); }
if (configuration.isSyslogTcpEnabled()) { server.registerInput(new SyslogTCPInput()); }
if (configuration.isAmqpEnabled()) { server.registerInput(new AMQPInput()); }
if (configuration.isHttpEnabled()) { server.registerInput(new GELFHttpInput()); }
// Register message filters.
server.registerFilter(new BlacklistFilter());
if (configuration.isEnableTokenizerFilter()) { server.registerFilter(new TokenizerFilter()); }
server.registerFilter(new StreamMatcherFilter());
<MASK>server.registerFilter(new CounterUpdateFilter());</MASK>
server.registerFilter(new RewriteFilter());
// Register outputs.
server.registerOutput(new ElasticSearchOutput());
try {
server.startRestApi();
} catch(Exception e) {
LOG.error("Could not start REST API. Terminating.", e);
System.exit(1);
}
// Blocks until we shut down.
server.run();
LOG.info("Graylog2 {} exiting.", Core.GRAYLOG2_VERSION);
}"
|
Inversion-Mutation
|
megadiff
|
"public GUIInstallData provide(ResourceManager resourceManager, VariableSubstitutor variableSubstitutor, Properties variables, ClassPathCrawler classPathCrawler, BindeableContainer container) throws Exception
{
this.resourceManager = resourceManager;
this.variableSubstitutor = variableSubstitutor;
this.classPathCrawler = classPathCrawler;
final GUIInstallData guiInstallData = new GUIInstallData(variables, variableSubstitutor);
// Loads the installation data
loadInstallData(guiInstallData);
// Load custom action data.
// loadCustomData(guiInstallData, container, pathResolver);
loadGUIInstallData(guiInstallData);
loadInstallerRequirements(guiInstallData);
loadDynamicVariables(guiInstallData);
loadDynamicConditions(guiInstallData);
loadDefaultLocale(guiInstallData);
// Load custom langpack if exist.
addCustomLangpack(guiInstallData);
loadLookAndFeel(guiInstallData);
if (UIManager.getColor("Button.background") != null)
{
guiInstallData.buttonsHColor = UIManager.getColor("Button.background");
}
return guiInstallData;
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "provide"
|
"public GUIInstallData provide(ResourceManager resourceManager, VariableSubstitutor variableSubstitutor, Properties variables, ClassPathCrawler classPathCrawler, BindeableContainer container) throws Exception
{
this.resourceManager = resourceManager;
this.variableSubstitutor = variableSubstitutor;
this.classPathCrawler = classPathCrawler;
final GUIInstallData guiInstallData = new GUIInstallData(variables, variableSubstitutor);
// Loads the installation data
loadInstallData(guiInstallData);
// Load custom action data.
// loadCustomData(guiInstallData, container, pathResolver);
loadGUIInstallData(guiInstallData);
loadInstallerRequirements(guiInstallData);
loadDynamicVariables(guiInstallData);
loadDynamicConditions(guiInstallData);
// Load custom langpack if exist.
addCustomLangpack(guiInstallData);
<MASK>loadDefaultLocale(guiInstallData);</MASK>
loadLookAndFeel(guiInstallData);
if (UIManager.getColor("Button.background") != null)
{
guiInstallData.buttonsHColor = UIManager.getColor("Button.background");
}
return guiInstallData;
}"
|
Inversion-Mutation
|
megadiff
|
"@Override
protected void onHandleIntent(Intent intent) {
if (intent.getIntExtra(EXTRA_ACTION, 0) == ADD_LOG) {
if (intent.hasExtra(EXTRA_APP_ID)) {
addLog(intent.getLongExtra(EXTRA_APP_ID, 0),
intent.getIntExtra(EXTRA_ALLOW, 0));
} else {
int appUid = intent.getIntExtra(EXTRA_APP_UID, 0);
Uri appUri = Uri.withAppendedPath(Apps.CONTENT_URI, "uid/" + appUid);
Log.d(TAG, "Looking for app with UID of " + appUid);
Log.d(TAG, "Using uri: " + appUri);
Cursor c = mCr.query(appUri, new String[] { Apps._ID }, null, null, null);
if (c != null && c.moveToFirst()) {
Log.d(TAG, "app_id=" + c.getLong(c.getColumnIndex(Apps._ID)));
addLog(c.getLong(c.getColumnIndex(Apps._ID)),
intent.getIntExtra(EXTRA_ALLOW, 0));
c.close();
} else {
Log.d(TAG, "app_id not found, add it to the database");
addAppAndLog(intent);
}
}
recycle();
} else if (intent.getIntExtra(EXTRA_ACTION, 0) == RECYCLE) {
recycle();
} else {
throw new IllegalArgumentException();
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onHandleIntent"
|
"@Override
protected void onHandleIntent(Intent intent) {
if (intent.getIntExtra(EXTRA_ACTION, 0) == ADD_LOG) {
if (intent.hasExtra(EXTRA_APP_ID)) {
addLog(intent.getLongExtra(EXTRA_APP_ID, 0),
intent.getIntExtra(EXTRA_ALLOW, 0));
} else {
int appUid = intent.getIntExtra(EXTRA_APP_UID, 0);
Uri appUri = Uri.withAppendedPath(Apps.CONTENT_URI, "uid/" + appUid);
Log.d(TAG, "Looking for app with UID of " + appUid);
Log.d(TAG, "Using uri: " + appUri);
Cursor c = mCr.query(appUri, new String[] { Apps._ID }, null, null, null);
if (c != null && c.moveToFirst()) {
Log.d(TAG, "app_id=" + c.getLong(c.getColumnIndex(Apps._ID)));
addLog(c.getLong(c.getColumnIndex(Apps._ID)),
intent.getIntExtra(EXTRA_ALLOW, 0));
} else {
Log.d(TAG, "app_id not found, add it to the database");
addAppAndLog(intent);
}
<MASK>c.close();</MASK>
}
recycle();
} else if (intent.getIntExtra(EXTRA_ACTION, 0) == RECYCLE) {
recycle();
} else {
throw new IllegalArgumentException();
}
}"
|
Inversion-Mutation
|
megadiff
|
"private void displayCardAnswer() {
Log.i(AnkiDroidApp.TAG, "displayCardAnswer");
sDisplayAnswer = true;
if (mPrefTimer) {
mCardTimer.stop();
}
String displayString = "";
// If the user wrote an answer
if (mPrefWriteAnswers) {
mAnswerField.setVisibility(View.GONE);
if (mCurrentCard != null) {
// Obtain the user answer and the correct answer
String userAnswer = mAnswerField.getText().toString();
Matcher matcher = sSpanPattern.matcher(mCurrentCard.getAnswer());
String correctAnswer = matcher.replaceAll("");
matcher = sBrPattern.matcher(correctAnswer);
correctAnswer = matcher.replaceAll("\n");
matcher = Sound.sSoundPattern.matcher(correctAnswer);
correctAnswer = matcher.replaceAll("");
matcher = Image.sImagePattern.matcher(correctAnswer);
correctAnswer = matcher.replaceAll("");
Log.i(AnkiDroidApp.TAG, "correct answer = " + correctAnswer);
// Obtain the diff and send it to updateCard
DiffEngine diff = new DiffEngine();
displayString = enrichWithQASpan(diff.diff_prettyHtml(diff.diff_main(userAnswer, correctAnswer))
+ "<br/>" + mCurrentCard.getAnswer(), true);
}
// Hide soft keyboard
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(mAnswerField.getWindowToken(), 0);
} else {
displayString = enrichWithQASpan(mCurrentCard.getAnswer(), true);
}
// Depending on preferences do or do not show the question
if (isQuestionDisplayed()) {
StringBuffer sb = new StringBuffer();
sb.append(enrichWithQASpan(mCurrentCard.getQuestion(), false));
sb.append("<hr/>");
sb.append(displayString);
displayString = sb.toString();
}
mFlipCard.setVisibility(View.GONE);
showEaseButtons();
updateCard(displayString);
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "displayCardAnswer"
|
"private void displayCardAnswer() {
Log.i(AnkiDroidApp.TAG, "displayCardAnswer");
sDisplayAnswer = true;
if (mPrefTimer) {
mCardTimer.stop();
}
String displayString = "";
// If the user wrote an answer
if (mPrefWriteAnswers) {
mAnswerField.setVisibility(View.GONE);
if (mCurrentCard != null) {
// Obtain the user answer and the correct answer
String userAnswer = mAnswerField.getText().toString();
Matcher matcher = sSpanPattern.matcher(mCurrentCard.getAnswer());
String correctAnswer = matcher.replaceAll("");
matcher = sBrPattern.matcher(correctAnswer);
correctAnswer = matcher.replaceAll("\n");
matcher = Sound.sSoundPattern.matcher(correctAnswer);
correctAnswer = matcher.replaceAll("");
matcher = Image.sImagePattern.matcher(correctAnswer);
correctAnswer = matcher.replaceAll("");
Log.i(AnkiDroidApp.TAG, "correct answer = " + correctAnswer);
// Obtain the diff and send it to updateCard
DiffEngine diff = new DiffEngine();
displayString = enrichWithQASpan(diff.diff_prettyHtml(diff.diff_main(userAnswer, correctAnswer))
+ "<br/>" + mCurrentCard.getAnswer(), true);
}
// Hide soft keyboard
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(mAnswerField.getWindowToken(), 0);
} else {
displayString = enrichWithQASpan(mCurrentCard.getAnswer(), true);
}
// Depending on preferences do or do not show the question
if (isQuestionDisplayed()) {
StringBuffer sb = new StringBuffer();
sb.append(enrichWithQASpan(mCurrentCard.getQuestion(), false));
sb.append("<hr/>");
sb.append(displayString);
displayString = sb.toString();
<MASK>mFlipCard.setVisibility(View.GONE);</MASK>
}
showEaseButtons();
updateCard(displayString);
}"
|
Inversion-Mutation
|
megadiff
|
"@Override
public void onStart(Intent intent, int startId)
{
Log.i(TAG, "Called");
// Create some random data
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this
.getApplicationContext());
int[] allWidgetIds = intent
.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
ComponentName thisWidget = new ComponentName(getApplicationContext(), LargeWidgetProvider.class);
int[] allWidgetIds2 = appWidgetManager.getAppWidgetIds(thisWidget);
Log.w(TAG, "From Intent" + String.valueOf(allWidgetIds.length));
Log.w(TAG, "Direct" + String.valueOf(allWidgetIds2.length));
StatsProvider stats = StatsProvider.getInstance(this);
// make sure to flush cache
BatteryStatsProxy.getInstance(this).invalidate();
if (!stats.hasCustomRef())
{
// restore any available custom reference
StatsProvider.getInstance(this).deserializeFromFile();
}
for (int widgetId : allWidgetIds)
{
RemoteViews remoteViews = new RemoteViews(this
.getApplicationContext().getPackageName(),
R.layout.large_widget_layout);
// we change the bg color of the layout based on alpha from prefs
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
int opacity = sharedPrefs.getInt("large_widget_bg_opacity", 20);
opacity = (255 * opacity) / 100;
remoteViews.setInt(R.id.layout, "setBackgroundColor", (opacity << 24) & android.graphics.Color.BLACK);
// retrieve stats
int statType = StatsProvider.statTypeFromPosition(
Integer.valueOf(sharedPrefs.getString("large_widget_default_stat_type", "1")));
boolean showPct = sharedPrefs.getBoolean("large_widget_show_pct", false);
boolean showTitle = sharedPrefs.getBoolean("widget_show_stat_type", true);
long timeAwake = 0;
long timeDeepSleep = 0;
long timeScreenOn = 0;
long timeSince = 0;
long sumPWakelocks = 0;
long sumKWakelocks = 0;
try
{
ArrayList<StatElement> otherStats = stats.getOtherUsageStatList(true, statType);
if ( (otherStats != null) && ( otherStats.size() > 1) )
{
timeAwake = ((Misc) stats.getElementByKey(otherStats, "Awake")).getTimeOn();
timeScreenOn = ((Misc) stats.getElementByKey(otherStats, "Screen On")).getTimeOn();
timeSince = stats.getBatteryRealtime(statType);
ArrayList<StatElement> pWakelockStats = stats.getWakelockStatList(true, statType, 0, 0);
sumPWakelocks = stats.sum(pWakelockStats);
ArrayList<StatElement> kWakelockStats = stats.getNativeKernelWakelockStatList(true, statType, 0, 0);
sumKWakelocks = stats.sum(kWakelockStats);
Misc deepSleepStat = ((Misc) stats.getElementByKey(otherStats, "Deep Sleep"));
if (deepSleepStat != null)
{
timeDeepSleep = deepSleepStat.getTimeOn();
}
else
{
timeDeepSleep = 0;
}
if (!showTitle)
{
remoteViews.setInt(R.id.stat_type, "setVisibility", View.GONE);
}
// Set the text
remoteViews.setTextViewText(R.id.stat_type, StatsProvider.statTypeToLabel(statType));
remoteViews.setTextViewText(R.id.since, DateUtils.formatDuration(timeSince));
if (showPct)
{
remoteViews.setTextViewText(R.id.awake, StringUtils.formatRatio(timeAwake, timeSince));
remoteViews.setTextViewText(R.id.deep_sleep, StringUtils.formatRatio(timeDeepSleep, timeSince));
remoteViews.setTextViewText(R.id.screen_on, StringUtils.formatRatio(timeScreenOn, timeSince));
}
else
{
remoteViews.setTextViewText(R.id.awake, DateUtils.formatDuration(timeAwake));
remoteViews.setTextViewText(R.id.deep_sleep, DateUtils.formatDuration(timeDeepSleep));
remoteViews.setTextViewText(R.id.screen_on, DateUtils.formatDuration(timeScreenOn));
}
// and the font size
float fontSize = Float.valueOf(sharedPrefs.getString("large_widget_font_size", "10"));
remoteViews.setFloat(R.id.staticSince, "setTextSize", fontSize);
remoteViews.setFloat(R.id.staticAwake, "setTextSize", fontSize);
remoteViews.setFloat(R.id.staticDeepSleep, "setTextSize", fontSize);
remoteViews.setFloat(R.id.staticScreenOn, "setTextSize", fontSize);
remoteViews.setFloat(R.id.staticKWL, "setTextSize", fontSize);
remoteViews.setFloat(R.id.staticPWL, "setTextSize", fontSize);
remoteViews.setFloat(R.id.stat_type, "setTextSize", fontSize);
remoteViews.setFloat(R.id.since, "setTextSize", fontSize);
remoteViews.setFloat(R.id.awake, "setTextSize", fontSize);
remoteViews.setFloat(R.id.deep_sleep, "setTextSize", fontSize);
remoteViews.setFloat(R.id.screen_on, "setTextSize", fontSize);
remoteViews.setFloat(R.id.kwl, "setTextSize", fontSize);
remoteViews.setFloat(R.id.wl, "setTextSize", fontSize);
if ( (sumPWakelocks == 1) && (pWakelockStats.size()==1) )
{
// there was no reference
remoteViews.setTextViewText(R.id.wl, "n/a");
}
else
{
if (showPct)
{
remoteViews.setTextViewText(R.id.wl, StringUtils.formatRatio(sumPWakelocks, timeSince));
}
else
{
remoteViews.setTextViewText(R.id.wl, DateUtils.formatDuration(sumPWakelocks));
}
}
if ( (sumKWakelocks == 1) && (kWakelockStats.size()==1) )
{
// there was no reference
remoteViews.setTextViewText(R.id.kwl, "n/a");
}
else
{
if (showPct)
{
remoteViews.setTextViewText(R.id.kwl, StringUtils.formatRatio(sumKWakelocks, timeSince));
}
else
{
remoteViews.setTextViewText(R.id.kwl, DateUtils.formatDuration(sumKWakelocks));
}
}
WidgetBars graph = new WidgetBars();
ArrayList<Long> serie = new ArrayList<Long>();
serie.add(timeSince);
serie.add(timeDeepSleep);
serie.add(timeAwake);
serie.add(timeScreenOn);
serie.add(sumKWakelocks);
serie.add(sumPWakelocks);
remoteViews.setImageViewBitmap(R.id.graph, graph.getBitmap(this, serie));
}
else
{
// no stat available
// Set the text
String notAvailable = "n/a";
remoteViews.setTextViewText(R.id.stat_type, StatsProvider.statTypeToLabel(statType));
remoteViews.setTextViewText(R.id.since, notAvailable);
remoteViews.setTextViewText(R.id.awake, notAvailable);
remoteViews.setTextViewText(R.id.screen_on, notAvailable);
remoteViews.setTextViewText(R.id.wl, notAvailable);
remoteViews.setTextViewText(R.id.kwl, notAvailable);
}
}
catch (Exception e)
{
Log.e(TAG,"An error occured: " + e.getMessage());
GenericLogger.stackTrace(TAG, e.getStackTrace());
}
finally
{
Log.d(TAG, "Since: " + DateUtils.formatDuration(timeSince));
Log.d(TAG, "Awake: " + DateUtils.formatDuration(timeAwake));
Log.d(TAG, "Screen on: " + DateUtils.formatDuration(timeScreenOn));
Log.d(TAG, "P. Wl.: " + DateUtils.formatDuration(sumPWakelocks));
Log.d(TAG, "K. Wl.: " + DateUtils.formatDuration(sumKWakelocks));
// Register an onClickListener for the graph -> refresh
Intent clickIntent = new Intent(this.getApplicationContext(),
LargeWidgetProvider.class);
clickIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
clickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,
allWidgetIds);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
getApplicationContext(), 0, clickIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.layout, pendingIntent);
// Register an onClickListener for the widget -> call main activity
Intent i = new Intent(Intent.ACTION_MAIN);
PackageManager manager = getPackageManager();
i = manager.getLaunchIntentForPackage(getPackageName());
i.addCategory(Intent.CATEGORY_LAUNCHER);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent clickPI = PendingIntent.getActivity(
this.getApplicationContext(), 0,
i, 0);
remoteViews.setOnClickPendingIntent(R.id.graph, clickPI);
appWidgetManager.updateAppWidget(widgetId, remoteViews);
}
}
stopSelf();
super.onStart(intent, startId);
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onStart"
|
"@Override
public void onStart(Intent intent, int startId)
{
Log.i(TAG, "Called");
// Create some random data
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this
.getApplicationContext());
int[] allWidgetIds = intent
.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
ComponentName thisWidget = new ComponentName(getApplicationContext(), LargeWidgetProvider.class);
int[] allWidgetIds2 = appWidgetManager.getAppWidgetIds(thisWidget);
Log.w(TAG, "From Intent" + String.valueOf(allWidgetIds.length));
Log.w(TAG, "Direct" + String.valueOf(allWidgetIds2.length));
StatsProvider stats = StatsProvider.getInstance(this);
// make sure to flush cache
BatteryStatsProxy.getInstance(this).invalidate();
if (!stats.hasCustomRef())
{
// restore any available custom reference
StatsProvider.getInstance(this).deserializeFromFile();
}
for (int widgetId : allWidgetIds)
{
RemoteViews remoteViews = new RemoteViews(this
.getApplicationContext().getPackageName(),
R.layout.large_widget_layout);
// we change the bg color of the layout based on alpha from prefs
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
int opacity = sharedPrefs.getInt("large_widget_bg_opacity", 20);
opacity = (255 * opacity) / 100;
remoteViews.setInt(R.id.layout, "setBackgroundColor", (opacity << 24) & android.graphics.Color.BLACK);
// retrieve stats
int statType = StatsProvider.statTypeFromPosition(
Integer.valueOf(sharedPrefs.getString("large_widget_default_stat_type", "1")));
boolean showPct = sharedPrefs.getBoolean("large_widget_show_pct", false);
boolean showTitle = sharedPrefs.getBoolean("widget_show_stat_type", true);
long timeAwake = 0;
long timeDeepSleep = 0;
long timeScreenOn = 0;
long timeSince = 0;
long sumPWakelocks = 0;
long sumKWakelocks = 0;
try
{
ArrayList<StatElement> otherStats = stats.getOtherUsageStatList(true, statType);
if ( (otherStats != null) && ( otherStats.size() > 1) )
{
timeAwake = ((Misc) stats.getElementByKey(otherStats, "Awake")).getTimeOn();
timeScreenOn = ((Misc) stats.getElementByKey(otherStats, "Screen On")).getTimeOn();
timeSince = stats.getBatteryRealtime(statType);
ArrayList<StatElement> pWakelockStats = stats.getWakelockStatList(true, statType, 0, 0);
sumPWakelocks = stats.sum(pWakelockStats);
ArrayList<StatElement> kWakelockStats = stats.getNativeKernelWakelockStatList(true, statType, 0, 0);
sumKWakelocks = stats.sum(kWakelockStats);
Misc deepSleepStat = ((Misc) stats.getElementByKey(otherStats, "Deep Sleep"));
if (deepSleepStat != null)
{
timeDeepSleep = deepSleepStat.getTimeOn();
}
else
{
timeDeepSleep = 0;
}
if (!showTitle)
{
remoteViews.setInt(R.id.stat_type, "setVisibility", View.GONE);
}
// Set the text
remoteViews.setTextViewText(R.id.stat_type, StatsProvider.statTypeToLabel(statType));
remoteViews.setTextViewText(R.id.since, DateUtils.formatDuration(timeSince));
if (showPct)
{
remoteViews.setTextViewText(R.id.awake, StringUtils.formatRatio(timeAwake, timeSince));
remoteViews.setTextViewText(R.id.deep_sleep, StringUtils.formatRatio(timeDeepSleep, timeSince));
remoteViews.setTextViewText(R.id.screen_on, StringUtils.formatRatio(timeScreenOn, timeSince));
}
else
{
remoteViews.setTextViewText(R.id.awake, DateUtils.formatDuration(timeAwake));
remoteViews.setTextViewText(R.id.deep_sleep, DateUtils.formatDuration(timeDeepSleep));
remoteViews.setTextViewText(R.id.screen_on, DateUtils.formatDuration(timeScreenOn));
}
// and the font size
float fontSize = Float.valueOf(sharedPrefs.getString("large_widget_font_size", "10"));
remoteViews.setFloat(R.id.staticSince, "setTextSize", fontSize);
remoteViews.setFloat(R.id.staticAwake, "setTextSize", fontSize);
remoteViews.setFloat(R.id.staticDeepSleep, "setTextSize", fontSize);
remoteViews.setFloat(R.id.staticScreenOn, "setTextSize", fontSize);
remoteViews.setFloat(R.id.staticKWL, "setTextSize", fontSize);
remoteViews.setFloat(R.id.staticPWL, "setTextSize", fontSize);
remoteViews.setFloat(R.id.stat_type, "setTextSize", fontSize);
remoteViews.setFloat(R.id.since, "setTextSize", fontSize);
remoteViews.setFloat(R.id.awake, "setTextSize", fontSize);
remoteViews.setFloat(R.id.deep_sleep, "setTextSize", fontSize);
remoteViews.setFloat(R.id.screen_on, "setTextSize", fontSize);
remoteViews.setFloat(R.id.kwl, "setTextSize", fontSize);
remoteViews.setFloat(R.id.wl, "setTextSize", fontSize);
if ( (sumPWakelocks == 1) && (pWakelockStats.size()==1) )
{
// there was no reference
remoteViews.setTextViewText(R.id.wl, "n/a");
}
else
{
if (showPct)
{
remoteViews.setTextViewText(R.id.wl, StringUtils.formatRatio(sumPWakelocks, timeSince));
}
else
{
remoteViews.setTextViewText(R.id.wl, DateUtils.formatDuration(sumPWakelocks));
}
}
if ( (sumKWakelocks == 1) && (kWakelockStats.size()==1) )
{
// there was no reference
remoteViews.setTextViewText(R.id.kwl, "n/a");
}
else
{
if (showPct)
{
remoteViews.setTextViewText(R.id.kwl, StringUtils.formatRatio(sumKWakelocks, timeSince));
}
else
{
remoteViews.setTextViewText(R.id.kwl, DateUtils.formatDuration(sumKWakelocks));
}
}
WidgetBars graph = new WidgetBars();
ArrayList<Long> serie = new ArrayList<Long>();
serie.add(timeSince);
<MASK>serie.add(timeAwake);</MASK>
serie.add(timeDeepSleep);
serie.add(timeScreenOn);
serie.add(sumKWakelocks);
serie.add(sumPWakelocks);
remoteViews.setImageViewBitmap(R.id.graph, graph.getBitmap(this, serie));
}
else
{
// no stat available
// Set the text
String notAvailable = "n/a";
remoteViews.setTextViewText(R.id.stat_type, StatsProvider.statTypeToLabel(statType));
remoteViews.setTextViewText(R.id.since, notAvailable);
remoteViews.setTextViewText(R.id.awake, notAvailable);
remoteViews.setTextViewText(R.id.screen_on, notAvailable);
remoteViews.setTextViewText(R.id.wl, notAvailable);
remoteViews.setTextViewText(R.id.kwl, notAvailable);
}
}
catch (Exception e)
{
Log.e(TAG,"An error occured: " + e.getMessage());
GenericLogger.stackTrace(TAG, e.getStackTrace());
}
finally
{
Log.d(TAG, "Since: " + DateUtils.formatDuration(timeSince));
Log.d(TAG, "Awake: " + DateUtils.formatDuration(timeAwake));
Log.d(TAG, "Screen on: " + DateUtils.formatDuration(timeScreenOn));
Log.d(TAG, "P. Wl.: " + DateUtils.formatDuration(sumPWakelocks));
Log.d(TAG, "K. Wl.: " + DateUtils.formatDuration(sumKWakelocks));
// Register an onClickListener for the graph -> refresh
Intent clickIntent = new Intent(this.getApplicationContext(),
LargeWidgetProvider.class);
clickIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
clickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,
allWidgetIds);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
getApplicationContext(), 0, clickIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.layout, pendingIntent);
// Register an onClickListener for the widget -> call main activity
Intent i = new Intent(Intent.ACTION_MAIN);
PackageManager manager = getPackageManager();
i = manager.getLaunchIntentForPackage(getPackageName());
i.addCategory(Intent.CATEGORY_LAUNCHER);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent clickPI = PendingIntent.getActivity(
this.getApplicationContext(), 0,
i, 0);
remoteViews.setOnClickPendingIntent(R.id.graph, clickPI);
appWidgetManager.updateAppWidget(widgetId, remoteViews);
}
}
stopSelf();
super.onStart(intent, startId);
}"
|
Inversion-Mutation
|
megadiff
|
"private void fillProjectProperties(IProjectProperties projectProperties, ProjectPropertiesTO to) throws PropertiesException,
CoreException {
if (to == null) {
log.info("Project properties not found. Use default.");
} else {
final IWorkingSetManager workingSetManager = PlatformUI.getWorkbench().getWorkingSetManager();
projectProperties.setProjectWorkingSet(workingSetManager.getWorkingSet(to.getWorkingSetName()));
projectProperties.setRuleSetFile(to.getRuleSetFile());
projectProperties.setRuleSetStoredInProject(to.isRuleSetStoredInProject());
projectProperties.setPmdEnabled(projectProperties.getProject().hasNature(PMDNature.PMD_NATURE));
projectProperties.setIncludeDerivedFiles(to.isIncludeDerivedFiles());
if (to.isRuleSetStoredInProject()) {
loadRuleSetFromProject(projectProperties);
} else {
setRuleSetFromProperties(projectProperties, to.getRules());
}
log.debug("Project properties loaded");
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "fillProjectProperties"
|
"private void fillProjectProperties(IProjectProperties projectProperties, ProjectPropertiesTO to) throws PropertiesException,
CoreException {
if (to == null) {
log.info("Project properties not found. Use default.");
} else {
final IWorkingSetManager workingSetManager = PlatformUI.getWorkbench().getWorkingSetManager();
projectProperties.setProjectWorkingSet(workingSetManager.getWorkingSet(to.getWorkingSetName()));
<MASK>projectProperties.setRuleSetStoredInProject(to.isRuleSetStoredInProject());</MASK>
projectProperties.setRuleSetFile(to.getRuleSetFile());
projectProperties.setPmdEnabled(projectProperties.getProject().hasNature(PMDNature.PMD_NATURE));
projectProperties.setIncludeDerivedFiles(to.isIncludeDerivedFiles());
if (to.isRuleSetStoredInProject()) {
loadRuleSetFromProject(projectProperties);
} else {
setRuleSetFromProperties(projectProperties, to.getRules());
}
log.debug("Project properties loaded");
}
}"
|
Inversion-Mutation
|
megadiff
|
"@Test
public void testAddTwo() {
Symbol sym = Symbol.of("HACKEM MUCHE");
ScoredId id1 = new ScoredIdBuilder(42, 3.5).addChannel(sym, Math.PI).build();
ScoredId id2 = new ScoredIdBuilder(38, 2.6).addChannel(sym, Math.E).build();
builder.add(id1);
builder.add(id2);
assertThat(builder.size(), equalTo(2));
PackedScoredIdList list = builder.build();
assertThat(list.get(0), equalTo(id1));
assertThat(list.get(1), equalTo(id2));
Iterator<ScoredId> iter = list.iterator();
assertThat(Lists.newArrayList(iter),
contains(id1, id2));
assertThat(iter.hasNext(), equalTo(false));
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "testAddTwo"
|
"@Test
public void testAddTwo() {
Symbol sym = Symbol.of("HACKEM MUCHE");
ScoredId id1 = new ScoredIdBuilder(42, 3.5).addChannel(sym, Math.PI).build();
ScoredId id2 = new ScoredIdBuilder(38, 2.6).addChannel(sym, Math.E).build();
<MASK>assertThat(builder.size(), equalTo(2));</MASK>
builder.add(id1);
builder.add(id2);
PackedScoredIdList list = builder.build();
assertThat(list.get(0), equalTo(id1));
assertThat(list.get(1), equalTo(id2));
Iterator<ScoredId> iter = list.iterator();
assertThat(Lists.newArrayList(iter),
contains(id1, id2));
assertThat(iter.hasNext(), equalTo(false));
}"
|
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
|
"protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
if(serverManager==null)
initialize();
revieweeName = req.getParameter("revieweeuser");
String contextString = req.getContextPath();
String pathInfo = req.getPathInfo();
User user = (User) req.getSession().getAttribute(IDavinciServerConstants.SESSION_USER);
if(user==null){
req.getSession().setAttribute(IDavinciServerConstants.REDIRECT_TO, req.getRequestURL().toString());
resp.sendRedirect(this.getLoginUrl(req));
return;
}
if (pathInfo == null || pathInfo.equals("")) {
ReviewObject reviewObject = (ReviewObject) req.getSession().getAttribute(
Constants.REVIEW_INFO);
if (reviewObject == null) {
// Because the requested URL is /review so the empty review object means we
// can not have a designer name. Error.
// resp.setHeader("referrer", contextString +"review.html" );
resp.sendRedirect(this.getLoginUrl(req));
return;
} else {
resp.addCookie(new Cookie(Constants.REVIEW_COOKIE_DESIGNER, reviewObject.getDesignerName()));
resp.addCookie(new Cookie(Constants.REVIEW_COOKIE_DESIGNER_EMAIL, reviewObject.getDesignerEmail()));
if (reviewObject.getCommentId() != null)
resp.addCookie(new Cookie(Constants.REVIEW_COOKIE_CMTID,
reviewObject.getCommentId()));
if (reviewObject.getFile() != null)
resp.addCookie(new Cookie(Constants.REVIEW_COOKIE_FILE,
reviewObject.getFile()));
writeReviewPage(req, resp, "review.html");
}
} else {
IPath path = new Path(pathInfo);
String prefix = path.segment(0);
if(prefix == null){
resp.sendRedirect(contextString + "/review");
return;
}
if(handleReviewRequest(req, resp, path) || handleLibraryRequest(req, resp, path, user)) {
return;
}
if (prefix.equals(IDavinciServerConstants.APP_URL.substring(1))
// || prefix.equals(IDavinciServerConstants.USER_URL.substring(1))
|| prefix.equals(Constants.CMD_URL.substring(1))) {
// Forward to DavinciPageServlet such as "/app/img/1.jpg"
req.getRequestDispatcher(pathInfo).forward(req, resp);
return;
}
// Check if it is a valid user name.
// If it is a valid user name, do login
// Else, error.
User designer = userManager.getUser(prefix);
if (designer == null) {
resp.sendRedirect(this.getLoginUrl(req));
return;
} else {
ReviewObject reviewObject = new ReviewObject(prefix);
reviewObject.setDesignerEmail(designer.getPerson().getEmail());
if (path.segmentCount() > 2) {
// Token = 20100101/project1/folder1/sample1.html/default
String commentId = path.segment(path.segmentCount() - 1);
String fileName = path.removeLastSegments(1).removeFirstSegments(1)
.toPortableString();
reviewObject.setFile(fileName);
reviewObject.setCommentId(commentId);
}
req.getSession().setAttribute(Constants.REVIEW_INFO, reviewObject);
resp.sendRedirect(contextString + "/review");
return;
}
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doGet"
|
"protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
if(serverManager==null)
initialize();
revieweeName = req.getParameter("revieweeuser");
String contextString = req.getContextPath();
String pathInfo = req.getPathInfo();
User user = (User) req.getSession().getAttribute(IDavinciServerConstants.SESSION_USER);
if(user==null){
req.getSession().setAttribute(IDavinciServerConstants.REDIRECT_TO, req.getRequestURL().toString());
resp.sendRedirect(this.getLoginUrl(req));
return;
}
if (pathInfo == null || pathInfo.equals("")) {
ReviewObject reviewObject = (ReviewObject) req.getSession().getAttribute(
Constants.REVIEW_INFO);
if (reviewObject == null) {
// Because the requested URL is /review so the empty review object means we
// can not have a designer name. Error.
// resp.setHeader("referrer", contextString +"review.html" );
resp.sendRedirect(this.getLoginUrl(req));
return;
} else {
resp.addCookie(new Cookie(Constants.REVIEW_COOKIE_DESIGNER, reviewObject.getDesignerName()));
resp.addCookie(new Cookie(Constants.REVIEW_COOKIE_DESIGNER_EMAIL, reviewObject.getDesignerEmail()));
if (reviewObject.getCommentId() != null)
resp.addCookie(new Cookie(Constants.REVIEW_COOKIE_CMTID,
reviewObject.getCommentId()));
if (reviewObject.getFile() != null)
resp.addCookie(new Cookie(Constants.REVIEW_COOKIE_FILE,
reviewObject.getFile()));
writeReviewPage(req, resp, "review.html");
}
} else {
IPath path = new Path(pathInfo);
String prefix = path.segment(0);
if(prefix == null){
resp.sendRedirect(contextString + "/review");
return;
}
if(handleReviewRequest(req, resp, path) || handleLibraryRequest(req, resp, path, user)) {
return;
}
if (prefix.equals(IDavinciServerConstants.APP_URL.substring(1))
// || prefix.equals(IDavinciServerConstants.USER_URL.substring(1))
|| prefix.equals(Constants.CMD_URL.substring(1))) {
// Forward to DavinciPageServlet such as "/app/img/1.jpg"
req.getRequestDispatcher(pathInfo).forward(req, resp);
return;
}
// Check if it is a valid user name.
// If it is a valid user name, do login
// Else, error.
User designer = userManager.getUser(prefix);
if (designer == null) {
resp.sendRedirect(this.getLoginUrl(req));
return;
} else {
ReviewObject reviewObject = new ReviewObject(prefix);
if (path.segmentCount() > 2) {
// Token = 20100101/project1/folder1/sample1.html/default
String commentId = path.segment(path.segmentCount() - 1);
String fileName = path.removeLastSegments(1).removeFirstSegments(1)
.toPortableString();
reviewObject.setFile(fileName);
reviewObject.setCommentId(commentId);
<MASK>reviewObject.setDesignerEmail(designer.getPerson().getEmail());</MASK>
}
req.getSession().setAttribute(Constants.REVIEW_INFO, reviewObject);
resp.sendRedirect(contextString + "/review");
return;
}
}
}"
|
Inversion-Mutation
|
megadiff
|
"@TestTargetNew(
level = TestLevel.COMPLETE,
method = "setDither",
args = {boolean.class}
)
public void testSetDither() {
assertConstantStateNotSet();
assertNull(mDrawableContainer.getCurrent());
mDrawableContainer.setConstantState(mDrawableContainerState);
mDrawableContainer.setDither(false);
mDrawableContainer.setDither(true);
MockDrawable dr = new MockDrawable();
addAndSelectDrawable(dr);
// call current drawable's setDither if dither is changed.
dr.reset();
mDrawableContainer.setDither(false);
assertTrue(dr.hasSetDitherCalled());
// does not call it if dither is not changed.
dr.reset();
mDrawableContainer.setDither(true);
assertTrue(dr.hasSetDitherCalled());
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "testSetDither"
|
"@TestTargetNew(
level = TestLevel.COMPLETE,
method = "setDither",
args = {boolean.class}
)
public void testSetDither() {
assertConstantStateNotSet();
assertNull(mDrawableContainer.getCurrent());
mDrawableContainer.setDither(false);
mDrawableContainer.setDither(true);
<MASK>mDrawableContainer.setConstantState(mDrawableContainerState);</MASK>
MockDrawable dr = new MockDrawable();
addAndSelectDrawable(dr);
// call current drawable's setDither if dither is changed.
dr.reset();
mDrawableContainer.setDither(false);
assertTrue(dr.hasSetDitherCalled());
// does not call it if dither is not changed.
dr.reset();
mDrawableContainer.setDither(true);
assertTrue(dr.hasSetDitherCalled());
}"
|
Inversion-Mutation
|
megadiff
|
"public void submitJob(final Job job, boolean stageFiles,
DtoActionStatus status) throws JobSubmissionException {
final String debug_token = "SUBMIT_" + job.getJobname() + ": ";
try {
int noStageins = 0;
if (stageFiles) {
final List<Element> stageIns = JsdlHelpers
.getStageInElements(job.getJobDescription());
noStageins = stageIns.size();
}
status.setTotalElements(status.getTotalElements() + 4 + noStageins);
// myLogger.debug("Preparing job environment...");
job.addLogMessage("Preparing job environment.");
status.addElement("Preparing job environment...");
addLogMessageToPossibleMultiPartJobParent(job,
"Starting job submission for job: " + job.getJobname());
myLogger.debug(debug_token + "preparing job environment...");
prepareJobEnvironment(job);
myLogger.debug(debug_token + "preparing job environment finished.");
if (stageFiles) {
myLogger.debug(debug_token + "staging in files started...");
status.addLogMessage("Starting file stage-in.");
job.addLogMessage("Staging possible input files.");
// myLogger.debug("Staging possible input files...");
stageFiles(job, status);
job.addLogMessage("File staging finished.");
status.addLogMessage("File stage-in finished.");
myLogger.debug(debug_token + "staging in files finished.");
}
status.addElement("Job environment prepared...");
} catch (final Throwable e) {
myLogger.debug(debug_token + "error: " + e.getLocalizedMessage());
status.setFailed(true);
status.setErrorCause(e.getLocalizedMessage());
status.setFinished(true);
throw new JobSubmissionException(
"Could not access remote filesystem: "
+ e.getLocalizedMessage());
}
status.addElement("Setting credential...");
myLogger.debug(debug_token + "setting credential started...");
if (job.getFqan() != null) {
try {
job.setCredential(getUser().getCredential(job.getFqan()));
} catch (final Throwable e) {
status.setFailed(true);
status.setErrorCause(e.getLocalizedMessage());
status.setFinished(true);
myLogger.error(e.getLocalizedMessage(), e);
throw new JobSubmissionException(
"Could not create credential to use to submit the job: "
+ e.getLocalizedMessage());
}
} else {
job.addLogMessage("Setting non-vo credential: " + job.getFqan());
job.setCredential(getUser().getCredential());
}
myLogger.debug(debug_token + "setting credential finished.");
myLogger.debug(debug_token
+ "adding job properties as env variables to jsdl..");
Document oldJsdl = job.getJobDescription();
for (String key : job.getJobProperties().keySet()) {
String value = job.getJobProperty(key);
key = "GRISU_" + key.toUpperCase();
if (StringUtils.isNotBlank(value)) {
Element e = JsdlHelpers
.addOrRetrieveExistingApplicationEnvironmentElement(
oldJsdl, key);
e.setTextContent(value);
}
}
job.setJobDescription(oldJsdl);
String handle = null;
myLogger.debug(debug_token + "submitting job to endpoint...");
try {
status.addElement("Starting job submission using GT4...");
job.addLogMessage("Submitting job to endpoint...");
final String candidate = JsdlHelpers.getCandidateHosts(job
.getJobDescription())[0];
final GridResource resource = getUser().getInformationManager()
.getGridResource(candidate);
String version = resource.getGRAMVersion();
if (version == null) {
// TODO is that good enough?
version = "4.0.0";
}
String submissionType = null;
if (version.startsWith("5")) {
submissionType = "GT5";
} else {
submissionType = "GT4";
}
try {
myLogger.debug(debug_token + "submitting...");
handle = getUser().getJobManager().submit(
submissionType, job);
myLogger.debug(debug_token + "submittission finished...");
} catch (final ServerJobSubmissionException e) {
myLogger.debug(debug_token + "submittission failed: "
+ e.getLocalizedMessage());
status.addLogMessage("Job submission failed on server.");
status.setFailed(true);
status.setFinished(true);
status.setErrorCause(e.getLocalizedMessage());
job.addLogMessage("Submission to endpoint failed: "
+ e.getLocalizedMessage());
addLogMessageToPossibleMultiPartJobParent(
job,
"Job submission for job: " + job.getJobname()
+ " failed: " + e.getLocalizedMessage());
throw new JobSubmissionException(
"Submission to endpoint failed: "
+ e.getLocalizedMessage());
}
job.addLogMessage("Submission finished.");
} catch (final Throwable e) {
myLogger.debug(debug_token + "something failed: "
+ e.getLocalizedMessage());
// e.printStackTrace();
status.addLogMessage("Job submission failed.");
status.setFailed(true);
status.setFinished(true);
job.addLogMessage("Submission to endpoint failed: "
+ e.getLocalizedMessage());
addLogMessageToPossibleMultiPartJobParent(
job,
"Job submission for job: " + job.getJobname() + " failed: "
+ e.getLocalizedMessage());
myLogger.error(e.getLocalizedMessage(), e);
throw new JobSubmissionException(
"Job submission to endpoint failed: "
+ e.getLocalizedMessage(), e);
}
if (handle == null) {
myLogger.debug(debug_token
+ "submission finished but no jobhandle.");
status.addLogMessage("Submission finished but no jobhandle...");
status.setFailed(true);
status.setErrorCause("No jobhandle");
status.setFinished(true);
job.addLogMessage("Submission finished but jobhandle is null...");
addLogMessageToPossibleMultiPartJobParent(
job,
"Job submission for job: " + job.getJobname()
+ " finished but jobhandle is null...");
throw new JobSubmissionException(
"Job apparently submitted but jobhandle is null for job: "
+ job.getJobname());
}
try {
myLogger.debug(debug_token + "wrapping up started");
job.addJobProperty(Constants.SUBMISSION_TIME_KEY,
Long.toString(new Date().getTime()));
// we don't want the credential to be stored with the job in this
// case
// TODO or do we want it to be stored?
job.setCredential(null);
job.addLogMessage("Job submission finished successful.");
addLogMessageToPossibleMultiPartJobParent(
job,
"Job submission for job: " + job.getJobname()
+ " finished successful.");
jobdao.saveOrUpdate(job);
myLogger.debug(debug_token + "wrapping up finished");
myLogger.info("Jobsubmission for job " + job.getJobname()
+ " and user " + getUser().getDn() + " successful.");
status.addElement("Job submission finished...");
status.setFinished(true);
} catch (final Throwable e) {
myLogger.debug(debug_token + "wrapping up failed: "
+ e.getLocalizedMessage());
status.addLogMessage("Submission finished, error in wrap-up...");
status.setFailed(true);
status.setFinished(true);
status.setErrorCause(e.getLocalizedMessage());
job.addLogMessage("Submission finished, error in wrap-up...");
addLogMessageToPossibleMultiPartJobParent(
job,
"Job submission for job: " + job.getJobname()
+ " finished but error in wrap-up...");
throw new JobSubmissionException(
"Job apparently submitted but error in wrap-up for job: "
+ job.getJobname());
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "submitJob"
|
"public void submitJob(final Job job, boolean stageFiles,
DtoActionStatus status) throws JobSubmissionException {
final String debug_token = "SUBMIT_" + job.getJobname() + ": ";
try {
int noStageins = 0;
if (stageFiles) {
final List<Element> stageIns = JsdlHelpers
.getStageInElements(job.getJobDescription());
noStageins = stageIns.size();
}
status.setTotalElements(status.getTotalElements() + 4 + noStageins);
// myLogger.debug("Preparing job environment...");
job.addLogMessage("Preparing job environment.");
status.addElement("Preparing job environment...");
addLogMessageToPossibleMultiPartJobParent(job,
"Starting job submission for job: " + job.getJobname());
myLogger.debug(debug_token + "preparing job environment...");
prepareJobEnvironment(job);
myLogger.debug(debug_token + "preparing job environment finished.");
if (stageFiles) {
myLogger.debug(debug_token + "staging in files started...");
status.addLogMessage("Starting file stage-in.");
job.addLogMessage("Staging possible input files.");
// myLogger.debug("Staging possible input files...");
stageFiles(job, status);
job.addLogMessage("File staging finished.");
status.addLogMessage("File stage-in finished.");
myLogger.debug(debug_token + "staging in files finished.");
}
status.addElement("Job environment prepared...");
} catch (final Throwable e) {
myLogger.debug(debug_token + "error: " + e.getLocalizedMessage());
status.setFailed(true);
status.setErrorCause(e.getLocalizedMessage());
status.setFinished(true);
throw new JobSubmissionException(
"Could not access remote filesystem: "
+ e.getLocalizedMessage());
}
status.addElement("Setting credential...");
myLogger.debug(debug_token + "setting credential started...");
if (job.getFqan() != null) {
try {
job.setCredential(getUser().getCredential(job.getFqan()));
} catch (final Throwable e) {
status.setFailed(true);
status.setErrorCause(e.getLocalizedMessage());
status.setFinished(true);
myLogger.error(e.getLocalizedMessage(), e);
throw new JobSubmissionException(
"Could not create credential to use to submit the job: "
+ e.getLocalizedMessage());
}
} else {
job.addLogMessage("Setting non-vo credential: " + job.getFqan());
job.setCredential(getUser().getCredential());
}
myLogger.debug(debug_token + "setting credential finished.");
myLogger.debug(debug_token
+ "adding job properties as env variables to jsdl..");
Document oldJsdl = job.getJobDescription();
for (String key : job.getJobProperties().keySet()) {
<MASK>key = "GRISU_" + key.toUpperCase();</MASK>
String value = job.getJobProperty(key);
if (StringUtils.isNotBlank(value)) {
Element e = JsdlHelpers
.addOrRetrieveExistingApplicationEnvironmentElement(
oldJsdl, key);
e.setTextContent(value);
}
}
job.setJobDescription(oldJsdl);
String handle = null;
myLogger.debug(debug_token + "submitting job to endpoint...");
try {
status.addElement("Starting job submission using GT4...");
job.addLogMessage("Submitting job to endpoint...");
final String candidate = JsdlHelpers.getCandidateHosts(job
.getJobDescription())[0];
final GridResource resource = getUser().getInformationManager()
.getGridResource(candidate);
String version = resource.getGRAMVersion();
if (version == null) {
// TODO is that good enough?
version = "4.0.0";
}
String submissionType = null;
if (version.startsWith("5")) {
submissionType = "GT5";
} else {
submissionType = "GT4";
}
try {
myLogger.debug(debug_token + "submitting...");
handle = getUser().getJobManager().submit(
submissionType, job);
myLogger.debug(debug_token + "submittission finished...");
} catch (final ServerJobSubmissionException e) {
myLogger.debug(debug_token + "submittission failed: "
+ e.getLocalizedMessage());
status.addLogMessage("Job submission failed on server.");
status.setFailed(true);
status.setFinished(true);
status.setErrorCause(e.getLocalizedMessage());
job.addLogMessage("Submission to endpoint failed: "
+ e.getLocalizedMessage());
addLogMessageToPossibleMultiPartJobParent(
job,
"Job submission for job: " + job.getJobname()
+ " failed: " + e.getLocalizedMessage());
throw new JobSubmissionException(
"Submission to endpoint failed: "
+ e.getLocalizedMessage());
}
job.addLogMessage("Submission finished.");
} catch (final Throwable e) {
myLogger.debug(debug_token + "something failed: "
+ e.getLocalizedMessage());
// e.printStackTrace();
status.addLogMessage("Job submission failed.");
status.setFailed(true);
status.setFinished(true);
job.addLogMessage("Submission to endpoint failed: "
+ e.getLocalizedMessage());
addLogMessageToPossibleMultiPartJobParent(
job,
"Job submission for job: " + job.getJobname() + " failed: "
+ e.getLocalizedMessage());
myLogger.error(e.getLocalizedMessage(), e);
throw new JobSubmissionException(
"Job submission to endpoint failed: "
+ e.getLocalizedMessage(), e);
}
if (handle == null) {
myLogger.debug(debug_token
+ "submission finished but no jobhandle.");
status.addLogMessage("Submission finished but no jobhandle...");
status.setFailed(true);
status.setErrorCause("No jobhandle");
status.setFinished(true);
job.addLogMessage("Submission finished but jobhandle is null...");
addLogMessageToPossibleMultiPartJobParent(
job,
"Job submission for job: " + job.getJobname()
+ " finished but jobhandle is null...");
throw new JobSubmissionException(
"Job apparently submitted but jobhandle is null for job: "
+ job.getJobname());
}
try {
myLogger.debug(debug_token + "wrapping up started");
job.addJobProperty(Constants.SUBMISSION_TIME_KEY,
Long.toString(new Date().getTime()));
// we don't want the credential to be stored with the job in this
// case
// TODO or do we want it to be stored?
job.setCredential(null);
job.addLogMessage("Job submission finished successful.");
addLogMessageToPossibleMultiPartJobParent(
job,
"Job submission for job: " + job.getJobname()
+ " finished successful.");
jobdao.saveOrUpdate(job);
myLogger.debug(debug_token + "wrapping up finished");
myLogger.info("Jobsubmission for job " + job.getJobname()
+ " and user " + getUser().getDn() + " successful.");
status.addElement("Job submission finished...");
status.setFinished(true);
} catch (final Throwable e) {
myLogger.debug(debug_token + "wrapping up failed: "
+ e.getLocalizedMessage());
status.addLogMessage("Submission finished, error in wrap-up...");
status.setFailed(true);
status.setFinished(true);
status.setErrorCause(e.getLocalizedMessage());
job.addLogMessage("Submission finished, error in wrap-up...");
addLogMessageToPossibleMultiPartJobParent(
job,
"Job submission for job: " + job.getJobname()
+ " finished but error in wrap-up...");
throw new JobSubmissionException(
"Job apparently submitted but error in wrap-up for job: "
+ job.getJobname());
}
}"
|
Inversion-Mutation
|
megadiff
|
"public static void exec(int[] rom) {
JFrame window = new JFrame();
MakoPanel view = new MakoPanel(rom);
window.addKeyListener(view);
window.add(view);
window.setTitle("Mako");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false);
window.pack();
window.setVisible(true);
while(true) {
view.vm.run();
view.vm.keys = view.keys;
view.repaint();
try { Thread.sleep(10); }
catch(InterruptedException ie) {}
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "exec"
|
"public static void exec(int[] rom) {
JFrame window = new JFrame();
MakoPanel view = new MakoPanel(rom);
window.addKeyListener(view);
window.add(view);
window.setTitle("Mako");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
<MASK>window.pack();</MASK>
window.setResizable(false);
window.setVisible(true);
while(true) {
view.vm.run();
view.vm.keys = view.keys;
view.repaint();
try { Thread.sleep(10); }
catch(InterruptedException ie) {}
}
}"
|
Inversion-Mutation
|
megadiff
|
"protected byte[] makeHeaderBytes(int pl) {
ByteBuffer header = ByteBuffer.allocate(HEADER_SIZE);
header.put(type);
header.putInt(pl);
header.putLong(time);
header.putLong(seq);
return header.array();
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "makeHeaderBytes"
|
"protected byte[] makeHeaderBytes(int pl) {
ByteBuffer header = ByteBuffer.allocate(HEADER_SIZE);
header.put(type);
header.putInt(pl);
<MASK>header.putLong(seq);</MASK>
header.putLong(time);
return header.array();
}"
|
Inversion-Mutation
|
megadiff
|
"@Override
public void createPartControl(final Composite parent) {
IContextService service = (IContextService) getSite().getService(IContextService.class);
service.activateContext(CONTEXT_ID);
parent.setLayout(adjustLayout(new GridLayout(1, false)));
Composite row1 = new Composite(parent, SWT.NONE);
row1.setLayoutData(createHorizontalFillGridData());
row1.setLayout(adjustLayout(new GridLayout(2, true)));
Composite progress = new Composite(row1, SWT.NONE);
progress.setLayoutData(createHorizontalFillGridData());
progress.setLayout(adjustLayout(new GridLayout(2, false)));
Composite progressBarBorder = new Composite(progress, SWT.NONE);
progressBarBorder.setLayoutData(createHorizontalFillGridData());
GridLayout progressBarBorderLayout = new GridLayout();
progressBarBorderLayout.marginWidth = 2;
progressBarBorderLayout.marginHeight = 2;
progressBarBorderLayout.horizontalSpacing = 2;
progressBarBorderLayout.verticalSpacing = 2;
progressBarBorder.setLayout(progressBarBorderLayout);
progressBar = new RunProgressBar(progressBarBorder);
progressBar.setLayoutData(createHorizontalFillGridData());
progressBar.setLayout(adjustLayout(new GridLayout()));
progressBar.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_WHITE));
Composite clock = new Composite(row1, SWT.NONE);
clock.setLayoutData(createHorizontalFillGridData());
clock.setLayout(new FillLayout(SWT.HORIZONTAL));
processTimeAverage = new Label(clock, SWT.LEFT);
processTime = new Label(clock, SWT.LEFT);
elapsedTime = new Label(clock, SWT.LEFT);
Composite row2 = new Composite(parent, SWT.NONE);
row2.setLayoutData(createHorizontalFillGridData());
row2.setLayout(adjustLayout(new GridLayout(2, true)));
Composite counter = new Composite(row2, SWT.NONE);
counter.setLayoutData(createHorizontalFillGridData());
counter.setLayout(new FillLayout(SWT.HORIZONTAL));
testCount = new CLabel(counter, SWT.LEFT);
passCount = new ResultLabel(
counter,
Messages.TestResultView_passesLabel,
Activator.getImageDescriptor("icons/pass-gray.gif").createImage() //$NON-NLS-1$
);
failureCount = new ResultLabel(
counter,
Messages.TestResultView_failuresLabel,
Activator.getImageDescriptor("icons/failure-gray.gif").createImage() //$NON-NLS-1$
);
errorCount = new ResultLabel(
counter,
Messages.TestResultView_errorsLabel,
Activator.getImageDescriptor("icons/error-gray.gif").createImage() //$NON-NLS-1$
);
SashForm row3 = new SashForm(parent, SWT.NONE);
row3.setLayoutData(createBothFillGridData());
row3.setLayout(adjustLayout(new GridLayout(2, true)));
Tree resultTree = new Tree(row3, SWT.BORDER);
resultTree.setLayoutData(createBothFillGridData());
resultTreeViewer = new TreeViewer(resultTree);
resultTreeViewer.setContentProvider(new ResultTreeContentProvider());
resultTreeViewer.setLabelProvider(new ResultTreeLabelProvider());
resultTreeViewer.addSelectionChangedListener(new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
failureTrace.clearText();
if (!(event.getSelection() instanceof IStructuredSelection)) return;
IStructuredSelection selection = (IStructuredSelection) event.getSelection();
Object element = selection.getFirstElement();
if (!(element instanceof TestCaseResult)) return;
TestCaseResult testCase = (TestCaseResult) element;
if (!testCase.fixed()) return;
if (!testCase.hasFailures() && !testCase.hasErrors()) return;
failureTrace.setText(testCase.getFailureTrace());
}
});
resultTreeViewer.addDoubleClickListener(new IDoubleClickListener() {
@Override
public void doubleClick(DoubleClickEvent event) {
IStructuredSelection selection = (IStructuredSelection) event.getSelection();
Object element = selection.getFirstElement();
if (element instanceof TestCaseResult) {
TestCaseResult testCase = (TestCaseResult) element;
String fileName = testCase.getFile();
if (fileName == null) return;
IFile file =
ResourcesPlugin.getWorkspace()
.getRoot()
.getFileForLocation(new Path(fileName));
if (file != null) {
EditorOpen.open(file, testCase.getLine());
} else {
EditorOpen.open(
EFS.getLocalFileSystem().getStore(new Path(fileName)),
testCase.getLine()
);
}
} else if (element instanceof TestSuiteResult) {
TestSuiteResult suite= (TestSuiteResult) element;
String fileName = suite.getFile();
if (fileName == null) return;
IFile file =
ResourcesPlugin.getWorkspace()
.getRoot()
.getFileForLocation(new Path(fileName));
if (file != null) {
EditorOpen.open(file);
} else {
EditorOpen.open(
EFS.getLocalFileSystem().getStore(new Path(fileName))
);
}
}
}
});
Composite row3Right = new Composite(row3, SWT.NONE);
row3Right.setLayoutData(createHorizontalFillGridData());
row3Right.setLayout(adjustLayout(new GridLayout(1, true)));
new ResultLabel(
row3Right,
Messages.TestResultView_failureTraceLabel,
Activator.getImageDescriptor("icons/failure-trace.gif").createImage() //$NON-NLS-1$
);
failureTrace = createFailureTrace(row3Right);
IViewSite site = getViewSite();
site.getPage().addPartListener(partListenr);
initializeActions(site);
reset();
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createPartControl"
|
"@Override
public void createPartControl(final Composite parent) {
IContextService service = (IContextService) getSite().getService(IContextService.class);
service.activateContext(CONTEXT_ID);
parent.setLayout(adjustLayout(new GridLayout(1, false)));
Composite row1 = new Composite(parent, SWT.NONE);
row1.setLayoutData(createHorizontalFillGridData());
row1.setLayout(adjustLayout(new GridLayout(2, true)));
Composite progress = new Composite(row1, SWT.NONE);
progress.setLayoutData(createHorizontalFillGridData());
progress.setLayout(adjustLayout(new GridLayout(2, false)));
Composite progressBarBorder = new Composite(progress, SWT.NONE);
progressBarBorder.setLayoutData(createHorizontalFillGridData());
GridLayout progressBarBorderLayout = new GridLayout();
progressBarBorderLayout.marginWidth = 2;
progressBarBorderLayout.marginHeight = 2;
progressBarBorderLayout.horizontalSpacing = 2;
progressBarBorderLayout.verticalSpacing = 2;
progressBarBorder.setLayout(progressBarBorderLayout);
progressBar = new RunProgressBar(progressBarBorder);
progressBar.setLayoutData(createHorizontalFillGridData());
progressBar.setLayout(adjustLayout(new GridLayout()));
progressBar.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_WHITE));
Composite clock = new Composite(row1, SWT.NONE);
clock.setLayoutData(createHorizontalFillGridData());
clock.setLayout(new FillLayout(SWT.HORIZONTAL));
processTimeAverage = new Label(clock, SWT.LEFT);
<MASK>elapsedTime = new Label(clock, SWT.LEFT);</MASK>
processTime = new Label(clock, SWT.LEFT);
Composite row2 = new Composite(parent, SWT.NONE);
row2.setLayoutData(createHorizontalFillGridData());
row2.setLayout(adjustLayout(new GridLayout(2, true)));
Composite counter = new Composite(row2, SWT.NONE);
counter.setLayoutData(createHorizontalFillGridData());
counter.setLayout(new FillLayout(SWT.HORIZONTAL));
testCount = new CLabel(counter, SWT.LEFT);
passCount = new ResultLabel(
counter,
Messages.TestResultView_passesLabel,
Activator.getImageDescriptor("icons/pass-gray.gif").createImage() //$NON-NLS-1$
);
failureCount = new ResultLabel(
counter,
Messages.TestResultView_failuresLabel,
Activator.getImageDescriptor("icons/failure-gray.gif").createImage() //$NON-NLS-1$
);
errorCount = new ResultLabel(
counter,
Messages.TestResultView_errorsLabel,
Activator.getImageDescriptor("icons/error-gray.gif").createImage() //$NON-NLS-1$
);
SashForm row3 = new SashForm(parent, SWT.NONE);
row3.setLayoutData(createBothFillGridData());
row3.setLayout(adjustLayout(new GridLayout(2, true)));
Tree resultTree = new Tree(row3, SWT.BORDER);
resultTree.setLayoutData(createBothFillGridData());
resultTreeViewer = new TreeViewer(resultTree);
resultTreeViewer.setContentProvider(new ResultTreeContentProvider());
resultTreeViewer.setLabelProvider(new ResultTreeLabelProvider());
resultTreeViewer.addSelectionChangedListener(new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
failureTrace.clearText();
if (!(event.getSelection() instanceof IStructuredSelection)) return;
IStructuredSelection selection = (IStructuredSelection) event.getSelection();
Object element = selection.getFirstElement();
if (!(element instanceof TestCaseResult)) return;
TestCaseResult testCase = (TestCaseResult) element;
if (!testCase.fixed()) return;
if (!testCase.hasFailures() && !testCase.hasErrors()) return;
failureTrace.setText(testCase.getFailureTrace());
}
});
resultTreeViewer.addDoubleClickListener(new IDoubleClickListener() {
@Override
public void doubleClick(DoubleClickEvent event) {
IStructuredSelection selection = (IStructuredSelection) event.getSelection();
Object element = selection.getFirstElement();
if (element instanceof TestCaseResult) {
TestCaseResult testCase = (TestCaseResult) element;
String fileName = testCase.getFile();
if (fileName == null) return;
IFile file =
ResourcesPlugin.getWorkspace()
.getRoot()
.getFileForLocation(new Path(fileName));
if (file != null) {
EditorOpen.open(file, testCase.getLine());
} else {
EditorOpen.open(
EFS.getLocalFileSystem().getStore(new Path(fileName)),
testCase.getLine()
);
}
} else if (element instanceof TestSuiteResult) {
TestSuiteResult suite= (TestSuiteResult) element;
String fileName = suite.getFile();
if (fileName == null) return;
IFile file =
ResourcesPlugin.getWorkspace()
.getRoot()
.getFileForLocation(new Path(fileName));
if (file != null) {
EditorOpen.open(file);
} else {
EditorOpen.open(
EFS.getLocalFileSystem().getStore(new Path(fileName))
);
}
}
}
});
Composite row3Right = new Composite(row3, SWT.NONE);
row3Right.setLayoutData(createHorizontalFillGridData());
row3Right.setLayout(adjustLayout(new GridLayout(1, true)));
new ResultLabel(
row3Right,
Messages.TestResultView_failureTraceLabel,
Activator.getImageDescriptor("icons/failure-trace.gif").createImage() //$NON-NLS-1$
);
failureTrace = createFailureTrace(row3Right);
IViewSite site = getViewSite();
site.getPage().addPartListener(partListenr);
initializeActions(site);
reset();
}"
|
Inversion-Mutation
|
megadiff
|
"public void run() {
Provisioner provisioner = Accessor.getService(Provisioner.class);
while (true) {
if (!servicesToProvision.isEmpty()) {
LinkedHashSet<SignatureElement> copy ;
synchronized (servicesToProvision){
copy = new LinkedHashSet<SignatureElement>(servicesToProvision);
}
Iterator<SignatureElement> it = copy.iterator();
Set<SignatureElement> sigsToRemove = new LinkedHashSet<SignatureElement>();
logger.fine("Services to provision from Spacer/Jobber: "+ servicesToProvision.size());
while (it.hasNext()) {
SignatureElement sigEl = it.next();
// Catalog lookup or use Lookup Service for the particular
// service
Service service = (Service) Accessor.getService(sigEl.getSignature());
if (service == null ) {
sigEl.incrementProvisionAttempts();
if (provisioner != null) {
try {
logger.info("Provisioning: "+ sigEl.getSignature());
service = provisioner.provision(sigEl.getServiceType(), sigEl.getProviderName(), sigEl.getVersion());
if (service!=null) sigsToRemove.add(sigEl);
} catch (ProvisioningException pe) {
logger.severe("Problem provisioning: " +pe.getMessage());
} catch (RemoteException re) {
provisioner = Accessor.getService(Provisioner.class);
String msg = "Problem provisioning "+sigEl.getSignature().getServiceType()
+ " (" + sigEl.getSignature().getProviderName() + ")"
+ " " +re.getMessage();
logger.severe(msg);
}
} else
provisioner = Accessor.getService(Provisioner.class);
if (service == null && sigEl.getProvisionAttempts() > MAX_ATTEMPTS) {
String logMsg = "Provisioning for " + sigEl.getServiceType() + "(" + sigEl.getProviderName()
+ ") tried: " + sigEl.getProvisionAttempts() +" times, provisioning will not be reattempted";
logger.severe(logMsg);
try {
failExertionInSpace(sigEl, new ProvisioningException(logMsg));
sigsToRemove.add(sigEl);
} catch (ExertionException ile) {
logger.severe("Problem trying to remove exception after reattempting to provision");
}
}
} else
sigsToRemove.add(sigEl);
}
if (!sigsToRemove.isEmpty()) {
synchronized (servicesToProvision) {
servicesToProvision.removeAll(sigsToRemove);
}
}
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
|
"public void run() {
Provisioner provisioner = Accessor.getService(Provisioner.class);
while (true) {
if (!servicesToProvision.isEmpty()) {
LinkedHashSet<SignatureElement> copy ;
synchronized (servicesToProvision){
copy = new LinkedHashSet<SignatureElement>(servicesToProvision);
}
Iterator<SignatureElement> it = copy.iterator();
Set<SignatureElement> sigsToRemove = new LinkedHashSet<SignatureElement>();
logger.fine("Services to provision from Spacer/Jobber: "+ servicesToProvision.size());
while (it.hasNext()) {
SignatureElement sigEl = it.next();
// Catalog lookup or use Lookup Service for the particular
// service
Service service = (Service) Accessor.getService(sigEl.getSignature());
if (service == null ) {
if (provisioner != null) {
try {
logger.info("Provisioning: "+ sigEl.getSignature());
<MASK>sigEl.incrementProvisionAttempts();</MASK>
service = provisioner.provision(sigEl.getServiceType(), sigEl.getProviderName(), sigEl.getVersion());
if (service!=null) sigsToRemove.add(sigEl);
} catch (ProvisioningException pe) {
logger.severe("Problem provisioning: " +pe.getMessage());
} catch (RemoteException re) {
provisioner = Accessor.getService(Provisioner.class);
String msg = "Problem provisioning "+sigEl.getSignature().getServiceType()
+ " (" + sigEl.getSignature().getProviderName() + ")"
+ " " +re.getMessage();
logger.severe(msg);
}
} else
provisioner = Accessor.getService(Provisioner.class);
if (service == null && sigEl.getProvisionAttempts() > MAX_ATTEMPTS) {
String logMsg = "Provisioning for " + sigEl.getServiceType() + "(" + sigEl.getProviderName()
+ ") tried: " + sigEl.getProvisionAttempts() +" times, provisioning will not be reattempted";
logger.severe(logMsg);
try {
failExertionInSpace(sigEl, new ProvisioningException(logMsg));
sigsToRemove.add(sigEl);
} catch (ExertionException ile) {
logger.severe("Problem trying to remove exception after reattempting to provision");
}
}
} else
sigsToRemove.add(sigEl);
}
if (!sigsToRemove.isEmpty()) {
synchronized (servicesToProvision) {
servicesToProvision.removeAll(sigsToRemove);
}
}
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
}"
|
Inversion-Mutation
|
megadiff
|
"@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.EditAugment:
if (mLongClickingItemId == -1)
AugmentEditActivity.startActivity(this, 0, getFFXICharacter(), mPart, mCurrent, -1);
else
AugmentEditActivity.startActivity(this, 0, getFFXICharacter(), mPart, -1, mLongClickingItemId);
return true;
case R.id.DeleteAugment:
showDialog(R.string.QueryDeleteAugment);
return true;
}
Equipment eq = getDAO().instantiateEquipment(-1, mLongClickingItemId);
Intent intent;
if (eq != null) {
String name = eq.getName();
String[] urls = getResources().getStringArray(R.array.SearchURIs);
String url;
url = null;
switch (item.getItemId()) {
case R.id.WebSearch0:
url = urls[0];
break;
case R.id.WebSearch1:
url = urls[1];
break;
case R.id.WebSearch2:
url = urls[2];
break;
case R.id.WebSearch3:
url = urls[3];
break;
case R.id.WebSearch4:
url = urls[4];
break;
case R.id.WebSearch5:
url = urls[5];
break;
case R.id.WebSearch6:
url = urls[6];
break;
case R.id.WebSearch7:
url = urls[7];
break;
default:
url = null;
break;
}
if (url != null) {
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url + Uri.encode(name.split("\\+")[0])));
startActivity(intent);
return true;
}
}
return super.onContextItemSelected(item);
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onContextItemSelected"
|
"@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.EditAugment:
if (mLongClickingItemId == -1)
AugmentEditActivity.startActivity(this, 0, getFFXICharacter(), mPart, mCurrent, -1);
else
AugmentEditActivity.startActivity(this, 0, getFFXICharacter(), mPart, -1, mLongClickingItemId);
return true;
case R.id.DeleteAugment:
showDialog(R.string.QueryDeleteAugment);
return true;
}
Equipment eq = getDAO().instantiateEquipment(-1, mLongClickingItemId);
<MASK>String name = eq.getName();</MASK>
Intent intent;
if (eq != null) {
String[] urls = getResources().getStringArray(R.array.SearchURIs);
String url;
url = null;
switch (item.getItemId()) {
case R.id.WebSearch0:
url = urls[0];
break;
case R.id.WebSearch1:
url = urls[1];
break;
case R.id.WebSearch2:
url = urls[2];
break;
case R.id.WebSearch3:
url = urls[3];
break;
case R.id.WebSearch4:
url = urls[4];
break;
case R.id.WebSearch5:
url = urls[5];
break;
case R.id.WebSearch6:
url = urls[6];
break;
case R.id.WebSearch7:
url = urls[7];
break;
default:
url = null;
break;
}
if (url != null) {
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url + Uri.encode(name.split("\\+")[0])));
startActivity(intent);
return true;
}
}
return super.onContextItemSelected(item);
}"
|
Inversion-Mutation
|
megadiff
|
"@Test public void shouldPassWhenStep1AndStep2Completed() {
ApplicationContext ctx = createSpringContainer();
AuctionRepository auctionRepository = lookupAuctionRepository(ctx);
AuctionService auctionService = lookupAuctionService(ctx);
assertEquals(0, auctionService.allRunningAuctions().size());
auctionRepository.createNewAuction(new Auction(1, "My first auction"));
auctionRepository.createNewAuction(new Auction(2, "My second auction"));
assertEquals(2, auctionService.allRunningAuctions().size());
Auction auction = auctionService.findById(1D);
assertEquals("My first auction", auction.description());
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "shouldPassWhenStep1AndStep2Completed"
|
"@Test public void shouldPassWhenStep1AndStep2Completed() {
ApplicationContext ctx = createSpringContainer();
AuctionRepository auctionRepository = lookupAuctionRepository(ctx);
<MASK>AuctionService auctionService = lookupAuctionService(ctx);</MASK>
assertEquals(0, auctionService.allRunningAuctions().size());
auctionRepository.createNewAuction(new Auction(1, "My first auction"));
auctionRepository.createNewAuction(new Auction(2, "My second auction"));
assertEquals(2, auctionService.allRunningAuctions().size());
Auction auction = auctionService.findById(1D);
assertEquals("My first auction", auction.description());
}"
|
Inversion-Mutation
|
megadiff
|
"public void init(HighchartConfig config) {
HighchartJsOverlay old = jsOverlay;
if(old != null) {
old.destroy();
}
jsOverlay = config.renderTo(getElement());
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "init"
|
"public void init(HighchartConfig config) {
HighchartJsOverlay old = jsOverlay;
<MASK>jsOverlay = config.renderTo(getElement());</MASK>
if(old != null) {
old.destroy();
}
}"
|
Inversion-Mutation
|
megadiff
|
"public static void main(String[] argv) {
int exitCode = 1;
if (!ws.exists()) {
ws.mkdir();
}
try {
logger = LogFormatter.createDuplex(new File(ws, "xpert.log"), Level.INFO);
} catch (IOException e) {
throw new RuntimeException(e);
}
String pluginName = "default";
String configFileName = "config.properties";
String profileName = null;
String xccdfBaseName = null;
boolean printHelp = false;
for (int i=0; i < argv.length; i++) {
if (argv[i].equals("-h")) {
printHelp = true;
} else if (i == (argv.length - 1)) { // last arg (but not -h)
xccdfBaseName = argv[i];
} else if (argv[i].equals("-config")) {
configFileName = argv[++i];
} else if (argv[i].equals("-profile")) {
profileName = argv[++i];
} else if (argv[i].equals("-plugin")) {
pluginName = argv[++i];
} else if (argv[i].equals("-debug")) {
debug = true;
}
}
IPluginContainer container = null;
try {
container = ContainerFactory.newInstance(new File(BASE_DIR, "plugin")).createContainer(pluginName);
} catch (IllegalArgumentException e) {
logger.severe("Not a directory: " + e.getMessage());
} catch (NoSuchElementException e) {
logger.severe("Plugin not found: " + e.getMessage());
} catch (ContainerConfigurationException e) {
logger.severe(LogFormatter.toString(e));
}
printHeader(container);
if (printHelp) {
printHelp(container);
exitCode = 0;
} else if (xccdfBaseName == null) {
logger.warning("No XCCDF file was specified");
printHelp(container);
} else if (container == null) {
printHelp(null);
} else {
logger.info("Start time: " + new Date().toString());
try {
//
// Configure the jOVAL plugin
//
Properties config = new Properties();
File configFile = new File(configFileName);
if (configFile.isFile()) {
config.load(new FileInputStream(configFile));
}
container.configure(config);
//
// Load the XCCDF and selected profile
//
logger.info("Loading " + xccdfBaseName);
XccdfBundle xccdf = new XccdfBundle(new File(xccdfBaseName));
Profile profile = new Profile(xccdf, profileName);
//
// Perform the evaluation
//
XPERT engine = new XPERT(xccdf, profile, container.getPlugin());
engine.run();
logger.info("Finished processing XCCDF bundle");
exitCode = 0;
} catch (CpeException e) {
logger.severe(LogFormatter.toString(e));
} catch (OvalException e) {
logger.severe(LogFormatter.toString(e));
} catch (XccdfException e) {
logger.severe(LogFormatter.toString(e));
} catch (Exception e) {
logger.severe("Problem configuring the plugin -- check that the configuration is valid");
logger.severe(LogFormatter.toString(e));
}
}
System.exit(exitCode);
}"
|
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "main"
|
"public static void main(String[] argv) {
int exitCode = 1;
if (!ws.exists()) {
ws.mkdir();
}
try {
logger = LogFormatter.createDuplex(new File(ws, "xpert.log"), Level.INFO);
} catch (IOException e) {
throw new RuntimeException(e);
}
String pluginName = "default";
String configFileName = "config.properties";
String profileName = null;
String xccdfBaseName = null;
boolean printHelp = false;
for (int i=0; i < argv.length; i++) {
if (argv[i].equals("-h")) {
printHelp = true;
} else if (i == (argv.length - 1)) { // last arg (but not -h)
xccdfBaseName = argv[i];
} else if (argv[i].equals("-config")) {
configFileName = argv[++i];
} else if (argv[i].equals("-profile")) {
profileName = argv[++i];
} else if (argv[i].equals("-plugin")) {
pluginName = argv[++i];
} else if (argv[i].equals("-debug")) {
debug = true;
}
}
IPluginContainer container = null;
try {
container = ContainerFactory.newInstance(new File(BASE_DIR, "plugin")).createContainer(pluginName);
} catch (IllegalArgumentException e) {
logger.severe("Not a directory: " + e.getMessage());
} catch (NoSuchElementException e) {
logger.severe("Plugin not found: " + e.getMessage());
} catch (ContainerConfigurationException e) {
logger.severe(LogFormatter.toString(e));
}
printHeader(container);
<MASK>logger.info("Start time: " + new Date().toString());</MASK>
if (printHelp) {
printHelp(container);
exitCode = 0;
} else if (xccdfBaseName == null) {
logger.warning("No XCCDF file was specified");
printHelp(container);
} else if (container == null) {
printHelp(null);
} else {
try {
//
// Configure the jOVAL plugin
//
Properties config = new Properties();
File configFile = new File(configFileName);
if (configFile.isFile()) {
config.load(new FileInputStream(configFile));
}
container.configure(config);
//
// Load the XCCDF and selected profile
//
logger.info("Loading " + xccdfBaseName);
XccdfBundle xccdf = new XccdfBundle(new File(xccdfBaseName));
Profile profile = new Profile(xccdf, profileName);
//
// Perform the evaluation
//
XPERT engine = new XPERT(xccdf, profile, container.getPlugin());
engine.run();
logger.info("Finished processing XCCDF bundle");
exitCode = 0;
} catch (CpeException e) {
logger.severe(LogFormatter.toString(e));
} catch (OvalException e) {
logger.severe(LogFormatter.toString(e));
} catch (XccdfException e) {
logger.severe(LogFormatter.toString(e));
} catch (Exception e) {
logger.severe("Problem configuring the plugin -- check that the configuration is valid");
logger.severe(LogFormatter.toString(e));
}
}
System.exit(exitCode);
}"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.