type
stringclasses 1
value | dataset
stringclasses 1
value | input
stringlengths 75
160k
| instruction
stringlengths 117
171
| output
stringlengths 88
168k
|
---|---|---|---|---|
Inversion-Mutation | megadiff | "public V put(K key, V value) {
// TODO
if(key == null) {
throw new NullPointerException("Key == null");
}
if(size == data.length) adjustArrayLength();
int iOf = indexOf(key);
if(iOf == -1) {
data[size++] = new Entry<K,V>(key, value);
return null;
} else {
V valueBefore = data[iOf].getValue();
data[iOf] = new Entry<K,V>(key, value);
return valueBefore;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "put" | "public V put(K key, V value) {
// TODO
<MASK>if(size == data.length) adjustArrayLength();</MASK>
if(key == null) {
throw new NullPointerException("Key == null");
}
int iOf = indexOf(key);
if(iOf == -1) {
data[size++] = new Entry<K,V>(key, value);
return null;
} else {
V valueBefore = data[iOf].getValue();
data[iOf] = new Entry<K,V>(key, value);
return valueBefore;
}
}" |
Inversion-Mutation | megadiff | "public static void showExportImageDialog(JFrame owner, ImageModel model) throws IOException {
JFileChooser chooser = model.getSource() != null ? new JFileChooser(model.getSource().getParentFile()) : new JFileChooser();
chooser.setFileFilter(new FileNameExtensionFilter("PNG Image", EXPORT_EXTENSION));
chooser.setDialogTitle("Export image");
if (chooser.showDialog(owner, "Export") == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
if (!file.getName().endsWith("." + EXPORT_EXTENSION)) {
file = new File(file.getAbsolutePath() + "." + EXPORT_EXTENSION);
}
ImageModelIO.exportImage(file, model);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "showExportImageDialog" | "public static void showExportImageDialog(JFrame owner, ImageModel model) throws IOException {
JFileChooser chooser = model.getSource() != null ? new JFileChooser(model.getSource().getParentFile()) : new JFileChooser();
chooser.setFileFilter(new FileNameExtensionFilter("PNG Image", EXPORT_EXTENSION));
chooser.setDialogTitle("Export image");
if (chooser.showDialog(owner, "Export") == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
if (!file.getName().endsWith("." + EXPORT_EXTENSION)) {
file = new File(file.getAbsolutePath() + "." + EXPORT_EXTENSION);
<MASK>ImageModelIO.exportImage(file, model);</MASK>
}
}
}" |
Inversion-Mutation | megadiff | "private MainFrame() {
super();
setIconImage(Toolkit.getDefaultToolkit().getImage(MainFrame.class.getResource("/org/concord/energy3d/resources/icons/energy3d_2.gif")));
System.out.print("Initiating GUI...");
try {
fileChooser = new JFileChooser();
if (!Config.isWebStart()) {
final File dir = new File(System.getProperties().getProperty("user.dir") + "/Energy3D Projects");
if (!dir.exists()) {
System.out.print("Making save directory..." + dir + "...");
final boolean success = dir.mkdir();
System.out.println(success ? "done" : "failed");
}
fileChooser.setCurrentDirectory(dir);
}
fileChooser.addChoosableFileFilter(new ExtensionFileFilter("Energy3D Project (*.ser)", "ser"));
} catch (Exception e) {
fileChooser = null;
// System.err.println("MainFrame()");
e.printStackTrace();
}
colorChooser = new JColorChooser();
final ReadOnlyColorRGBA defaultColor = HousePart.getDefaultColor();
colorChooser.setColor(new Color(defaultColor.getRed(), defaultColor.getGreen(), defaultColor.getBlue()));
initialize();
System.out.println("done");
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "MainFrame" | "private MainFrame() {
super();
setIconImage(Toolkit.getDefaultToolkit().getImage(MainFrame.class.getResource("/org/concord/energy3d/resources/icons/energy3d_2.gif")));
System.out.print("Initiating GUI...");
try {
if (!Config.isWebStart()) {
<MASK>fileChooser = new JFileChooser();</MASK>
final File dir = new File(System.getProperties().getProperty("user.dir") + "/Energy3D Projects");
if (!dir.exists()) {
System.out.print("Making save directory..." + dir + "...");
final boolean success = dir.mkdir();
System.out.println(success ? "done" : "failed");
}
fileChooser.setCurrentDirectory(dir);
}
fileChooser.addChoosableFileFilter(new ExtensionFileFilter("Energy3D Project (*.ser)", "ser"));
} catch (Exception e) {
fileChooser = null;
// System.err.println("MainFrame()");
e.printStackTrace();
}
colorChooser = new JColorChooser();
final ReadOnlyColorRGBA defaultColor = HousePart.getDefaultColor();
colorChooser.setColor(new Color(defaultColor.getRed(), defaultColor.getGreen(), defaultColor.getBlue()));
initialize();
System.out.println("done");
}" |
Inversion-Mutation | megadiff | "public void run() {
ProcessBuilder pb = new ProcessBuilder(cmdArray);
try {
PMS.info("Starting " + cmdLine);
if (params.outputFile != null && params.outputFile.getParentFile().isDirectory())
pb.directory(params.outputFile.getParentFile());
if (params.workDir != null && params.workDir.isDirectory())
pb.directory(params.workDir);
process = pb.start();
//process = Runtime.getRuntime().exec(cmdArray);
PMS.get().currentProcesses.add(process);
stderrConsumer = new OutputTextConsumer(process.getErrorStream(), true);
stderrConsumer.start();
outConsumer = null;
if (params.outputFile != null) {
PMS.info("Writing in " + params.outputFile.getAbsolutePath());
outConsumer = new OutputTextConsumer(process.getInputStream(), false);
} else if (params.input_pipes[0] != null) {
PMS.info("Reading pipe: " + params.input_pipes[0].getInputPipe());
//Thread.sleep(150);
bo = params.input_pipes[0].getDirectBuffer();
if (bo == null || params.losslessaudio || params.lossyaudio||params.no_videoencode) {
InputStream is = params.input_pipes[0].getInputStream();
outConsumer = new OutputBufferConsumer((params.avidemux)?new AviDemuxerInputStream(is, params, attachedProcesses):is, params);
bo = (BufferedOutputFile) outConsumer.getBuffer();
}
bo.attachThread(this);
new OutputTextConsumer(process.getInputStream(), true).start();
} else if (params.log) {
outConsumer = new OutputTextConsumer(process.getInputStream(), true);
} else {
outConsumer = new OutputBufferConsumer(process.getInputStream(), params);
bo = (BufferedOutputFile) outConsumer.getBuffer();
bo.attachThread(this);
}
if (params.stdin != null) {
params.stdin.push(process.getOutputStream());
}
if (outConsumer != null)
outConsumer.start();
process.waitFor();
try {
if (outConsumer != null)
outConsumer.join(1000);
} catch (InterruptedException e) {}
if (bo != null)
bo.close();
} catch (Exception e) {
PMS.error("Fatal error in process starting: ", e);
stopProcess();
} finally {
if (!destroyed && !params.noexitcheck) {
try {
success = true;
if (process != null && process.exitValue() != 0) {
PMS.minimal("Process " + cmdArray[0] + " has a return code of " + process.exitValue() + "! Maybe an error occured... check the log file");
success = false;
}
} catch (IllegalThreadStateException itse) {
PMS.error("An error occured", itse);
}
}
if (attachedProcesses != null) {
for(ProcessWrapper pw:attachedProcesses) {
if (pw != null)
pw.stopProcess();
}
}
PMS.get().currentProcesses.remove(process);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run" | "public void run() {
ProcessBuilder pb = new ProcessBuilder(cmdArray);
try {
PMS.info("Starting " + cmdLine);
if (params.outputFile != null && params.outputFile.getParentFile().isDirectory())
pb.directory(params.outputFile.getParentFile());
if (params.workDir != null && params.workDir.isDirectory())
pb.directory(params.workDir);
process = pb.start();
//process = Runtime.getRuntime().exec(cmdArray);
PMS.get().currentProcesses.add(process);
stderrConsumer = new OutputTextConsumer(process.getErrorStream(), true);
outConsumer = null;
if (params.outputFile != null) {
PMS.info("Writing in " + params.outputFile.getAbsolutePath());
outConsumer = new OutputTextConsumer(process.getInputStream(), false);
} else if (params.input_pipes[0] != null) {
PMS.info("Reading pipe: " + params.input_pipes[0].getInputPipe());
//Thread.sleep(150);
bo = params.input_pipes[0].getDirectBuffer();
if (bo == null || params.losslessaudio || params.lossyaudio||params.no_videoencode) {
InputStream is = params.input_pipes[0].getInputStream();
outConsumer = new OutputBufferConsumer((params.avidemux)?new AviDemuxerInputStream(is, params, attachedProcesses):is, params);
bo = (BufferedOutputFile) outConsumer.getBuffer();
}
bo.attachThread(this);
new OutputTextConsumer(process.getInputStream(), true).start();
} else if (params.log) {
outConsumer = new OutputTextConsumer(process.getInputStream(), true);
} else {
outConsumer = new OutputBufferConsumer(process.getInputStream(), params);
bo = (BufferedOutputFile) outConsumer.getBuffer();
bo.attachThread(this);
}
if (params.stdin != null) {
params.stdin.push(process.getOutputStream());
}
<MASK>stderrConsumer.start();</MASK>
if (outConsumer != null)
outConsumer.start();
process.waitFor();
try {
if (outConsumer != null)
outConsumer.join(1000);
} catch (InterruptedException e) {}
if (bo != null)
bo.close();
} catch (Exception e) {
PMS.error("Fatal error in process starting: ", e);
stopProcess();
} finally {
if (!destroyed && !params.noexitcheck) {
try {
success = true;
if (process != null && process.exitValue() != 0) {
PMS.minimal("Process " + cmdArray[0] + " has a return code of " + process.exitValue() + "! Maybe an error occured... check the log file");
success = false;
}
} catch (IllegalThreadStateException itse) {
PMS.error("An error occured", itse);
}
}
if (attachedProcesses != null) {
for(ProcessWrapper pw:attachedProcesses) {
if (pw != null)
pw.stopProcess();
}
}
PMS.get().currentProcesses.remove(process);
}
}" |
Inversion-Mutation | megadiff | "@Override
public Message post(final String text) throws MessagePostException {
if (text.isEmpty()) {
throw new MessagePostException("some message content is required");
}
if (!NetboutUtils.participantOf(this.viewer, this).confirmed()) {
throw new IllegalStateException(
String.format(
"You '%s' can't post to bout #%d until you join",
this.viewer,
this.number()
)
);
}
this.validate(text);
final Long duplicate = this.hub.make("pre-post-ignore-duplicate")
.synchronously()
.inBout(this)
.arg(this.number())
.arg(text)
.asDefault(0L)
.exec();
Message message;
if (duplicate == 0L) {
final MessageDt msg = this.data.addMessage();
msg.setDate(new Date());
msg.setAuthor(this.viewer.name());
msg.setText(text);
Logger.debug(
this,
"#post('%s'): message posted",
text
);
message = new HubMessage(
this.hub,
this.viewer,
this,
msg
);
message.text();
this.hub.make("notify-bout-participants")
.arg(this.number())
.arg(message.number())
.asDefault(false)
.exec();
this.hub.infinity().see(message);
} else {
try {
message = this.message(duplicate);
} catch (com.netbout.spi.MessageNotFoundException ex) {
throw new MessagePostException(
String.format(
"duplicate found at msg #%d, but it's absent",
duplicate
),
ex
);
}
}
return message;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "post" | "@Override
public Message post(final String text) throws MessagePostException {
if (text.isEmpty()) {
throw new MessagePostException("some message content is required");
}
if (!NetboutUtils.participantOf(this.viewer, this).confirmed()) {
throw new IllegalStateException(
String.format(
"You '%s' can't post to bout #%d until you join",
this.viewer,
this.number()
)
);
}
this.validate(text);
final Long duplicate = this.hub.make("pre-post-ignore-duplicate")
.synchronously()
.inBout(this)
.arg(this.number())
.arg(text)
.asDefault(0L)
.exec();
Message message;
if (duplicate == 0L) {
final MessageDt msg = this.data.addMessage();
msg.setDate(new Date());
msg.setAuthor(this.viewer.name());
msg.setText(text);
Logger.debug(
this,
"#post('%s'): message posted",
text
);
message = new HubMessage(
this.hub,
this.viewer,
this,
msg
);
message.text();
this.hub.make("notify-bout-participants")
.arg(this.number())
.arg(message.number())
.asDefault(false)
.exec();
} else {
try {
message = this.message(duplicate);
} catch (com.netbout.spi.MessageNotFoundException ex) {
throw new MessagePostException(
String.format(
"duplicate found at msg #%d, but it's absent",
duplicate
),
ex
);
}
}
<MASK>this.hub.infinity().see(message);</MASK>
return message;
}" |
Inversion-Mutation | megadiff | "private void getGroupCompetitionResults(Table table, int row) {
try {
List runs = new ArrayList(getRunBiz().getRunnersByDistance(distance, null));
Map runGroups = new HashMap();
RunGroupMap map = new RunGroupMap();
Iterator iterator = runs.iterator();
while (iterator.hasNext()) {
Run runner = (Run) iterator.next();
if (runner.getRunGroupName() != null && runner.getRunGroupName().trim().length() > 0) {
RunGroup runnerGroup = (RunGroup) runGroups.get(runner.getRunGroupName());
if (runnerGroup == null) {
runnerGroup = new RunGroup(runner.getRunGroupName());
runGroups.put(runner.getRunGroupName(), runnerGroup);
}
map.put(runnerGroup, runner);
}
}
List groupList = new ArrayList(map.keySet());
Collections.sort(groupList, new RunGroupComparator(map));
iterator = groupList.iterator();
while (iterator.hasNext()) {
RunGroup runGroup = (RunGroup) iterator.next();
Collection runnersInRunGroup = map.getCollection(runGroup);
row = insertRunGroupIntoTable(table, row, runGroup.getGroupName() + " - " + runGroup.getCounter().toString());
Iterator runIter = runnersInRunGroup.iterator();
int num = 1;
int count = 0;
while (runIter.hasNext()) {
Run run = (Run) runIter.next();
if (count < 3) {
num = runs.indexOf(run);
row = insertRunIntoTable(table, row, run, num, count+1);
}
count++;
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getGroupCompetitionResults" | "private void getGroupCompetitionResults(Table table, int row) {
try {
List runs = new ArrayList(getRunBiz().getRunnersByDistance(distance, null));
Map runGroups = new HashMap();
RunGroupMap map = new RunGroupMap();
Iterator iterator = runs.iterator();
while (iterator.hasNext()) {
Run runner = (Run) iterator.next();
if (runner.getRunGroupName() != null && runner.getRunGroupName().trim().length() > 0) {
RunGroup runnerGroup = (RunGroup) runGroups.get(runner.getRunGroupName());
if (runnerGroup == null) {
runnerGroup = new RunGroup(runner.getRunGroupName());
runGroups.put(runner.getRunGroupName(), runnerGroup);
}
map.put(runnerGroup, runner);
}
}
List groupList = new ArrayList(map.keySet());
Collections.sort(groupList, new RunGroupComparator(map));
iterator = groupList.iterator();
while (iterator.hasNext()) {
RunGroup runGroup = (RunGroup) iterator.next();
Collection runnersInRunGroup = map.getCollection(runGroup);
row = insertRunGroupIntoTable(table, row, runGroup.getGroupName() + " - " + runGroup.getCounter().toString());
Iterator runIter = runnersInRunGroup.iterator();
int num = 1;
int count = 0;
while (runIter.hasNext()) {
if (count < 3) {
<MASK>Run run = (Run) runIter.next();</MASK>
num = runs.indexOf(run);
row = insertRunIntoTable(table, row, run, num, count+1);
}
count++;
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}" |
Inversion-Mutation | megadiff | "@Override
@EventType(event = EventField.Command)
public void runEvent(CommandEvent event) {
Sender target = event.getChannel();
if (target == null) {
target = event.getSender();
if (target == null) {
return;
}
}
target.sendMessage("Hello. I am " + BotUser.getBotUser().getNick() + " " + RalexBot.VERSION + " using PircBotX " + PircBotX.VERSION);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "runEvent" | "@Override
@EventType(event = EventField.Command)
public void runEvent(CommandEvent event) {
Sender target = event.getChannel();
if (target == null) {
target = event.getSender();
if (target == null) {
return;
}
<MASK>target.sendMessage("Hello. I am " + BotUser.getBotUser().getNick() + " " + RalexBot.VERSION + " using PircBotX " + PircBotX.VERSION);</MASK>
}
}" |
Inversion-Mutation | megadiff | "public HelpCommand(MultiverseCore plugin) {
super(plugin);
this.setName("Get Help with Multiverse");
this.setCommandUsage("/mv " + ChatColor.GOLD + "[PAGE #]");
this.setArgRange(0, 1);
this.addKey("mv help");
this.addKey("mv");
this.addKey("mvhelp");
this.setPermission("multiverse.help", "Displays a nice help menu.", PermissionDefault.TRUE);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "HelpCommand" | "public HelpCommand(MultiverseCore plugin) {
super(plugin);
this.setName("Get Help with Multiverse");
this.setCommandUsage("/mv " + ChatColor.GOLD + "[PAGE #]");
this.setArgRange(0, 1);
this.addKey("mv");
this.addKey("mvhelp");
<MASK>this.addKey("mv help");</MASK>
this.setPermission("multiverse.help", "Displays a nice help menu.", PermissionDefault.TRUE);
}" |
Inversion-Mutation | megadiff | "public SyntaxTreeMouseImpl getSyntaxTreeWithCompress() {
cleanUpInvalidBranch(current);
fixMemoizedBranch(current);
sortBranch(current);
Debug.dump(current);
cleanUpFailedBranch(current);
cleanUpEmptyBranch(current);
compressBranch(current);
SyntaxTreeMouseImpl parent = new SyntaxTreeMouseImpl();
convert(current, parent);
return (SyntaxTreeMouseImpl) parent.children.get(0);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getSyntaxTreeWithCompress" | "public SyntaxTreeMouseImpl getSyntaxTreeWithCompress() {
cleanUpInvalidBranch(current);
fixMemoizedBranch(current);
sortBranch(current);
cleanUpFailedBranch(current);
cleanUpEmptyBranch(current);
compressBranch(current);
<MASK>Debug.dump(current);</MASK>
SyntaxTreeMouseImpl parent = new SyntaxTreeMouseImpl();
convert(current, parent);
return (SyntaxTreeMouseImpl) parent.children.get(0);
}" |
Inversion-Mutation | megadiff | "public void apply(GOut g) {
long st = 0;
if(Config.profile) st = System.nanoTime();
if(trans.length < slotnum) {
synchronized(Slot.class) {
trans = new boolean[slotnum];
repl = new boolean[slotnum];
shaders = Utils.extend(shaders, slotnum);
}
}
bufdiff(cur, next, trans, repl);
Slot<?>[] deplist = GLState.deplist;
boolean dirty = false;
for(int i = trans.length - 1; i >= 0; i--) {
if(repl[i] || trans[i]) {
GLState nst = next.states[i];
ShaderMacro[] ns = (nst == null)?null:nst.shaders();
if(ns != shaders[i]) {
proghash ^= System.identityHashCode(shaders[i]) ^ System.identityHashCode(ns);
shaders[i] = ns;
dirty = true;
}
}
}
usedprog = prog != null;
if(dirty) {
ShaderMacro.Program np;
boolean shreq = false;
for(int i = 0; i < trans.length; i++) {
if((shaders[i] != null) && next.states[i].reqshaders()) {
shreq = true;
break;
}
}
if(shreq && g.gc.pref.shuse.val) {
np = findprog(proghash, shaders);
} else {
np = null;
}
if(np != prog) {
if(np != null)
np.apply(g);
else
g.gl.glUseProgramObjectARB(0);
prog = np;
if(debug)
checkerr(g.gl);
pdirty = true;
}
}
if((prog != null) != usedprog) {
for(int i = 0; i < trans.length; i++) {
if(trans[i])
repl[i] = true;
}
}
cur.copy(old);
for(int i = deplist.length - 1; i >= 0; i--) {
int id = deplist[i].id;
if(repl[id]) {
if(cur.states[id] != null) {
cur.states[id].unapply(g);
if(debug)
stcheckerr(g, "unapply", cur.states[id]);
}
cur.states[id] = null;
}
}
/* Note on invariants: States may exit non-locally
* from apply, applyto/applyfrom or reapply (e.g. by
* throwing Loading exceptions) in a defined way
* provided they do so before they have changed any GL
* state. If they exit non-locally after GL state has
* been altered, future results are undefined. */
for(int i = 0; i < deplist.length; i++) {
int id = deplist[i].id;
if(repl[id]) {
if(next.states[id] != null) {
next.states[id].apply(g);
cur.states[id] = next.states[id];
if(debug)
stcheckerr(g, "apply", cur.states[id]);
}
if(!pdirty && (prog != null))
prog.adirty(deplist[i]);
} else if(trans[id]) {
cur.states[id].applyto(g, next.states[id]);
if(debug)
stcheckerr(g, "applyto", cur.states[id]);
next.states[id].applyfrom(g, cur.states[id]);
cur.states[id] = next.states[id];
if(debug)
stcheckerr(g, "applyfrom", cur.states[id]);
if(!pdirty && (prog != null))
prog.adirty(deplist[i]);
} else if((prog != null) && pdirty && (shaders[id] != null)) {
cur.states[id].reapply(g);
if(debug)
stcheckerr(g, "reapply", cur.states[id]);
}
}
if((ccam != cam) || (cwxf != wxf)) {
/* See comment above */
mv.load(ccam = cam).mul1(cwxf = wxf);
matmode(GL2.GL_MODELVIEW);
gl.glLoadMatrixf(mv.m, 0);
}
if(prog != null)
prog.autoapply(g, pdirty);
pdirty = false;
checkerr(gl);
if(Config.profile)
time += System.nanoTime() - st;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "apply" | "public void apply(GOut g) {
long st = 0;
if(Config.profile) st = System.nanoTime();
<MASK>Slot<?>[] deplist = GLState.deplist;</MASK>
if(trans.length < slotnum) {
synchronized(Slot.class) {
trans = new boolean[slotnum];
repl = new boolean[slotnum];
shaders = Utils.extend(shaders, slotnum);
}
}
bufdiff(cur, next, trans, repl);
boolean dirty = false;
for(int i = trans.length - 1; i >= 0; i--) {
if(repl[i] || trans[i]) {
GLState nst = next.states[i];
ShaderMacro[] ns = (nst == null)?null:nst.shaders();
if(ns != shaders[i]) {
proghash ^= System.identityHashCode(shaders[i]) ^ System.identityHashCode(ns);
shaders[i] = ns;
dirty = true;
}
}
}
usedprog = prog != null;
if(dirty) {
ShaderMacro.Program np;
boolean shreq = false;
for(int i = 0; i < trans.length; i++) {
if((shaders[i] != null) && next.states[i].reqshaders()) {
shreq = true;
break;
}
}
if(shreq && g.gc.pref.shuse.val) {
np = findprog(proghash, shaders);
} else {
np = null;
}
if(np != prog) {
if(np != null)
np.apply(g);
else
g.gl.glUseProgramObjectARB(0);
prog = np;
if(debug)
checkerr(g.gl);
pdirty = true;
}
}
if((prog != null) != usedprog) {
for(int i = 0; i < trans.length; i++) {
if(trans[i])
repl[i] = true;
}
}
cur.copy(old);
for(int i = deplist.length - 1; i >= 0; i--) {
int id = deplist[i].id;
if(repl[id]) {
if(cur.states[id] != null) {
cur.states[id].unapply(g);
if(debug)
stcheckerr(g, "unapply", cur.states[id]);
}
cur.states[id] = null;
}
}
/* Note on invariants: States may exit non-locally
* from apply, applyto/applyfrom or reapply (e.g. by
* throwing Loading exceptions) in a defined way
* provided they do so before they have changed any GL
* state. If they exit non-locally after GL state has
* been altered, future results are undefined. */
for(int i = 0; i < deplist.length; i++) {
int id = deplist[i].id;
if(repl[id]) {
if(next.states[id] != null) {
next.states[id].apply(g);
cur.states[id] = next.states[id];
if(debug)
stcheckerr(g, "apply", cur.states[id]);
}
if(!pdirty && (prog != null))
prog.adirty(deplist[i]);
} else if(trans[id]) {
cur.states[id].applyto(g, next.states[id]);
if(debug)
stcheckerr(g, "applyto", cur.states[id]);
next.states[id].applyfrom(g, cur.states[id]);
cur.states[id] = next.states[id];
if(debug)
stcheckerr(g, "applyfrom", cur.states[id]);
if(!pdirty && (prog != null))
prog.adirty(deplist[i]);
} else if((prog != null) && pdirty && (shaders[id] != null)) {
cur.states[id].reapply(g);
if(debug)
stcheckerr(g, "reapply", cur.states[id]);
}
}
if((ccam != cam) || (cwxf != wxf)) {
/* See comment above */
mv.load(ccam = cam).mul1(cwxf = wxf);
matmode(GL2.GL_MODELVIEW);
gl.glLoadMatrixf(mv.m, 0);
}
if(prog != null)
prog.autoapply(g, pdirty);
pdirty = false;
checkerr(gl);
if(Config.profile)
time += System.nanoTime() - st;
}" |
Inversion-Mutation | megadiff | "private void writeObject(ObjectOutputStream stream)
throws IOException {
stream.writeObject(back);
stream.writeObject(front);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "writeObject" | "private void writeObject(ObjectOutputStream stream)
throws IOException {
<MASK>stream.writeObject(front);</MASK>
stream.writeObject(back);
}" |
Inversion-Mutation | megadiff | "private Injector createWebInjector() {
final List<Module> modules = new ArrayList<Module>();
modules.add(sshInjector.getInstance(WebModule.class));
modules.add(sshInjector.getInstance(ProjectQoSFilter.Module.class));
return sysInjector.createChildInjector(modules);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createWebInjector" | "private Injector createWebInjector() {
final List<Module> modules = new ArrayList<Module>();
<MASK>modules.add(sshInjector.getInstance(ProjectQoSFilter.Module.class));</MASK>
modules.add(sshInjector.getInstance(WebModule.class));
return sysInjector.createChildInjector(modules);
}" |
Inversion-Mutation | megadiff | "@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_tag_activity);
if (savedInstanceState != null) {
mTagIdInEdit = savedInstanceState.getLong(BUNDLE_KEY_TAG_ID_IN_EDIT, -1);
}
// Set up the check box to toggle My tag sharing.
mEnabled = (CheckBox) findViewById(R.id.toggle_enabled_checkbox);
mEnabled.setChecked(false); // Set after initial data load completes.
findViewById(R.id.toggle_enabled_target).setOnClickListener(this);
// Setup the active tag selector.
mActiveTagDetails = findViewById(R.id.active_tag_details);
mSelectActiveTagAnchor = findViewById(R.id.choose_my_tag);
findViewById(R.id.active_tag).setOnClickListener(this);
updateActiveTagView(null); // Filled in after initial data load.
mActiveTagId = getPreferences(Context.MODE_PRIVATE).getLong(PREF_KEY_ACTIVE_TAG, -1);
// Setup the list.
mAdapter = new TagAdapter(this);
mList = (ListView) findViewById(android.R.id.list);
mList.setAdapter(mAdapter);
mList.setOnItemClickListener(this);
findViewById(R.id.add_tag).setOnClickListener(this);
// Don't setup the empty view until after the first load
// so the empty text doesn't flash when first loading the
// activity.
mList.setEmptyView(null);
// Kick off an async task to load the tags.
new TagLoaderTask().execute((Void[]) null);
// If we're not on a user build offer a back door for writing tags.
// The UX is horrible so we don't want to ship it but need it for testing.
if (!Build.TYPE.equalsIgnoreCase("user")) {
mWriteSupport = true;
}
registerForContextMenu(mList);
if (getIntent().hasExtra(EditTagActivity.EXTRA_RESULT_MSG)) {
NdefMessage msg = (NdefMessage) Preconditions.checkNotNull(
getIntent().getParcelableExtra(EditTagActivity.EXTRA_RESULT_MSG));
saveNewMessage(msg);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCreate" | "@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_tag_activity);
if (savedInstanceState != null) {
mTagIdInEdit = savedInstanceState.getLong(BUNDLE_KEY_TAG_ID_IN_EDIT, -1);
}
// Set up the check box to toggle My tag sharing.
mEnabled = (CheckBox) findViewById(R.id.toggle_enabled_checkbox);
mEnabled.setChecked(false); // Set after initial data load completes.
findViewById(R.id.toggle_enabled_target).setOnClickListener(this);
// Setup the active tag selector.
mActiveTagDetails = findViewById(R.id.active_tag_details);
mSelectActiveTagAnchor = findViewById(R.id.choose_my_tag);
findViewById(R.id.active_tag).setOnClickListener(this);
updateActiveTagView(null); // Filled in after initial data load.
mActiveTagId = getPreferences(Context.MODE_PRIVATE).getLong(PREF_KEY_ACTIVE_TAG, -1);
// Setup the list.
mAdapter = new TagAdapter(this);
mList = (ListView) findViewById(android.R.id.list);
mList.setAdapter(mAdapter);
mList.setOnItemClickListener(this);
findViewById(R.id.add_tag).setOnClickListener(this);
// Don't setup the empty view until after the first load
// so the empty text doesn't flash when first loading the
// activity.
mList.setEmptyView(null);
// Kick off an async task to load the tags.
new TagLoaderTask().execute((Void[]) null);
// If we're not on a user build offer a back door for writing tags.
// The UX is horrible so we don't want to ship it but need it for testing.
if (!Build.TYPE.equalsIgnoreCase("user")) {
mWriteSupport = true;
<MASK>registerForContextMenu(mList);</MASK>
}
if (getIntent().hasExtra(EditTagActivity.EXTRA_RESULT_MSG)) {
NdefMessage msg = (NdefMessage) Preconditions.checkNotNull(
getIntent().getParcelableExtra(EditTagActivity.EXTRA_RESULT_MSG));
saveNewMessage(msg);
}
}" |
Inversion-Mutation | megadiff | "public void renderCSS(ResourceRenderer renderer, String path) throws RenderingException, IOException {
Orientation orientation = Orientation.LT;
if (path.endsWith("-lt.css")) {
path = path.substring(0, path.length() - "-lt.css".length()) + ".css";
} else if (path.endsWith("-rt.css")) {
path = path.substring(0, path.length() - "-rt.css".length()) + ".css";
orientation = Orientation.RT;
}
// Try cache first
if (!PropertyManager.isDevelopping()) {
if (path.startsWith("/portal/resource")) {
renderer.setExpiration(ONE_MONTH);
} else {
renderer.setExpiration(ONE_HOUR);
}
//
Map<String, String> cache = orientation == Orientation.LT ? ltCache : rtCache;
String css = cache.get(path);
if (css == null) {
StringBuilder sb = new StringBuilder();
processCSS(sb, path, orientation, true);
css = sb.toString();
cache.put(path, css);
}
renderer.getAppendable().append(css);
} else {
processCSS(renderer.getAppendable(), path, orientation, false);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "renderCSS" | "public void renderCSS(ResourceRenderer renderer, String path) throws RenderingException, IOException {
Orientation orientation = Orientation.LT;
if (path.endsWith("-lt.css")) {
path = path.substring(0, path.length() - "-lt.css".length()) + ".css";
} else if (path.endsWith("-rt.css")) {
path = path.substring(0, path.length() - "-rt.css".length()) + ".css";
orientation = Orientation.RT;
}
// Try cache first
if (!PropertyManager.isDevelopping()) {
if (path.startsWith("/portal/resource")) {
renderer.setExpiration(ONE_MONTH);
} else {
renderer.setExpiration(ONE_HOUR);
}
//
Map<String, String> cache = orientation == Orientation.LT ? ltCache : rtCache;
String css = cache.get(path);
if (css == null) {
StringBuilder sb = new StringBuilder();
processCSS(sb, path, orientation, true);
css = sb.toString();
cache.put(path, css);
<MASK>renderer.getAppendable().append(css);</MASK>
}
} else {
processCSS(renderer.getAppendable(), path, orientation, false);
}
}" |
Inversion-Mutation | megadiff | "@SuppressWarnings("serial")
public MyRosPage(final PageParameters parameters)
throws URISyntaxException, ROSRSException {
super(parameters);
List<URI> uris = ROSRService.getROList(rodlURI, MySession.get().getdLibraAccessToken());
final List<ResearchObject> researchObjects = new ArrayList<ResearchObject>();
for (URI uri : uris) {
try {
researchObjects
.add(RoFactory.createResearchObject(rodlURI, uri, false, MySession.get().getUsernames()));
} catch (Exception e) {
error("Could not get manifest for: " + uri + " (" + e.getMessage() + ")");
}
}
final Form<?> form = new Form<Void>("form");
form.setOutputMarkupId(true);
add(form);
form.add(new MyFeedbackPanel("feedbackPanel"));
CheckGroup<ResearchObject> group = new CheckGroup<ResearchObject>("group", selectedResearchObjects);
form.add(group);
RefreshingView<ResearchObject> list = new MyROsRefreshingView("rosListView", researchObjects);
group.add(list);
final Label deleteCntLabel = new Label("deleteCnt", new PropertyModel<String>(this, "deleteCnt"));
deleteCntLabel.setOutputMarkupId(true);
add(deleteCntLabel);
final Form<?> addForm = new Form<Void>("addForm");
RequiredTextField<String> name = new RequiredTextField<String>("roId", new PropertyModel<String>(this, "roId"));
name.add(new IValidator<String>() {
@Override
public void validate(IValidatable<String> validatable) {
try {
if (!ROSRService.isRoIdFree(((PortalApplication) getApplication()).getRodlURI(),
validatable.getValue())) {
validatable.error(new ValidationError().setMessage("This ID is already in use"));
}
} catch (Exception e) {
LOG.error(e);
// assume it's ok
}
}
});
addForm.add(name);
add(addForm);
addFeedbackPanel = new MyFeedbackPanel("addFeedbackPanel");
addFeedbackPanel.setOutputMarkupId(true);
addForm.add(addFeedbackPanel);
form.add(new MyAjaxButton("delete", form) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
form.process(null);
if (!selectedResearchObjects.isEmpty()) {
target.add(deleteCntLabel);
target.appendJavaScript("$('#confirm-delete-modal').modal('show')");
}
}
});
deleteFeedbackPanel = new MyFeedbackPanel("deleteFeedbackPanel");
deleteFeedbackPanel.setOutputMarkupId(true);
add(deleteFeedbackPanel);
add(new MyAjaxButton("confirmDelete", form) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
Token dLibraToken = MySession.get().getdLibraAccessToken();
for (AggregatedResource ro : selectedResearchObjects) {
try {
ROSRService.deleteResearchObject(ro.getURI(), dLibraToken);
researchObjects.remove(ro);
} catch (Exception e) {
error("Could not delete Research Object: " + ro.getURI() + " (" + e.getMessage() + ")");
}
}
target.add(form);
target.add(deleteFeedbackPanel);
target.appendJavaScript("$('#confirm-delete-modal').modal('hide')");
}
});
add(new MyAjaxButton("cancelDelete", form) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
target.appendJavaScript("$('#confirm-delete-modal').modal('hide')");
}
});
form.add(new MyAjaxButton("add", form) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
target.appendJavaScript("$('#confirm-add-modal').modal('show')");
}
});
addForm.add(new MyAjaxButton("confirmAdd", addForm) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> addForm) {
super.onSubmit(target, addForm);
Token dLibraToken = MySession.get().getdLibraAccessToken();
try {
ClientResponse response = ROSRService.createResearchObject(
((PortalApplication) getApplication()).getRodlURI(), roId, dLibraToken);
if (response.getStatus() == HttpStatus.SC_CREATED) {
URI researchObjectURI = response.getLocation();
researchObjects.add(RoFactory.createResearchObject(rodlURI, researchObjectURI, false, MySession
.get().getUsernames()));
target.appendJavaScript("$('#confirm-add-modal').modal('hide')");
} else if (response.getStatus() == HttpStatus.SC_CONFLICT) {
error("This ID is already used.");
}
} catch (ROSRSException e) {
error("Could not add Research Object: " + roId + " (" + e.getMessage() + ")");
}
target.add(form);
target.add(addFeedbackPanel);
}
@Override
protected void onError(AjaxRequestTarget target, Form<?> form) {
super.onError(target, form);
target.add(addFeedbackPanel);
}
});
addForm.add(new MyAjaxButton("cancelAdd", addForm) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
target.appendJavaScript("$('#confirm-add-modal').modal('hide')");
}
}.setDefaultFormProcessing(false));
form.add(new BookmarkablePageLink<Void>("myExpImport", MyExpImportPage.class));
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "MyRosPage" | "@SuppressWarnings("serial")
public MyRosPage(final PageParameters parameters)
throws URISyntaxException, ROSRSException {
super(parameters);
List<URI> uris = ROSRService.getROList(rodlURI, MySession.get().getdLibraAccessToken());
final List<ResearchObject> researchObjects = new ArrayList<ResearchObject>();
for (URI uri : uris) {
try {
researchObjects
.add(RoFactory.createResearchObject(rodlURI, uri, false, MySession.get().getUsernames()));
} catch (Exception e) {
error("Could not get manifest for: " + uri + " (" + e.getMessage() + ")");
}
}
final Form<?> form = new Form<Void>("form");
form.setOutputMarkupId(true);
add(form);
form.add(new MyFeedbackPanel("feedbackPanel"));
CheckGroup<ResearchObject> group = new CheckGroup<ResearchObject>("group", selectedResearchObjects);
form.add(group);
RefreshingView<ResearchObject> list = new MyROsRefreshingView("rosListView", researchObjects);
group.add(list);
final Label deleteCntLabel = new Label("deleteCnt", new PropertyModel<String>(this, "deleteCnt"));
deleteCntLabel.setOutputMarkupId(true);
add(deleteCntLabel);
final Form<?> addForm = new Form<Void>("addForm");
RequiredTextField<String> name = new RequiredTextField<String>("roId", new PropertyModel<String>(this, "roId"));
name.add(new IValidator<String>() {
@Override
public void validate(IValidatable<String> validatable) {
try {
if (!ROSRService.isRoIdFree(((PortalApplication) getApplication()).getRodlURI(),
validatable.getValue())) {
validatable.error(new ValidationError().setMessage("This ID is already in use"));
}
} catch (Exception e) {
LOG.error(e);
// assume it's ok
}
}
});
addForm.add(name);
add(addForm);
addFeedbackPanel = new MyFeedbackPanel("addFeedbackPanel");
addFeedbackPanel.setOutputMarkupId(true);
addForm.add(addFeedbackPanel);
form.add(new MyAjaxButton("delete", form) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
form.process(null);
if (!selectedResearchObjects.isEmpty()) {
target.add(deleteCntLabel);
target.appendJavaScript("$('#confirm-delete-modal').modal('show')");
}
}
});
deleteFeedbackPanel = new MyFeedbackPanel("deleteFeedbackPanel");
deleteFeedbackPanel.setOutputMarkupId(true);
add(deleteFeedbackPanel);
add(new MyAjaxButton("confirmDelete", form) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
Token dLibraToken = MySession.get().getdLibraAccessToken();
for (AggregatedResource ro : selectedResearchObjects) {
try {
ROSRService.deleteResearchObject(ro.getURI(), dLibraToken);
researchObjects.remove(ro);
} catch (Exception e) {
error("Could not delete Research Object: " + ro.getURI() + " (" + e.getMessage() + ")");
}
}
target.add(form);
target.add(deleteFeedbackPanel);
target.appendJavaScript("$('#confirm-delete-modal').modal('hide')");
}
});
add(new MyAjaxButton("cancelDelete", form) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
target.appendJavaScript("$('#confirm-delete-modal').modal('hide')");
}
});
form.add(new MyAjaxButton("add", form) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
target.appendJavaScript("$('#confirm-add-modal').modal('show')");
}
});
addForm.add(new MyAjaxButton("confirmAdd", addForm) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> addForm) {
super.onSubmit(target, addForm);
Token dLibraToken = MySession.get().getdLibraAccessToken();
try {
ClientResponse response = ROSRService.createResearchObject(
((PortalApplication) getApplication()).getRodlURI(), roId, dLibraToken);
if (response.getStatus() == HttpStatus.SC_CREATED) {
URI researchObjectURI = response.getLocation();
researchObjects.add(RoFactory.createResearchObject(rodlURI, researchObjectURI, false, MySession
.get().getUsernames()));
} else if (response.getStatus() == HttpStatus.SC_CONFLICT) {
error("This ID is already used.");
}
} catch (ROSRSException e) {
error("Could not add Research Object: " + roId + " (" + e.getMessage() + ")");
}
target.add(form);
target.add(addFeedbackPanel);
<MASK>target.appendJavaScript("$('#confirm-add-modal').modal('hide')");</MASK>
}
@Override
protected void onError(AjaxRequestTarget target, Form<?> form) {
super.onError(target, form);
target.add(addFeedbackPanel);
}
});
addForm.add(new MyAjaxButton("cancelAdd", addForm) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
<MASK>target.appendJavaScript("$('#confirm-add-modal').modal('hide')");</MASK>
}
}.setDefaultFormProcessing(false));
form.add(new BookmarkablePageLink<Void>("myExpImport", MyExpImportPage.class));
}" |
Inversion-Mutation | megadiff | "@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> addForm) {
super.onSubmit(target, addForm);
Token dLibraToken = MySession.get().getdLibraAccessToken();
try {
ClientResponse response = ROSRService.createResearchObject(
((PortalApplication) getApplication()).getRodlURI(), roId, dLibraToken);
if (response.getStatus() == HttpStatus.SC_CREATED) {
URI researchObjectURI = response.getLocation();
researchObjects.add(RoFactory.createResearchObject(rodlURI, researchObjectURI, false, MySession
.get().getUsernames()));
target.appendJavaScript("$('#confirm-add-modal').modal('hide')");
} else if (response.getStatus() == HttpStatus.SC_CONFLICT) {
error("This ID is already used.");
}
} catch (ROSRSException e) {
error("Could not add Research Object: " + roId + " (" + e.getMessage() + ")");
}
target.add(form);
target.add(addFeedbackPanel);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onSubmit" | "@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> addForm) {
super.onSubmit(target, addForm);
Token dLibraToken = MySession.get().getdLibraAccessToken();
try {
ClientResponse response = ROSRService.createResearchObject(
((PortalApplication) getApplication()).getRodlURI(), roId, dLibraToken);
if (response.getStatus() == HttpStatus.SC_CREATED) {
URI researchObjectURI = response.getLocation();
researchObjects.add(RoFactory.createResearchObject(rodlURI, researchObjectURI, false, MySession
.get().getUsernames()));
} else if (response.getStatus() == HttpStatus.SC_CONFLICT) {
error("This ID is already used.");
}
} catch (ROSRSException e) {
error("Could not add Research Object: " + roId + " (" + e.getMessage() + ")");
}
target.add(form);
target.add(addFeedbackPanel);
<MASK>target.appendJavaScript("$('#confirm-add-modal').modal('hide')");</MASK>
}" |
Inversion-Mutation | megadiff | "public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
Player send;
if(!(sender instanceof Player)){
sender.sendMessage(title + ChatColor.RED + "Player context is required!");
return true;
}
send = (Player) sender;
// /home
if(args.length==0){
if(plugin.homesManager.homes.containsKey(send.getName())){
Home home = plugin.homesManager.homes.get(send.getName());
Location loc = send.getLocation();
send.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1);
send.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1);
send.getWorld().playEffect(loc, Effect.STEP_SOUND, 51);
loc = home.pos;
loc.getWorld().loadChunk(loc.getWorld().getChunkAt(loc));
send.teleport(home.pos);
loc.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1);
loc.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1);
loc.getWorld().playEffect(loc, Effect.STEP_SOUND, 51);
send.sendMessage(title + "Home, sweet home.");
} else{
sender.sendMessage(title + ChatColor.RED + "You need a home!");
}
return true;
}else if(args.length==1){
// /home help
if(args[0].equals("help")){
return false;
} else
// /home set
if(args[0].equals("set")){
Location loc = send.getLocation();
plugin.homesManager.homes.put(send.getName(), new Home(loc));
FileConfiguration config = plugin.homesYML;
String name = send.getName();
boolean newHome;
newHome = config.getString(send.getName()) == null;
config.set(name + ".x", loc.getX());
config.set(name + ".y", loc.getY());
config.set(name + ".z", loc.getZ());
config.set(name + ".yaw", loc.getPitch());
config.set(name + ".pitch", loc.getYaw());
config.set(name + ".world", loc.getWorld().getName());
if(newHome) config.set(name + ".open", false);
plugin.saveHomes();
loc.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1);
loc.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1);
loc.getWorld().playEffect(loc, Effect.STEP_SOUND, 51);
send.sendMessage(title + "Home set.");
} else
// /home open
if(args[0].equals("open")){
if(plugin.homesManager.homes.containsKey(send.getName())){
plugin.homesManager.openHomes.add(send.getName());
FileConfiguration config = plugin.homesYML;
config.set(send.getName() + ".open", true);
plugin.saveHomes();
Location home = plugin.homesManager.homes.get(send.getName()).pos;
home.getWorld().playEffect(home, Effect.ENDER_SIGNAL, 1);
home.getWorld().playEffect(home, Effect.MOBSPAWNER_FLAMES, 1);
home.getWorld().playEffect(home, Effect.STEP_SOUND, 111);
send.sendMessage(title + "Your home is now " + ChatColor.DARK_GREEN + "open" + ChatColor.GRAY + " to guests.");
} else{
send.sendMessage(title + ChatColor.RED + "You need a home!");
}
} else
// /home close
if(args[0].equals("close")){
if(plugin.homesManager.homes.containsKey(send.getName())){
plugin.homesManager.openHomes.remove(send.getName());
FileConfiguration config = plugin.homesYML;
config.set(send.getName() + ".open", false);
plugin.saveHomes();
Location home = plugin.homesManager.homes.get(send.getName()).pos;
home.getWorld().playEffect(home, Effect.ENDER_SIGNAL, 1);
home.getWorld().playEffect(home, Effect.MOBSPAWNER_FLAMES, 1);
home.getWorld().playEffect(home, Effect.STEP_SOUND, 40);
send.sendMessage(title + "Your home is now " + ChatColor.DARK_RED + "closed" + ChatColor.DARK_GRAY + " to guests.");
} else{
send.sendMessage(title + ChatColor.RED + "You need a home!");
}
} else
// /home [player]
{
Player target = plugin.getServer().getPlayer(args[0]);
String name;
if(target==null){
if(plugin.homesManager.homes.containsKey(args[0])){
name = args[0];
} else{
send.sendMessage(title + ChatColor.RED + "That player does not exist!");
return true;
}
}
name = target.getName();
if(!plugin.homesManager.homes.containsKey(name)){
send.sendMessage(title + ChatColor.RED + "That player does not have a home!");
}else if(!plugin.homesManager.openHomes.contains(name)&&!send.isOp()&&!send.getName().equals(target.getName())){
send.sendMessage(title + ChatColor.RED + "That player's home is " + ChatColor.DARK_RED + "closed" + ChatColor.RED + "!");
} else{
Location loc = send.getLocation();
Home home = plugin.homesManager.homes.get(name);
send.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1);
send.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1);
send.getWorld().playEffect(loc, Effect.STEP_SOUND, 51);
loc = home.pos;
loc.getWorld().loadChunk(loc.getWorld().getChunkAt(loc));
send.teleport(home.pos);
loc.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1);
loc.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1);
loc.getWorld().playEffect(loc, Effect.STEP_SOUND, 51);
send.sendMessage(title + "Welcome.");
}
}
return true;
} else if(args.length==2){
if(args[0].equals("set")&&args[1].equals("bed")){
Location loc = send.getBedSpawnLocation();
if(loc==null){
send.sendMessage(title + ChatColor.RED + "You need a bed!");
return true;
}
plugin.homesManager.homes.put(send.getName(), new Home(loc));
FileConfiguration config = plugin.homesYML;
String name = send.getName();
boolean newHome;
newHome = config.getString(send.getName()) == null;
config.set(name + ".x", loc.getX());
config.set(name + ".y", loc.getY());
config.set(name + ".z", loc.getZ());
config.set(name + ".yaw", loc.getPitch());
config.set(name + ".pitch", loc.getYaw());
config.set(name + ".world", loc.getWorld().getName());
if(newHome) config.set(name + ".open", false);
plugin.saveHomes();
loc.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1);
loc.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1);
loc.getWorld().playEffect(loc, Effect.STEP_SOUND, 51);
send.sendMessage(title + "Home set to bed.");
return true;
}
return false;
}
return false;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCommand" | "public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
Player send;
if(!(sender instanceof Player)){
sender.sendMessage(title + ChatColor.RED + "Player context is required!");
return true;
}
send = (Player) sender;
// /home
if(args.length==0){
if(plugin.homesManager.homes.containsKey(send.getName())){
Home home = plugin.homesManager.homes.get(send.getName());
Location loc = send.getLocation();
send.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1);
send.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1);
send.getWorld().playEffect(loc, Effect.STEP_SOUND, 51);
loc = home.pos;
loc.getWorld().loadChunk(loc.getWorld().getChunkAt(loc));
loc.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1);
loc.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1);
loc.getWorld().playEffect(loc, Effect.STEP_SOUND, 51);
<MASK>send.teleport(home.pos);</MASK>
send.sendMessage(title + "Home, sweet home.");
} else{
sender.sendMessage(title + ChatColor.RED + "You need a home!");
}
return true;
}else if(args.length==1){
// /home help
if(args[0].equals("help")){
return false;
} else
// /home set
if(args[0].equals("set")){
Location loc = send.getLocation();
plugin.homesManager.homes.put(send.getName(), new Home(loc));
FileConfiguration config = plugin.homesYML;
String name = send.getName();
boolean newHome;
newHome = config.getString(send.getName()) == null;
config.set(name + ".x", loc.getX());
config.set(name + ".y", loc.getY());
config.set(name + ".z", loc.getZ());
config.set(name + ".yaw", loc.getPitch());
config.set(name + ".pitch", loc.getYaw());
config.set(name + ".world", loc.getWorld().getName());
if(newHome) config.set(name + ".open", false);
plugin.saveHomes();
loc.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1);
loc.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1);
loc.getWorld().playEffect(loc, Effect.STEP_SOUND, 51);
send.sendMessage(title + "Home set.");
} else
// /home open
if(args[0].equals("open")){
if(plugin.homesManager.homes.containsKey(send.getName())){
plugin.homesManager.openHomes.add(send.getName());
FileConfiguration config = plugin.homesYML;
config.set(send.getName() + ".open", true);
plugin.saveHomes();
Location home = plugin.homesManager.homes.get(send.getName()).pos;
home.getWorld().playEffect(home, Effect.ENDER_SIGNAL, 1);
home.getWorld().playEffect(home, Effect.MOBSPAWNER_FLAMES, 1);
home.getWorld().playEffect(home, Effect.STEP_SOUND, 111);
send.sendMessage(title + "Your home is now " + ChatColor.DARK_GREEN + "open" + ChatColor.GRAY + " to guests.");
} else{
send.sendMessage(title + ChatColor.RED + "You need a home!");
}
} else
// /home close
if(args[0].equals("close")){
if(plugin.homesManager.homes.containsKey(send.getName())){
plugin.homesManager.openHomes.remove(send.getName());
FileConfiguration config = plugin.homesYML;
config.set(send.getName() + ".open", false);
plugin.saveHomes();
Location home = plugin.homesManager.homes.get(send.getName()).pos;
home.getWorld().playEffect(home, Effect.ENDER_SIGNAL, 1);
home.getWorld().playEffect(home, Effect.MOBSPAWNER_FLAMES, 1);
home.getWorld().playEffect(home, Effect.STEP_SOUND, 40);
send.sendMessage(title + "Your home is now " + ChatColor.DARK_RED + "closed" + ChatColor.DARK_GRAY + " to guests.");
} else{
send.sendMessage(title + ChatColor.RED + "You need a home!");
}
} else
// /home [player]
{
Player target = plugin.getServer().getPlayer(args[0]);
String name;
if(target==null){
if(plugin.homesManager.homes.containsKey(args[0])){
name = args[0];
} else{
send.sendMessage(title + ChatColor.RED + "That player does not exist!");
return true;
}
}
name = target.getName();
if(!plugin.homesManager.homes.containsKey(name)){
send.sendMessage(title + ChatColor.RED + "That player does not have a home!");
}else if(!plugin.homesManager.openHomes.contains(name)&&!send.isOp()&&!send.getName().equals(target.getName())){
send.sendMessage(title + ChatColor.RED + "That player's home is " + ChatColor.DARK_RED + "closed" + ChatColor.RED + "!");
} else{
Location loc = send.getLocation();
Home home = plugin.homesManager.homes.get(name);
send.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1);
send.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1);
send.getWorld().playEffect(loc, Effect.STEP_SOUND, 51);
loc = home.pos;
loc.getWorld().loadChunk(loc.getWorld().getChunkAt(loc));
<MASK>send.teleport(home.pos);</MASK>
loc.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1);
loc.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1);
loc.getWorld().playEffect(loc, Effect.STEP_SOUND, 51);
send.sendMessage(title + "Welcome.");
}
}
return true;
} else if(args.length==2){
if(args[0].equals("set")&&args[1].equals("bed")){
Location loc = send.getBedSpawnLocation();
if(loc==null){
send.sendMessage(title + ChatColor.RED + "You need a bed!");
return true;
}
plugin.homesManager.homes.put(send.getName(), new Home(loc));
FileConfiguration config = plugin.homesYML;
String name = send.getName();
boolean newHome;
newHome = config.getString(send.getName()) == null;
config.set(name + ".x", loc.getX());
config.set(name + ".y", loc.getY());
config.set(name + ".z", loc.getZ());
config.set(name + ".yaw", loc.getPitch());
config.set(name + ".pitch", loc.getYaw());
config.set(name + ".world", loc.getWorld().getName());
if(newHome) config.set(name + ".open", false);
plugin.saveHomes();
loc.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1);
loc.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1);
loc.getWorld().playEffect(loc, Effect.STEP_SOUND, 51);
send.sendMessage(title + "Home set to bed.");
return true;
}
return false;
}
return false;
}" |
Inversion-Mutation | megadiff | "public Set<Outage> updateOutages(final Set<ProtoOutage> outages) {
final Set<Outage> ret = new HashSet<Outage>();
for (ProtoOutage protoOutage : outages) {
final Outage existingOutage = getActiveOutage(
protoOutage.outage.getLat(), protoOutage.outage.getLon());
final AbstractOutageRevision newRevision = Iterables
.getOnlyElement(protoOutage.outage.getRevisions());
if (existingOutage == null) {// If there is no existing outage.
sessionFactory.getCurrentSession().save(protoOutage.outage);
sessionFactory.getCurrentSession().save(newRevision);
ret.add(protoOutage.outage);
} else {
existingOutage.getZoomLevels().addAll(
protoOutage.outage.getZoomLevels());
newRevision.setOutage(existingOutage);
// Test that no updates need to be made to the revision.
if (existingOutage.getRevisions().first()
.equalsIgnoreRun(newRevision)) {
// Ignore it.
} else {
ret.add(existingOutage);
sessionFactory.getCurrentSession().save(newRevision);
}
}
}
return ret;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "updateOutages" | "public Set<Outage> updateOutages(final Set<ProtoOutage> outages) {
final Set<Outage> ret = new HashSet<Outage>();
for (ProtoOutage protoOutage : outages) {
final Outage existingOutage = getActiveOutage(
protoOutage.outage.getLat(), protoOutage.outage.getLon());
final AbstractOutageRevision newRevision = Iterables
.getOnlyElement(protoOutage.outage.getRevisions());
if (existingOutage == null) {// If there is no existing outage.
sessionFactory.getCurrentSession().save(protoOutage.outage);
sessionFactory.getCurrentSession().save(newRevision);
ret.add(protoOutage.outage);
} else {
<MASK>ret.add(existingOutage);</MASK>
existingOutage.getZoomLevels().addAll(
protoOutage.outage.getZoomLevels());
newRevision.setOutage(existingOutage);
// Test that no updates need to be made to the revision.
if (existingOutage.getRevisions().first()
.equalsIgnoreRun(newRevision)) {
// Ignore it.
} else {
sessionFactory.getCurrentSession().save(newRevision);
}
}
}
return ret;
}" |
Inversion-Mutation | megadiff | "private final boolean interpretShort(InstructionF99b ins) {
int fromPC = iblock.pc;
MachineOperandF99b mop1 = (MachineOperandF99b)ins.getOp1();
switch (ins.getInst()) {
case Icmp:
case Icmp+1:
case Icmp+2:
case Icmp+3:
case Icmp+4:
case Icmp+5:
case Icmp+6:
case Icmp+7: {
short r = cpu.pop();
short l = cpu.pop();
boolean c = false;
switch (ins.getInst() & 0x7) {
case InstF99b.CMP_GE: c = l >= r; break;
case InstF99b.CMP_GT: c = l > r; break;
case InstF99b.CMP_LE: c = l <= r; break;
case InstF99b.CMP_LT: c = l < r; break;
case InstF99b.CMP_UGE: c = (l & 0xffff) >= (r & 0xffff); break;
case InstF99b.CMP_UGT: c = (l & 0xffff) > (r & 0xffff); break;
case InstF99b.CMP_ULE: c = (l & 0xffff) <= (r & 0xffff); break;
case InstF99b.CMP_ULT: c = (l & 0xffff) < (r & 0xffff); break;
}
cpu.push((short) (c ? -1 : 0));
return false;
}
case Imath_start:
case Imath_start+1:
case Imath_start+2:
case Imath_start+3:
case Imath_start+4:
case Imath_start+5: {
short r = cpu.pop();
short l = cpu.pop();
cpu.push((short) binOp(l, r, ins.getInst() - Imath_start));
return false;
}
case Imath_start+8:
case Imath_start+9:
case Imath_start+10:
case Imath_start+11:
case Imath_start+12:
case Imath_start+13:
case Imath_start+14:
case Imath_start+15: {
short v = cpu.pop();
cpu.push((short) unaryOp(v, ins.getInst() - Imath_start));
return false;
}
case Iload:
cpu.push(memory.readWord(cpu.pop()));
break;
case Icload:
cpu.push((short) (memory.readByte(cpu.pop()) & 0xff));
break;
case Istore: {
int addr = cpu.pop();
memory.writeWord(addr, cpu.pop());
break;
}
case Icstore: {
int addr = cpu.pop();
memory.writeByte(addr, (byte) cpu.pop());
break;
}
case IplusStore: {
short addr = cpu.pop();
iblock.domain.writeWord(addr, (short) (iblock.domain.readWord(addr) + cpu.pop()));
break;
}
case IcplusStore: {
short addr = cpu.pop();
iblock.domain.writeByte(addr, (byte) (iblock.domain.readByte(addr) + cpu.pop()));
break;
}
case IlitB:
case IlitW:
case IlitX:
cpu.push(mop1.immed);
break;
case Iexit:
cpu.setPC(cpu.rpop());
return true;
case Iexiti:
cpu.setPC(cpu.rpop());
cpu.setST(cpu.rpop());
cpu.noIntCount+=2;
return true;
case Idup:
cpu.push(cpu.peek());
break;
case Iqdup: {
short val = cpu.peek();
if (val != 0)
cpu.push(val);
break;
}
case I0branchX:
case I0branchB:
case I0branchW:
{
short targ = (short) (fromPC + mop1.immed);
if (cpu.pop() == 0) {
cpu.setPC(targ);
return true;
}
break;
}
case IbranchX:
case IbranchB:
case IbranchW:
{
short targ = (short) (fromPC + mop1.immed);
cpu.setPC(targ);
return true;
}
case I0equ:
cpu.push((short) (cpu.pop() == 0 ? -1 : 0));
break;
case Iequ:
cpu.push((short) (cpu.pop() == cpu.pop() ? -1 : 0));
break;
case Idrop:
cpu.pop();
break;
case Iswap: {
short x = cpu.pop();
short y = cpu.pop();
cpu.push(x);
cpu.push(y);
break;
}
case Iover:
cpu.push(iblock.getStackEntry(1));
break;
case Irot: {
short x = cpu.pop();
short y = cpu.pop();
short z = cpu.pop();
cpu.push(y);
cpu.push(x);
cpu.push(z);
break;
}
case Iumul: {
int mul = (cpu.pop() & 0xffff) * (cpu.pop() & 0xffff);
cpu.push((short) (mul & 0xffff));
cpu.push((short) (mul >> 16));
break;
}
case Iudivmod: {
int div = cpu.pop() & 0xffff;
int num = cpu.popd();
if (div == 0) {
cpu.push((short) -1);
cpu.push((short) 0);
} else {
int quot = num / div;
int rem = num % div;
if (quot >= 65536) {
cpu.push((short) -1);
cpu.push((short) 0);
} else {
cpu.push((short) rem);
cpu.push((short) quot);
}
}
break;
}
case Iand:
cpu.push((short) (cpu.pop() & cpu.pop()));
break;
case Ior:
cpu.push((short) (cpu.pop() | cpu.pop()));
break;
case Ixor:
cpu.push((short) (cpu.pop() ^ cpu.pop()));
break;
case Inot:
cpu.push((short) (cpu.pop() != 0 ? 0 : -1));
break;
case Inand: {
short m = cpu.pop();
short v = cpu.pop();
cpu.push((short) (v & ~m));
break;
}
case Icall:
cpu.rpush(iblock.pc);
cpu.setPC(mop1.immed);
return true;
case Iexecute:
cpu.rpush(iblock.pc);
cpu.setPC(cpu.pop());
return true;
case Idovar:
{
short next = cpu.rpop();
cpu.push(iblock.pc);
cpu.setPC(next);
return true;
}
case ItoR:
cpu.rpush(cpu.pop());
break;
case IRfrom:
cpu.push(cpu.rpop());
break;
case Irdrop:
cpu.rpop();
break;
case IatR:
cpu.push(cpu.rpeek());
break;
case Ispidx:
cpu.push(iblock.getStackEntry(mop1.immed));
break;
case Irpidx:
cpu.push(iblock.getReturnStackEntry(mop1.immed));
break;
case Ilpidx:
cpu.push(iblock.getLocalStackEntry(mop1.immed));
break;
case Ilocal:
cpu.push((short) (iblock.lp - (mop1.immed + 1) * 2));
break;
case Iupidx:
cpu.push((short) (iblock.up + (mop1.val & 0xff)));
break;
case Iuser:
cpu.push((short) (iblock.up + cpu.pop()));
break;
case IloopUp: {
short next = (short) (iblock.getReturnStackEntry(0) + 1);
short lim = iblock.getReturnStackEntry(1);
cpu.rpop();
cpu.rpush(next);
cpu.push((short) ((lim != 0 ? next < lim : next >= 1) ? 0 : -1));
break;
}
case IuloopUp: {
int next = (iblock.getReturnStackEntry(0) + 1) & 0xffff;
short lim = iblock.getReturnStackEntry(1);
cpu.rpop();
cpu.rpush((short) next);
cpu.push((short) ((lim != 0 ? next < (lim & 0xffff)
: next >= (1 & 0xffff)) ? 0 : -1));
break;
}
case IplusLoopUp: {
short change = cpu.pop();
short cur = iblock.getReturnStackEntry(0);
int next = (cur + change);
short lim = iblock.getReturnStackEntry(1);
cpu.rpop();
cpu.rpush((short) next);
cpu.push((short) ((lim != 0 ? (change < 0 ? next > lim : next < lim)
: next >= change) ? 0 : -1));
break;
}
case IuplusLoopUp: {
short change = cpu.pop();
short cur = iblock.getReturnStackEntry(0);
int next = (cur & 0xffff) + change;
short lim = iblock.getReturnStackEntry(1);
cpu.rpop();
cpu.rpush((short) next);
cpu.push((short) ((lim != 0 ? (change < 0 ? next > (lim & 0xffff) : next < (lim & 0xffff))
: (next & 0xffff) >= (change & 0xffff)) ? 0 : -1));
break;
}
case Icfill: {
cpu.addCycles(4);
int step = cpu.pop();
byte ch = (byte) cpu.pop();
int len = cpu.pop() & 0xffff;
int addr = cpu.pop();
while (len-- > 0) {
memory.writeByte(addr, ch);
addr += step;
cpu.addCycles(2);
}
break;
}
case Ifill: {
cpu.addCycles(3);
int step = cpu.pop();
short w = cpu.pop();
int len = cpu.pop() & 0xffff;
int addr = cpu.pop();
while (len-- > 0) {
memory.writeWord(addr, w);
addr += step*2;
cpu.addCycles(2);
}
break;
}
case Icmove: {
doCmove();
break;
}
case Iccompare: {
doCcompare();
break;
}
case Ilalloc: {
cpu.push((short) iblock.sp);
cpu.push((short) (iblock.rp - mop1.immed * 2));
cpu.push((short) (mop1.immed * 2));
cpu.push((short) -1);
cpu.push((short) -1);
doCmove();
((CpuStateF99b)cpu.getState()).setSP((short) (iblock.sp + mop1.immed * 2));
((CpuStateF99b)cpu.getState()).setRP((short) (iblock.rp - mop1.immed * 2));
break;
}
case IcontextFrom:
switch (mop1.immed) {
case CTX_INT:
cpu.push((short) cpu.getStatus().getIntMask());
break;
case CTX_SP:
cpu.push(((CpuStateF99b)cpu.getState()).getSP());
break;
case CTX_SP0:
cpu.push(((CpuStateF99b)cpu.getState()).getBaseSP());
break;
case CTX_RP:
cpu.push(((CpuStateF99b)cpu.getState()).getRP());
break;
case CTX_RP0:
cpu.push(((CpuStateF99b)cpu.getState()).getBaseRP());
break;
case CTX_UP:
cpu.push(((CpuStateF99b)cpu.getState()).getUP());
break;
case CTX_LP:
cpu.push(((CpuStateF99b)cpu.getState()).getLP());
break;
case CTX_PC:
cpu.push(cpu.getPC());
break;
case CTX_SR:
cpu.push(cpu.getStatus().flatten());
break;
default:
cpu.push((short) -1);
break;
}
break;
case ItoContext:
switch (mop1.immed) {
case CTX_INT:
((StatusF99b) ((CpuStateF99b)cpu.getState()).getStatus()).setIntMask(cpu.pop());
break;
case CTX_SP:
((CpuStateF99b)cpu.getState()).setSP(cpu.pop());
break;
case CTX_SP0: {
short sp0 = cpu.pop();
((CpuStateF99b)cpu.getState()).setBaseSP(sp0);
((CpuStateF99b)cpu.getState()).setSP(sp0);
break;
}
case CTX_RP:
((CpuStateF99b)cpu.getState()).setRP(cpu.pop());
break;
case CTX_RP0: {
short rp0 = cpu.pop();
((CpuStateF99b)cpu.getState()).setBaseRP(rp0);
((CpuStateF99b)cpu.getState()).setRP(rp0);
break;
}
case CTX_UP:
((CpuStateF99b)cpu.getState()).setUP(cpu.pop());
break;
case CTX_LP:
((CpuStateF99b)cpu.getState()).setLP(cpu.pop());
break;
case CTX_PC:
((CpuStateF99b)cpu.getState()).setPC(cpu.pop());
return true;
case CTX_SR:
cpu.getState().setST(cpu.pop());
//((StatusF99b) ((CpuStateF99b)cpu.getState()).getStatus()).expand(cpu.pop());
break;
default:
cpu.pop();
break;
}
break;
case Isyscall:
switch (mop1.immed) {
case SYSCALL_DEBUG_OFF: {
int oldCount = machine.getExecutor().debugCount;
machine.getExecutor().debugCount++;
if ((oldCount == 0) != (machine.getExecutor().debugCount == 0))
Executor.settingDumpFullInstructions.setBoolean(false);
break;
}
case SYSCALL_DEBUG_ON: {
int oldCount = machine.getExecutor().debugCount;
machine.getExecutor().debugCount--;
if ((oldCount == 0) != (machine.getExecutor().debugCount == 0))
Executor.settingDumpFullInstructions.setBoolean(true);
break;
}
case SYSCALL_IDLE: {
machine.getCpu().setIdle(true);
break;
}
case SYSCALL_REGISTER_SYMBOL: {
int xt = cpu.pop();
int nfa = cpu.pop();
StringBuilder sb = new StringBuilder();
int len = iblock.domain.readByte(nfa++) & 0x1f;
while (len-- > 0) {
char ch = (char) iblock.domain.readByte(nfa++);
sb.append(ch);
}
iblock.domain.getEntryAt(xt).defineSymbol(xt, sb.toString());
break;
}
case SYSCALL_FIND: {
// ( caddr lfa -- caddr 0 | xt -1=immed | xt 1 )
int lfa = cpu.pop();
int caddr = cpu.pop();
boolean found = false;
int[] after = { 0 };
int count = 65536;
while (lfa != 0 && count-- > 0) {
cpu.addCycles(3);
short nfa = (short) (lfa + 2);
if (nameMatches(iblock.domain, caddr, nfa, after)) {
short xt = (short) after[0];
if ((xt & 1) != 0)
xt++;
cpu.push(xt);
cpu.push((short) ((iblock.domain.readByte(nfa) & 0x40) != 0 ? 1 : -1));
found = true;
break;
} else {
lfa = iblock.domain.readWord(lfa);
}
}
if (!found) {
cpu.push((short) caddr);
cpu.push((short) 0);
}
break;
}
case SYSCALL_GFIND: {
// ( caddr gDictEnd gDict -- caddr 0 | xt 1 | xt -1 )
short gromDictEnd = cpu.pop();
short gromDict = cpu.pop();
int caddr = cpu.pop();
boolean found = false;
int[] after = { 0 };
MemoryDomain grom = cpu.getMachine().getMemory().getDomain(MemoryDomain.NAME_GRAPHICS);
while (gromDict < gromDictEnd) {
cpu.addCycles(3);
if (nameMatches(grom, caddr, gromDict, after)) {
cpu.push(grom.readWord(after[0]));
cpu.push((short) (((grom.readByte(gromDict) & 0x40) != 0) ? 1 : -1));
found = true;
break;
} else {
gromDict = (short) (after[0] + 2);
}
}
if (!found) {
cpu.push((short) caddr);
cpu.push((short) 0);
}
break;
}
/*
case SYSCALL_INTERPRET: {
int dp = cpu.pop();
int len = cpu.pop();
int addr = cpu.pop();
StringBuilder text = new StringBuilder();
while (len-- > 0) {
text.append((char) iblock.domain.readByte(addr++));
}
TargetContext targCtx = new F99bTargetContext(65536);
HostContext hostCtx = new HostContext(targCtx);
ForthComp comp = new ForthComp(hostCtx, targCtx);
ByteArrayOutputStream diag = new ByteArrayOutputStream();
targCtx.setDP(dp);
targCtx.importMemory(iblock.domain);
comp.setLog(new PrintStream(diag));
try {
comp.parseString(text.toString());
} catch (AbortException e) {
e.printStackTrace();
try {
diag.write(e.toString().getBytes());
} catch (IOException e1) {
e1.printStackTrace();
}
}
comp.finish();
if (comp.getErrors() != 0) {
System.err.println("Errors during compilation");
}
try {
targCtx.exportMemory(iblock.domain);
} catch (AbortException e) {
e.printStackTrace();
try {
diag.write(e.toString().getBytes());
} catch (IOException e1) {
e1.printStackTrace();
}
}
cpu.push((short) targCtx.getDP());
break;
}
*/
}
break;
default:
unsupported(ins);
}
return false;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "interpretShort" | "private final boolean interpretShort(InstructionF99b ins) {
int fromPC = iblock.pc;
MachineOperandF99b mop1 = (MachineOperandF99b)ins.getOp1();
switch (ins.getInst()) {
case Icmp:
case Icmp+1:
case Icmp+2:
case Icmp+3:
case Icmp+4:
case Icmp+5:
case Icmp+6:
case Icmp+7: {
short r = cpu.pop();
short l = cpu.pop();
boolean c = false;
switch (ins.getInst() & 0x7) {
case InstF99b.CMP_GE: c = l >= r; break;
case InstF99b.CMP_GT: c = l > r; break;
case InstF99b.CMP_LE: c = l <= r; break;
case InstF99b.CMP_LT: c = l < r; break;
case InstF99b.CMP_UGE: c = (l & 0xffff) >= (r & 0xffff); break;
case InstF99b.CMP_UGT: c = (l & 0xffff) > (r & 0xffff); break;
case InstF99b.CMP_ULE: c = (l & 0xffff) <= (r & 0xffff); break;
case InstF99b.CMP_ULT: c = (l & 0xffff) < (r & 0xffff); break;
}
cpu.push((short) (c ? -1 : 0));
return false;
}
case Imath_start:
case Imath_start+1:
case Imath_start+2:
case Imath_start+3:
case Imath_start+4:
case Imath_start+5: {
short r = cpu.pop();
short l = cpu.pop();
cpu.push((short) binOp(l, r, ins.getInst() - Imath_start));
return false;
}
case Imath_start+8:
case Imath_start+9:
case Imath_start+10:
case Imath_start+11:
case Imath_start+12:
case Imath_start+13:
case Imath_start+14:
case Imath_start+15: {
<MASK>short v = cpu.pop();</MASK>
cpu.push((short) unaryOp(v, ins.getInst() - Imath_start));
return false;
}
case Iload:
cpu.push(memory.readWord(cpu.pop()));
break;
case Icload:
cpu.push((short) (memory.readByte(cpu.pop()) & 0xff));
break;
case Istore: {
int addr = cpu.pop();
memory.writeWord(addr, cpu.pop());
break;
}
case Icstore: {
int addr = cpu.pop();
memory.writeByte(addr, (byte) cpu.pop());
break;
}
case IplusStore: {
short addr = cpu.pop();
iblock.domain.writeWord(addr, (short) (iblock.domain.readWord(addr) + cpu.pop()));
break;
}
case IcplusStore: {
short addr = cpu.pop();
iblock.domain.writeByte(addr, (byte) (iblock.domain.readByte(addr) + cpu.pop()));
break;
}
case IlitB:
case IlitW:
case IlitX:
cpu.push(mop1.immed);
break;
case Iexit:
cpu.setPC(cpu.rpop());
return true;
case Iexiti:
cpu.setPC(cpu.rpop());
cpu.setST(cpu.rpop());
cpu.noIntCount+=2;
return true;
case Idup:
cpu.push(cpu.peek());
break;
case Iqdup: {
short val = cpu.peek();
if (val != 0)
cpu.push(val);
break;
}
case I0branchX:
case I0branchB:
case I0branchW:
{
short targ = (short) (fromPC + mop1.immed);
if (cpu.pop() == 0) {
cpu.setPC(targ);
return true;
}
break;
}
case IbranchX:
case IbranchB:
case IbranchW:
{
short targ = (short) (fromPC + mop1.immed);
cpu.setPC(targ);
return true;
}
case I0equ:
cpu.push((short) (cpu.pop() == 0 ? -1 : 0));
break;
case Iequ:
cpu.push((short) (cpu.pop() == cpu.pop() ? -1 : 0));
break;
case Idrop:
cpu.pop();
break;
case Iswap: {
short x = cpu.pop();
short y = cpu.pop();
cpu.push(x);
cpu.push(y);
break;
}
case Iover:
cpu.push(iblock.getStackEntry(1));
break;
case Irot: {
short x = cpu.pop();
short y = cpu.pop();
short z = cpu.pop();
cpu.push(y);
cpu.push(x);
cpu.push(z);
break;
}
case Iumul: {
int mul = (cpu.pop() & 0xffff) * (cpu.pop() & 0xffff);
cpu.push((short) (mul & 0xffff));
cpu.push((short) (mul >> 16));
break;
}
case Iudivmod: {
int div = cpu.pop() & 0xffff;
int num = cpu.popd();
if (div == 0) {
cpu.push((short) -1);
cpu.push((short) 0);
} else {
int quot = num / div;
int rem = num % div;
if (quot >= 65536) {
cpu.push((short) -1);
cpu.push((short) 0);
} else {
cpu.push((short) rem);
cpu.push((short) quot);
}
}
break;
}
case Iand:
cpu.push((short) (cpu.pop() & cpu.pop()));
break;
case Ior:
cpu.push((short) (cpu.pop() | cpu.pop()));
break;
case Ixor:
cpu.push((short) (cpu.pop() ^ cpu.pop()));
break;
case Inot:
cpu.push((short) (cpu.pop() != 0 ? 0 : -1));
break;
case Inand: {
<MASK>short v = cpu.pop();</MASK>
short m = cpu.pop();
cpu.push((short) (v & ~m));
break;
}
case Icall:
cpu.rpush(iblock.pc);
cpu.setPC(mop1.immed);
return true;
case Iexecute:
cpu.rpush(iblock.pc);
cpu.setPC(cpu.pop());
return true;
case Idovar:
{
short next = cpu.rpop();
cpu.push(iblock.pc);
cpu.setPC(next);
return true;
}
case ItoR:
cpu.rpush(cpu.pop());
break;
case IRfrom:
cpu.push(cpu.rpop());
break;
case Irdrop:
cpu.rpop();
break;
case IatR:
cpu.push(cpu.rpeek());
break;
case Ispidx:
cpu.push(iblock.getStackEntry(mop1.immed));
break;
case Irpidx:
cpu.push(iblock.getReturnStackEntry(mop1.immed));
break;
case Ilpidx:
cpu.push(iblock.getLocalStackEntry(mop1.immed));
break;
case Ilocal:
cpu.push((short) (iblock.lp - (mop1.immed + 1) * 2));
break;
case Iupidx:
cpu.push((short) (iblock.up + (mop1.val & 0xff)));
break;
case Iuser:
cpu.push((short) (iblock.up + cpu.pop()));
break;
case IloopUp: {
short next = (short) (iblock.getReturnStackEntry(0) + 1);
short lim = iblock.getReturnStackEntry(1);
cpu.rpop();
cpu.rpush(next);
cpu.push((short) ((lim != 0 ? next < lim : next >= 1) ? 0 : -1));
break;
}
case IuloopUp: {
int next = (iblock.getReturnStackEntry(0) + 1) & 0xffff;
short lim = iblock.getReturnStackEntry(1);
cpu.rpop();
cpu.rpush((short) next);
cpu.push((short) ((lim != 0 ? next < (lim & 0xffff)
: next >= (1 & 0xffff)) ? 0 : -1));
break;
}
case IplusLoopUp: {
short change = cpu.pop();
short cur = iblock.getReturnStackEntry(0);
int next = (cur + change);
short lim = iblock.getReturnStackEntry(1);
cpu.rpop();
cpu.rpush((short) next);
cpu.push((short) ((lim != 0 ? (change < 0 ? next > lim : next < lim)
: next >= change) ? 0 : -1));
break;
}
case IuplusLoopUp: {
short change = cpu.pop();
short cur = iblock.getReturnStackEntry(0);
int next = (cur & 0xffff) + change;
short lim = iblock.getReturnStackEntry(1);
cpu.rpop();
cpu.rpush((short) next);
cpu.push((short) ((lim != 0 ? (change < 0 ? next > (lim & 0xffff) : next < (lim & 0xffff))
: (next & 0xffff) >= (change & 0xffff)) ? 0 : -1));
break;
}
case Icfill: {
cpu.addCycles(4);
int step = cpu.pop();
byte ch = (byte) cpu.pop();
int len = cpu.pop() & 0xffff;
int addr = cpu.pop();
while (len-- > 0) {
memory.writeByte(addr, ch);
addr += step;
cpu.addCycles(2);
}
break;
}
case Ifill: {
cpu.addCycles(3);
int step = cpu.pop();
short w = cpu.pop();
int len = cpu.pop() & 0xffff;
int addr = cpu.pop();
while (len-- > 0) {
memory.writeWord(addr, w);
addr += step*2;
cpu.addCycles(2);
}
break;
}
case Icmove: {
doCmove();
break;
}
case Iccompare: {
doCcompare();
break;
}
case Ilalloc: {
cpu.push((short) iblock.sp);
cpu.push((short) (iblock.rp - mop1.immed * 2));
cpu.push((short) (mop1.immed * 2));
cpu.push((short) -1);
cpu.push((short) -1);
doCmove();
((CpuStateF99b)cpu.getState()).setSP((short) (iblock.sp + mop1.immed * 2));
((CpuStateF99b)cpu.getState()).setRP((short) (iblock.rp - mop1.immed * 2));
break;
}
case IcontextFrom:
switch (mop1.immed) {
case CTX_INT:
cpu.push((short) cpu.getStatus().getIntMask());
break;
case CTX_SP:
cpu.push(((CpuStateF99b)cpu.getState()).getSP());
break;
case CTX_SP0:
cpu.push(((CpuStateF99b)cpu.getState()).getBaseSP());
break;
case CTX_RP:
cpu.push(((CpuStateF99b)cpu.getState()).getRP());
break;
case CTX_RP0:
cpu.push(((CpuStateF99b)cpu.getState()).getBaseRP());
break;
case CTX_UP:
cpu.push(((CpuStateF99b)cpu.getState()).getUP());
break;
case CTX_LP:
cpu.push(((CpuStateF99b)cpu.getState()).getLP());
break;
case CTX_PC:
cpu.push(cpu.getPC());
break;
case CTX_SR:
cpu.push(cpu.getStatus().flatten());
break;
default:
cpu.push((short) -1);
break;
}
break;
case ItoContext:
switch (mop1.immed) {
case CTX_INT:
((StatusF99b) ((CpuStateF99b)cpu.getState()).getStatus()).setIntMask(cpu.pop());
break;
case CTX_SP:
((CpuStateF99b)cpu.getState()).setSP(cpu.pop());
break;
case CTX_SP0: {
short sp0 = cpu.pop();
((CpuStateF99b)cpu.getState()).setBaseSP(sp0);
((CpuStateF99b)cpu.getState()).setSP(sp0);
break;
}
case CTX_RP:
((CpuStateF99b)cpu.getState()).setRP(cpu.pop());
break;
case CTX_RP0: {
short rp0 = cpu.pop();
((CpuStateF99b)cpu.getState()).setBaseRP(rp0);
((CpuStateF99b)cpu.getState()).setRP(rp0);
break;
}
case CTX_UP:
((CpuStateF99b)cpu.getState()).setUP(cpu.pop());
break;
case CTX_LP:
((CpuStateF99b)cpu.getState()).setLP(cpu.pop());
break;
case CTX_PC:
((CpuStateF99b)cpu.getState()).setPC(cpu.pop());
return true;
case CTX_SR:
cpu.getState().setST(cpu.pop());
//((StatusF99b) ((CpuStateF99b)cpu.getState()).getStatus()).expand(cpu.pop());
break;
default:
cpu.pop();
break;
}
break;
case Isyscall:
switch (mop1.immed) {
case SYSCALL_DEBUG_OFF: {
int oldCount = machine.getExecutor().debugCount;
machine.getExecutor().debugCount++;
if ((oldCount == 0) != (machine.getExecutor().debugCount == 0))
Executor.settingDumpFullInstructions.setBoolean(false);
break;
}
case SYSCALL_DEBUG_ON: {
int oldCount = machine.getExecutor().debugCount;
machine.getExecutor().debugCount--;
if ((oldCount == 0) != (machine.getExecutor().debugCount == 0))
Executor.settingDumpFullInstructions.setBoolean(true);
break;
}
case SYSCALL_IDLE: {
machine.getCpu().setIdle(true);
break;
}
case SYSCALL_REGISTER_SYMBOL: {
int xt = cpu.pop();
int nfa = cpu.pop();
StringBuilder sb = new StringBuilder();
int len = iblock.domain.readByte(nfa++) & 0x1f;
while (len-- > 0) {
char ch = (char) iblock.domain.readByte(nfa++);
sb.append(ch);
}
iblock.domain.getEntryAt(xt).defineSymbol(xt, sb.toString());
break;
}
case SYSCALL_FIND: {
// ( caddr lfa -- caddr 0 | xt -1=immed | xt 1 )
int lfa = cpu.pop();
int caddr = cpu.pop();
boolean found = false;
int[] after = { 0 };
int count = 65536;
while (lfa != 0 && count-- > 0) {
cpu.addCycles(3);
short nfa = (short) (lfa + 2);
if (nameMatches(iblock.domain, caddr, nfa, after)) {
short xt = (short) after[0];
if ((xt & 1) != 0)
xt++;
cpu.push(xt);
cpu.push((short) ((iblock.domain.readByte(nfa) & 0x40) != 0 ? 1 : -1));
found = true;
break;
} else {
lfa = iblock.domain.readWord(lfa);
}
}
if (!found) {
cpu.push((short) caddr);
cpu.push((short) 0);
}
break;
}
case SYSCALL_GFIND: {
// ( caddr gDictEnd gDict -- caddr 0 | xt 1 | xt -1 )
short gromDictEnd = cpu.pop();
short gromDict = cpu.pop();
int caddr = cpu.pop();
boolean found = false;
int[] after = { 0 };
MemoryDomain grom = cpu.getMachine().getMemory().getDomain(MemoryDomain.NAME_GRAPHICS);
while (gromDict < gromDictEnd) {
cpu.addCycles(3);
if (nameMatches(grom, caddr, gromDict, after)) {
cpu.push(grom.readWord(after[0]));
cpu.push((short) (((grom.readByte(gromDict) & 0x40) != 0) ? 1 : -1));
found = true;
break;
} else {
gromDict = (short) (after[0] + 2);
}
}
if (!found) {
cpu.push((short) caddr);
cpu.push((short) 0);
}
break;
}
/*
case SYSCALL_INTERPRET: {
int dp = cpu.pop();
int len = cpu.pop();
int addr = cpu.pop();
StringBuilder text = new StringBuilder();
while (len-- > 0) {
text.append((char) iblock.domain.readByte(addr++));
}
TargetContext targCtx = new F99bTargetContext(65536);
HostContext hostCtx = new HostContext(targCtx);
ForthComp comp = new ForthComp(hostCtx, targCtx);
ByteArrayOutputStream diag = new ByteArrayOutputStream();
targCtx.setDP(dp);
targCtx.importMemory(iblock.domain);
comp.setLog(new PrintStream(diag));
try {
comp.parseString(text.toString());
} catch (AbortException e) {
e.printStackTrace();
try {
diag.write(e.toString().getBytes());
} catch (IOException e1) {
e1.printStackTrace();
}
}
comp.finish();
if (comp.getErrors() != 0) {
System.err.println("Errors during compilation");
}
try {
targCtx.exportMemory(iblock.domain);
} catch (AbortException e) {
e.printStackTrace();
try {
diag.write(e.toString().getBytes());
} catch (IOException e1) {
e1.printStackTrace();
}
}
cpu.push((short) targCtx.getDP());
break;
}
*/
}
break;
default:
unsupported(ins);
}
return false;
}" |
Inversion-Mutation | megadiff | "@Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
RSSReaderServiceLocator serviceLocator = (RSSReaderServiceLocator) getApplication();
Preferences preferences = serviceLocator.getPreferences();
rssPollServiceScheduler = serviceLocator.getRssPollServiceScheduler();
getPreferenceManager().setSharedPreferencesName(preferences.getPreferencesFileName());
addPreferencesFromResource(R.xml.settings);
rssUrlPreference = (EditTextPreference) getPreferenceScreen()
.findPreference(RSS_URL_PREFERENCE_KEY);
refreshIntervalPreference = (ListPreference) getPreferenceScreen()
.findPreference(REFRESH_INTERVAL_PREFERENCE_KEY);
rssUrlPreference
.setOnPreferenceChangeListener(new UrlPreferenceChangeListener());
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCreate" | "@Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
RSSReaderServiceLocator serviceLocator = (RSSReaderServiceLocator) getApplication();
Preferences preferences = serviceLocator.getPreferences();
rssPollServiceScheduler = serviceLocator.getRssPollServiceScheduler();
<MASK>addPreferencesFromResource(R.xml.settings);</MASK>
getPreferenceManager().setSharedPreferencesName(preferences.getPreferencesFileName());
rssUrlPreference = (EditTextPreference) getPreferenceScreen()
.findPreference(RSS_URL_PREFERENCE_KEY);
refreshIntervalPreference = (ListPreference) getPreferenceScreen()
.findPreference(REFRESH_INTERVAL_PREFERENCE_KEY);
rssUrlPreference
.setOnPreferenceChangeListener(new UrlPreferenceChangeListener());
}" |
Inversion-Mutation | megadiff | "public IPCDISession createDebuggerSession(IPLaunch launch, IBinaryObject exe, IProgressMonitor monitor) throws CoreException {
IPJob job = launch.getPJob();
/*
* Find number of processes in job. If the attribute does not exist, assume one process.
*/
IntegerAttribute numProcAttr = job.getAttribute(JobAttributes.getNumberOfProcessesAttributeDefinition());
if (numProcAttr != null) {
this.jobSize = numProcAttr.getValue();
} else {
this.jobSize = 1;
}
session = new Session(this, job, jobSize, launch, exe);
this.job = job;
initialize(job, jobSize, monitor);
return session;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createDebuggerSession" | "public IPCDISession createDebuggerSession(IPLaunch launch, IBinaryObject exe, IProgressMonitor monitor) throws CoreException {
IPJob job = launch.getPJob();
/*
* Find number of processes in job. If the attribute does not exist, assume one process.
*/
IntegerAttribute numProcAttr = job.getAttribute(JobAttributes.getNumberOfProcessesAttributeDefinition());
if (numProcAttr != null) {
this.jobSize = numProcAttr.getValue();
} else {
this.jobSize = 1;
}
session = new Session(this, job, jobSize, launch, exe);
<MASK>initialize(job, jobSize, monitor);</MASK>
this.job = job;
return session;
}" |
Inversion-Mutation | megadiff | "private void findUiChildren(JClassType ownerType)
throws UnableToCompleteException {
while (ownerType != null) {
JMethod[] methods = ownerType.getMethods();
for (JMethod method : methods) {
UiChild annotation = method.getAnnotation(UiChild.class);
if (annotation != null) {
String tag = annotation.tagname();
int limit = annotation.limit();
if (tag.equals("")) {
String name = method.getName();
if (name.startsWith("add")) {
tag = name.substring(3).toLowerCase();
} else {
logger.die(method.getName()
+ " must either specify a UiChild tagname or begin "
+ "with \"add\".");
}
}
JParameter[] parameters = method.getParameters();
if (parameters.length == 0) {
logger.die("%s must take at least one Object argument", method.getName());
}
JType type = parameters[0].getType();
if (type.isClassOrInterface() == null) {
logger.die("%s first parameter must be an object type, found %s",
method.getName(), type.getQualifiedSourceName());
}
uiChildren.put(tag, Pair.create(method, limit));
}
}
ownerType = ownerType.getSuperclass();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "findUiChildren" | "private void findUiChildren(JClassType ownerType)
throws UnableToCompleteException {
<MASK>JMethod[] methods = ownerType.getMethods();</MASK>
while (ownerType != null) {
for (JMethod method : methods) {
UiChild annotation = method.getAnnotation(UiChild.class);
if (annotation != null) {
String tag = annotation.tagname();
int limit = annotation.limit();
if (tag.equals("")) {
String name = method.getName();
if (name.startsWith("add")) {
tag = name.substring(3).toLowerCase();
} else {
logger.die(method.getName()
+ " must either specify a UiChild tagname or begin "
+ "with \"add\".");
}
}
JParameter[] parameters = method.getParameters();
if (parameters.length == 0) {
logger.die("%s must take at least one Object argument", method.getName());
}
JType type = parameters[0].getType();
if (type.isClassOrInterface() == null) {
logger.die("%s first parameter must be an object type, found %s",
method.getName(), type.getQualifiedSourceName());
}
uiChildren.put(tag, Pair.create(method, limit));
}
}
ownerType = ownerType.getSuperclass();
}
}" |
Inversion-Mutation | megadiff | "@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
throws IOException, ServletException {
final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
final String requestURI = httpServletRequest.getRequestURI();
LOGGER.log(Level.TRACE, "Request[URI={0}]", requestURI);
// If requests Latke Remote APIs, skips this filter
if (requestURI.startsWith(Latkes.getContextPath() + "/latke/remote")) {
chain.doFilter(request, response);
return;
}
final LatkeBeanManager beanManager = Lifecycle.getBeanManager();
final InitService initService = beanManager.getReference(InitService.class);
try {
if (initService.isInited()) {
chain.doFilter(request, response);
return;
}
if ("POST".equalsIgnoreCase(httpServletRequest.getMethod()) && (Latkes.getContextPath() + "/init").equals(requestURI)) {
// Do initailization
chain.doFilter(request, response);
return;
}
final PreferenceQueryService preferenceQueryService = beanManager.getReference(PreferenceQueryService.class);
LOGGER.debug("Try to get preference to confirm whether the preference exixts");
final JSONObject preference = preferenceQueryService.getPreference();
if (null == preference) {
LOGGER.log(Level.WARN, "B3log Solo has not been initialized, so redirects to /init");
final HTTPRequestContext context = new HTTPRequestContext();
context.setRequest((HttpServletRequest) request);
context.setResponse((HttpServletResponse) response);
request.setAttribute(Keys.HttpRequest.REQUEST_URI, Latkes.getContextPath() + "/init");
request.setAttribute(Keys.HttpRequest.REQUEST_METHOD, HTTPRequestMethod.GET.name());
HTTPRequestDispatcher.dispatch(context);
} else {
// XXX: Wrong state of SoloServletListener.isInited()
chain.doFilter(request, response);
}
} catch (final ServiceException e) {
((HttpServletResponse) response).sendError(HttpServletResponse.SC_NOT_FOUND);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doFilter" | "@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
throws IOException, ServletException {
final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
final String requestURI = httpServletRequest.getRequestURI();
LOGGER.log(Level.TRACE, "Request[URI={0}]", requestURI);
if (requestURI.startsWith(Latkes.getContextPath() + "/latke/remote")) {
<MASK>// If requests Latke Remote APIs, skips this filter</MASK>
chain.doFilter(request, response);
return;
}
final LatkeBeanManager beanManager = Lifecycle.getBeanManager();
final InitService initService = beanManager.getReference(InitService.class);
try {
if (initService.isInited()) {
chain.doFilter(request, response);
return;
}
if ("POST".equalsIgnoreCase(httpServletRequest.getMethod()) && (Latkes.getContextPath() + "/init").equals(requestURI)) {
// Do initailization
chain.doFilter(request, response);
return;
}
final PreferenceQueryService preferenceQueryService = beanManager.getReference(PreferenceQueryService.class);
LOGGER.debug("Try to get preference to confirm whether the preference exixts");
final JSONObject preference = preferenceQueryService.getPreference();
if (null == preference) {
LOGGER.log(Level.WARN, "B3log Solo has not been initialized, so redirects to /init");
final HTTPRequestContext context = new HTTPRequestContext();
context.setRequest((HttpServletRequest) request);
context.setResponse((HttpServletResponse) response);
request.setAttribute(Keys.HttpRequest.REQUEST_URI, Latkes.getContextPath() + "/init");
request.setAttribute(Keys.HttpRequest.REQUEST_METHOD, HTTPRequestMethod.GET.name());
HTTPRequestDispatcher.dispatch(context);
} else {
// XXX: Wrong state of SoloServletListener.isInited()
chain.doFilter(request, response);
}
} catch (final ServiceException e) {
((HttpServletResponse) response).sendError(HttpServletResponse.SC_NOT_FOUND);
}
}" |
Inversion-Mutation | megadiff | "public void addGZIPPostParam(String key, String value) {
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ArrayList<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add((new BasicNameValuePair(key, value)));
GZIPOutputStream gZIPOutputStream = new GZIPOutputStream(byteArrayOutputStream);
gZIPOutputStream.write(EntityUtils.toByteArray(new UrlEncodedFormEntity(postParams, HTTP.UTF_8)));
gZIPOutputStream.close();
byte[] byteDataForGZIP = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.close();
inputStreamEntity = new InputStreamEntity(new ByteArrayInputStream(byteDataForGZIP), byteDataForGZIP.length);
inputStreamEntity.setContentType("application/x-www-form-urlencoded");
inputStreamEntity.setContentEncoding("gzip");
} catch (Exception e) {}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addGZIPPostParam" | "public void addGZIPPostParam(String key, String value) {
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ArrayList<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add((new BasicNameValuePair(key, value)));
GZIPOutputStream gZIPOutputStream = new GZIPOutputStream(byteArrayOutputStream);
gZIPOutputStream.write(EntityUtils.toByteArray(new UrlEncodedFormEntity(postParams, HTTP.UTF_8)));
<MASK>byte[] byteDataForGZIP = byteArrayOutputStream.toByteArray();</MASK>
gZIPOutputStream.close();
byteArrayOutputStream.close();
inputStreamEntity = new InputStreamEntity(new ByteArrayInputStream(byteDataForGZIP), byteDataForGZIP.length);
inputStreamEntity.setContentType("application/x-www-form-urlencoded");
inputStreamEntity.setContentEncoding("gzip");
} catch (Exception e) {}
}" |
Inversion-Mutation | megadiff | "public void actionPerformed(final ActionEvent e)
{
final CreateNewRepositoryFolderDialog newFolderDialog =
new CreateNewRepositoryFolderDialog(RepositoryPublishDialog.this);
if (!newFolderDialog.performEdit())
{
return;
}
final FileObject treeNode = getSelectedView();
if (treeNode == null)
{
return;
}
if (!StringUtils.isEmpty(newFolderDialog.getName()))
{
final Component glassPane = SwingUtilities.getRootPane(RepositoryPublishDialog.this).getGlassPane();
try
{
glassPane.setVisible(true);
glassPane.setCursor(new Cursor(Cursor.WAIT_CURSOR));
final FileObject child = treeNode.resolveFile(newFolderDialog.getFolderName());
child.createFolder();
if (child instanceof WebSolutionFileObject)
{
final WebSolutionFileObject webSolutionFileObject = (WebSolutionFileObject) child;
webSolutionFileObject.setDescription(newFolderDialog.getDescription());
}
getTable().refresh();
}
catch (Exception e1)
{
UncaughtExceptionsModel.getInstance().addException(e1);
}
finally
{
glassPane.setVisible(false);
glassPane.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "actionPerformed" | "public void actionPerformed(final ActionEvent e)
{
final CreateNewRepositoryFolderDialog newFolderDialog =
new CreateNewRepositoryFolderDialog(RepositoryPublishDialog.this);
if (!newFolderDialog.performEdit())
{
return;
}
final FileObject treeNode = getSelectedView();
if (treeNode == null)
{
return;
}
if (!StringUtils.isEmpty(newFolderDialog.getName()))
{
final Component glassPane = SwingUtilities.getRootPane(RepositoryPublishDialog.this).getGlassPane();
try
{
glassPane.setVisible(true);
glassPane.setCursor(new Cursor(Cursor.WAIT_CURSOR));
final FileObject child = treeNode.resolveFile(newFolderDialog.getFolderName());
if (child instanceof WebSolutionFileObject)
{
final WebSolutionFileObject webSolutionFileObject = (WebSolutionFileObject) child;
webSolutionFileObject.setDescription(newFolderDialog.getDescription());
}
<MASK>child.createFolder();</MASK>
getTable().refresh();
}
catch (Exception e1)
{
UncaughtExceptionsModel.getInstance().addException(e1);
}
finally
{
glassPane.setVisible(false);
glassPane.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
}
}" |
Inversion-Mutation | megadiff | "public GoalBuilder(Player player, List<String> commands, QuestChapter chapter) {
ScriptBuilder scriptBuilder = DenizenAPI.getCurrentInstance().getScriptEngine().getScriptBuilder();
CommandExecuter executor = DenizenAPI.getCurrentInstance().getScriptEngine().getScriptExecuter();
String[] args = null;
QuestManager qm = (QuestManager) Bukkit.getPluginManager().getPlugin ("Quest Manager");
//
// For each goal, build the proper listener.
//
for (String goal : commands) {
//
// Create the new goal and then find the ID of the listener.
//
Goal newGoal = new Goal();
String listenerId = null;
args = scriptBuilder.buildArgs(player, null, goal);
for (String arg : args) {
if (aH.matchesValueArg("ID", arg, ArgumentType.String)) {
listenerId = arg;
break;
}
}
//
// Add the goal to the chapter, and also add it to the QuestManager's
// map of listener IDs to goals. That way the events fire as they
// should, in the correct order.
//
chapter.addGoal(newGoal);
qm.addGoal(listenerId, newGoal);
//
// Break the Goal into arguments for the LISTEN command scriptEntry and
// execute the script.
//
try {
executor.execute(new ScriptEntry("LISTEN", args, player));
} catch (ScriptEntryCreationException e) {
e.printStackTrace();
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "GoalBuilder" | "public GoalBuilder(Player player, List<String> commands, QuestChapter chapter) {
ScriptBuilder scriptBuilder = DenizenAPI.getCurrentInstance().getScriptEngine().getScriptBuilder();
CommandExecuter executor = DenizenAPI.getCurrentInstance().getScriptEngine().getScriptExecuter();
String[] args = null;
QuestManager qm = (QuestManager) Bukkit.getPluginManager().getPlugin ("Quest Manager");
//
// For each goal, build the proper listener.
//
for (String goal : commands) {
//
// Create the new goal and then find the ID of the listener.
//
Goal newGoal = new Goal();
String listenerId = null;
for (String arg : args) {
if (aH.matchesValueArg("ID", arg, ArgumentType.String)) {
listenerId = arg;
break;
}
}
//
// Add the goal to the chapter, and also add it to the QuestManager's
// map of listener IDs to goals. That way the events fire as they
// should, in the correct order.
//
chapter.addGoal(newGoal);
qm.addGoal(listenerId, newGoal);
//
// Break the Goal into arguments for the LISTEN command scriptEntry and
// execute the script.
//
try {
<MASK>args = scriptBuilder.buildArgs(player, null, goal);</MASK>
executor.execute(new ScriptEntry("LISTEN", args, player));
} catch (ScriptEntryCreationException e) {
e.printStackTrace();
}
}
}" |
Inversion-Mutation | megadiff | "@Override
public void startSession() {
lights = new LightTracer(map);
lights.setUncaughtExceptionHandler(LightTracerCrashHandler
.getInstance());
lights.start();
partSystem = new ParticleSystem();
mapDisplay = new MapDisplayManager();
musicBox = new MusicBox();
net = new NetComm();
player = new Player(login);
connect();
if (!running) {
SessionManager.getInstance().cancelStart();
return;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "startSession" | "@Override
public void startSession() {
lights = new LightTracer(map);
lights.setUncaughtExceptionHandler(LightTracerCrashHandler
.getInstance());
lights.start();
partSystem = new ParticleSystem();
mapDisplay = new MapDisplayManager();
musicBox = new MusicBox();
net = new NetComm();
connect();
if (!running) {
SessionManager.getInstance().cancelStart();
return;
}
<MASK>player = new Player(login);</MASK>
}" |
Inversion-Mutation | megadiff | "public Triangle getClosestTriangle(double[] coords, double[] projection, int group)
{
Node n = getNode(coords, workBoundary1);
assert n != null;
Triangle toReturn = null;
double aabbDistance = Double.POSITIVE_INFINITY;
double triangleDistance;
seen.clear();
if(n.triangles == null || n.triangles.length == 0)
{
aabbDistance = distanceAABB(coords, workBoundary1);
triangleDistance = Double.POSITIVE_INFINITY;
}
else
{
for(Triangle t:n.triangles)
{
if(group >= 0 && t.getGroupId() != group)
continue;
double d = MeshLiaison.TRIANGLE_DISTANCE.compute(coords, t, closeIndex);
if(d < aabbDistance)
{
aabbDistance = d;
toReturn = t;
if(projection != null)
MeshLiaison.TRIANGLE_DISTANCE.getProjection(projection);
}
seen.add(t);
//It seems to happen often so let's optimize
if(aabbDistance == 0)
break;
}
if(seen.isEmpty())
{
//all triangles are from an other group
aabbDistance = distanceAABB(coords, workBoundary1);
triangleDistance = Double.POSITIVE_INFINITY;
}
else
{
triangleDistance = aabbDistance;
aabbDistance = Math.sqrt(aabbDistance);
}
}
getNodes(createCenteredAABB(coords, 1.01*aabbDistance), null, false);
for(Node nn: closeNodes)
{
if(nn != n && nn.triangles != null)
{
for(Triangle t:nn.triangles)
{
if(group >= 0 && t.getGroupId() != group)
continue;
if(!seen.contains(t))
{
double d = MeshLiaison.TRIANGLE_DISTANCE.compute(coords, t, closeIndex);
if(d < triangleDistance)
{
triangleDistance = d;
toReturn = t;
if(projection != null)
MeshLiaison.TRIANGLE_DISTANCE.getProjection(projection);
}
}
}
}
}
closeNodes.clear();
return toReturn;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getClosestTriangle" | "public Triangle getClosestTriangle(double[] coords, double[] projection, int group)
{
Node n = getNode(coords, workBoundary1);
assert n != null;
Triangle toReturn = null;
double aabbDistance = Double.POSITIVE_INFINITY;
double triangleDistance;
seen.clear();
if(n.triangles == null || n.triangles.length == 0)
{
aabbDistance = distanceAABB(coords, workBoundary1);
triangleDistance = Double.POSITIVE_INFINITY;
}
else
{
for(Triangle t:n.triangles)
{
if(group >= 0 && t.getGroupId() != group)
continue;
double d = MeshLiaison.TRIANGLE_DISTANCE.compute(coords, t, closeIndex);
if(d < aabbDistance)
{
aabbDistance = d;
toReturn = t;
if(projection != null)
MeshLiaison.TRIANGLE_DISTANCE.getProjection(projection);
}
seen.add(t);
//It seems to happen often so let's optimize
if(aabbDistance == 0)
break;
}
if(seen.isEmpty())
{
//all triangles are from an other group
aabbDistance = distanceAABB(coords, workBoundary1);
triangleDistance = Double.POSITIVE_INFINITY;
}
else
{
<MASK>aabbDistance = Math.sqrt(aabbDistance);</MASK>
triangleDistance = aabbDistance;
}
}
getNodes(createCenteredAABB(coords, 1.01*aabbDistance), null, false);
for(Node nn: closeNodes)
{
if(nn != n && nn.triangles != null)
{
for(Triangle t:nn.triangles)
{
if(group >= 0 && t.getGroupId() != group)
continue;
if(!seen.contains(t))
{
double d = MeshLiaison.TRIANGLE_DISTANCE.compute(coords, t, closeIndex);
if(d < triangleDistance)
{
triangleDistance = d;
toReturn = t;
if(projection != null)
MeshLiaison.TRIANGLE_DISTANCE.getProjection(projection);
}
}
}
}
}
closeNodes.clear();
return toReturn;
}" |
Inversion-Mutation | megadiff | "private void registerUIExtensions() {
// remember: the first handler to be added will be the first one open when stuff changes
uiExtensions.add((UIExtension)new Configuration(this));
uiExtensions.add((UIExtension)new SequenceEdit(this));
uiExtensions.add((UIExtension)new QuerySequence(this));
uiExtensions.add((UIExtension)new CompleteOverlap(this));
uiExtensions.add((UIExtension)new SpeciesSummary(this));
uiExtensions.add((UIExtension)new PairwiseSummary(this));
uiExtensions.add((UIExtension)new AllPairwiseDistances(this));
uiExtensions.add((UIExtension)new BestMatch(this));
uiExtensions.add((UIExtension)new BlockAnalysis(this));
uiExtensions.add((UIExtension)new Cluster(this));
uiExtensions.add((UIExtension)new BarcodeGenerator(this));
uiExtensions.add((UIExtension)new Exporter(this));
// uiExtensions.add((UIExtension)new Randomizer(this));
uiExtensions.add((UIExtension)new AlignmentHelperPlugin(this));
uiExtensions.add((UIExtension)new Tester(this));
uiExtensions.add((UIExtension)new SystemUsage(this));
// uiExtensions.add((UIExtension)new CombineDatasets(this));
// uiExtensions.add((UIExtension)new GenerateSubSet(this));
// uiExtensions.add((UIExtension)new EditDataSet(this));
// Hidden extensions
new CDSExaminer(this);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "registerUIExtensions" | "private void registerUIExtensions() {
// remember: the first handler to be added will be the first one open when stuff changes
uiExtensions.add((UIExtension)new Configuration(this));
uiExtensions.add((UIExtension)new SequenceEdit(this));
uiExtensions.add((UIExtension)new QuerySequence(this));
uiExtensions.add((UIExtension)new SpeciesSummary(this));
uiExtensions.add((UIExtension)new PairwiseSummary(this));
uiExtensions.add((UIExtension)new AllPairwiseDistances(this));
uiExtensions.add((UIExtension)new BestMatch(this));
uiExtensions.add((UIExtension)new BlockAnalysis(this));
uiExtensions.add((UIExtension)new Cluster(this));
<MASK>uiExtensions.add((UIExtension)new CompleteOverlap(this));</MASK>
uiExtensions.add((UIExtension)new BarcodeGenerator(this));
uiExtensions.add((UIExtension)new Exporter(this));
// uiExtensions.add((UIExtension)new Randomizer(this));
uiExtensions.add((UIExtension)new AlignmentHelperPlugin(this));
uiExtensions.add((UIExtension)new Tester(this));
uiExtensions.add((UIExtension)new SystemUsage(this));
// uiExtensions.add((UIExtension)new CombineDatasets(this));
// uiExtensions.add((UIExtension)new GenerateSubSet(this));
// uiExtensions.add((UIExtension)new EditDataSet(this));
// Hidden extensions
new CDSExaminer(this);
}" |
Inversion-Mutation | megadiff | "public void receive(NodeEvent event) {
if (event.getSource() != parameter.getNode()) return;
if (event instanceof ValueChangedEvent) {
// Check if the value change triggered a change in expression status.
// This can happen if revert to default switches from value to expression
// or vice versa.
setEnabled(parameter.isEnabled());
ValueChangedEvent e = (ValueChangedEvent) event;
if (e.getParameter() != parameter) return;
setExpressionStatus();
} else if (event instanceof NodeAttributeChangedEvent) {
setEnabled(parameter.isEnabled());
}
//To change body of implemented methods use File | Settings | File Templates.
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "receive" | "public void receive(NodeEvent event) {
if (event.getSource() != parameter.getNode()) return;
if (event instanceof ValueChangedEvent) {
// Check if the value change triggered a change in expression status.
// This can happen if revert to default switches from value to expression
// or vice versa.
ValueChangedEvent e = (ValueChangedEvent) event;
if (e.getParameter() != parameter) return;
<MASK>setEnabled(parameter.isEnabled());</MASK>
setExpressionStatus();
} else if (event instanceof NodeAttributeChangedEvent) {
<MASK>setEnabled(parameter.isEnabled());</MASK>
}
//To change body of implemented methods use File | Settings | File Templates.
}" |
Inversion-Mutation | megadiff | "@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_FILTER, 0, res.getString(R.string.caches_filter)).setIcon(R.drawable.ic_menu_filter);
if (type != CacheListType.HISTORY) {
menu.add(0, MENU_SORT, 0, res.getString(R.string.caches_sort)).setIcon(R.drawable.ic_menu_sort_alphabetically);
}
menu.add(0, MENU_SWITCH_SELECT_MODE, 0, res.getString(R.string.caches_select_mode)).setIcon(R.drawable.ic_menu_agenda);
menu.add(0, MENU_INVERT_SELECTION, 0, res.getString(R.string.caches_select_invert)).setIcon(R.drawable.ic_menu_mark);
if (type == CacheListType.OFFLINE) {
final SubMenu subMenu = menu.addSubMenu(0, SUBMENU_MANAGE_OFFLINE, 0, res.getString(R.string.caches_manage)).setIcon(R.drawable.ic_menu_save);
subMenu.add(0, MENU_DROP_CACHES, 0, res.getString(R.string.caches_drop_all)); // delete saved caches
subMenu.add(0, MENU_DROP_CACHES_AND_LIST, 0, res.getString(R.string.caches_drop_all_and_list));
subMenu.add(0, MENU_REFRESH_STORED, 0, res.getString(R.string.cache_offline_refresh)); // download details for all caches
subMenu.add(0, MENU_MOVE_TO_LIST, 0, res.getString(R.string.cache_menu_move_list));
subMenu.add(0, MENU_DELETE_EVENTS, 0, res.getString(R.string.caches_delete_events));
subMenu.add(0, MENU_CLEAR_OFFLINE_LOGS, 0, res.getString(R.string.caches_clear_offlinelogs));
//TODO: add submenu/AlertDialog and use R.string.gpx_import_title
subMenu.add(0, MENU_IMPORT_GPX, 0, res.getString(R.string.gpx_import_title));
if (Settings.getWebDeviceCode() != null) {
subMenu.add(0, MENU_IMPORT_WEB, 0, res.getString(R.string.web_import_title));
}
subMenu.add(0, MENU_EXPORT, 0, res.getString(R.string.export)); // export caches
} else {
if (type == CacheListType.HISTORY) {
final SubMenu subMenu = menu.addSubMenu(0, SUBMENU_MANAGE_HISTORY, 0, res.getString(R.string.caches_manage)).setIcon(R.drawable.ic_menu_save);
subMenu.add(0, MENU_EXPORT, 0, res.getString(R.string.export)); // export caches
subMenu.add(0, MENU_REMOVE_FROM_HISTORY, 0, res.getString(R.string.cache_clear_history)); // remove from history
subMenu.add(0, MENU_CLEAR_OFFLINE_LOGS, 0, res.getString(R.string.caches_clear_offlinelogs));
menu.add(0, MENU_REFRESH_STORED, 0, res.getString(R.string.cache_offline_refresh)).setIcon(R.drawable.ic_menu_set_as);
} else {
menu.add(0, MENU_REFRESH_STORED, 0, res.getString(R.string.caches_store_offline)).setIcon(R.drawable.ic_menu_set_as); // download details for all caches
}
}
navigationMenu = CacheListAppFactory.addMenuItems(menu, this, res);
if (type == CacheListType.OFFLINE) {
final SubMenu subMenu = menu.addSubMenu(0, SUBMENU_MANAGE_LISTS, 0, res.getString(R.string.list_menu)).setIcon(R.drawable.ic_menu_more);
subMenu.add(0, MENU_CREATE_LIST, 0, res.getString(R.string.list_menu_create));
subMenu.add(0, MENU_DROP_LIST, 0, res.getString(R.string.list_menu_drop));
subMenu.add(0, MENU_RENAME_LIST, 0, res.getString(R.string.list_menu_rename));
subMenu.add(0, MENU_SWITCH_LIST, 0, res.getString(R.string.list_menu_change));
}
return true;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCreateOptionsMenu" | "@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_FILTER, 0, res.getString(R.string.caches_filter)).setIcon(R.drawable.ic_menu_filter);
if (type != CacheListType.HISTORY) {
menu.add(0, MENU_SORT, 0, res.getString(R.string.caches_sort)).setIcon(R.drawable.ic_menu_sort_alphabetically);
}
menu.add(0, MENU_SWITCH_SELECT_MODE, 0, res.getString(R.string.caches_select_mode)).setIcon(R.drawable.ic_menu_agenda);
menu.add(0, MENU_INVERT_SELECTION, 0, res.getString(R.string.caches_select_invert)).setIcon(R.drawable.ic_menu_mark);
if (type == CacheListType.OFFLINE) {
final SubMenu subMenu = menu.addSubMenu(0, SUBMENU_MANAGE_OFFLINE, 0, res.getString(R.string.caches_manage)).setIcon(R.drawable.ic_menu_save);
subMenu.add(0, MENU_DROP_CACHES, 0, res.getString(R.string.caches_drop_all)); // delete saved caches
subMenu.add(0, MENU_DROP_CACHES_AND_LIST, 0, res.getString(R.string.caches_drop_all_and_list));
subMenu.add(0, MENU_REFRESH_STORED, 0, res.getString(R.string.cache_offline_refresh)); // download details for all caches
subMenu.add(0, MENU_MOVE_TO_LIST, 0, res.getString(R.string.cache_menu_move_list));
subMenu.add(0, MENU_DELETE_EVENTS, 0, res.getString(R.string.caches_delete_events));
subMenu.add(0, MENU_CLEAR_OFFLINE_LOGS, 0, res.getString(R.string.caches_clear_offlinelogs));
//TODO: add submenu/AlertDialog and use R.string.gpx_import_title
subMenu.add(0, MENU_IMPORT_GPX, 0, res.getString(R.string.gpx_import_title));
if (Settings.getWebDeviceCode() != null) {
subMenu.add(0, MENU_IMPORT_WEB, 0, res.getString(R.string.web_import_title));
}
subMenu.add(0, MENU_EXPORT, 0, res.getString(R.string.export)); // export caches
} else {
if (type == CacheListType.HISTORY) {
final SubMenu subMenu = menu.addSubMenu(0, SUBMENU_MANAGE_HISTORY, 0, res.getString(R.string.caches_manage)).setIcon(R.drawable.ic_menu_save);
<MASK>subMenu.add(0, MENU_REMOVE_FROM_HISTORY, 0, res.getString(R.string.cache_clear_history)); // remove from history</MASK>
subMenu.add(0, MENU_EXPORT, 0, res.getString(R.string.export)); // export caches
subMenu.add(0, MENU_CLEAR_OFFLINE_LOGS, 0, res.getString(R.string.caches_clear_offlinelogs));
menu.add(0, MENU_REFRESH_STORED, 0, res.getString(R.string.cache_offline_refresh)).setIcon(R.drawable.ic_menu_set_as);
} else {
menu.add(0, MENU_REFRESH_STORED, 0, res.getString(R.string.caches_store_offline)).setIcon(R.drawable.ic_menu_set_as); // download details for all caches
}
}
navigationMenu = CacheListAppFactory.addMenuItems(menu, this, res);
if (type == CacheListType.OFFLINE) {
final SubMenu subMenu = menu.addSubMenu(0, SUBMENU_MANAGE_LISTS, 0, res.getString(R.string.list_menu)).setIcon(R.drawable.ic_menu_more);
subMenu.add(0, MENU_CREATE_LIST, 0, res.getString(R.string.list_menu_create));
subMenu.add(0, MENU_DROP_LIST, 0, res.getString(R.string.list_menu_drop));
subMenu.add(0, MENU_RENAME_LIST, 0, res.getString(R.string.list_menu_rename));
subMenu.add(0, MENU_SWITCH_LIST, 0, res.getString(R.string.list_menu_change));
}
return true;
}" |
Inversion-Mutation | megadiff | "@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
getSherlockActivity().getSupportActionBar().setHomeButtonEnabled(true);
inflater.inflate(R.menu.catalog_menu, menu);
this.searchMenuItem = menu.findItem(R.id.search);
if (searchMenuItem != null) {
final SearchView searchView = (SearchView) searchMenuItem.getActionView();
if (searchView != null) {
searchView.setSubmitButtonEnabled(true);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
performSearch(query);
return true;
}
@Override
public boolean onQueryTextChange(String query) {
return false;
}
} );
} else {
searchMenuItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
dialogFactory.buildSearchDialog(R.string.search_books, R.string.enter_query, CatalogFragment.this);
return false;
}
});
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCreateOptionsMenu" | "@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
getSherlockActivity().getSupportActionBar().setHomeButtonEnabled(true);
inflater.inflate(R.menu.catalog_menu, menu);
this.searchMenuItem = menu.findItem(R.id.search);
if (searchMenuItem != null) {
final SearchView searchView = (SearchView) searchMenuItem.getActionView();
<MASK>searchView.setSubmitButtonEnabled(true);</MASK>
if (searchView != null) {
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
performSearch(query);
return true;
}
@Override
public boolean onQueryTextChange(String query) {
return false;
}
} );
} else {
searchMenuItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
dialogFactory.buildSearchDialog(R.string.search_books, R.string.enter_query, CatalogFragment.this);
return false;
}
});
}
}
}" |
Inversion-Mutation | megadiff | "public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpReq = (HttpServletRequest) request;
if(log.isDebugEnabled()){
log.debug("Enter SessionManagerFilter form " + httpReq.getRequestURI());
}
if (request instanceof javax.servlet.http.HttpServletRequest) {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse)response;
String uid = null;
if(SessionCreateConfig.doLogin()){
uid = getUidFromSession(httpReq);
if(redirectPaths.contains(httpReq.getServletPath())){
httpResponse.addCookie(new Cookie("redirect_path", httpReq.getServletPath()));
}
if( uid == null && !isExcludePath(httpReq.getServletPath())){
if (httpRequest.getHeader("MSDPortal-Ajax") != null) {
if(log.isInfoEnabled())
log.info("session timeout has occured. logoff automatically.");
httpResponse.setHeader(HttpStatusCode.HEADER_NAME,
HttpStatusCode.MSD_SESSION_TIMEOUT);
httpResponse.sendError(500);
return;
}
}
}else{
uid = getUidFromHeader(httpReq);
if (uid == null)
uid = getUidFromSession(httpReq);
if (uid != null) {
addUidToSession(uid, request);
}
}
if( uid == null ) {
Cookie[] cookies = httpReq.getCookies();
if( cookies != null ) {
for( Cookie cookie : cookies ) {
if( cookie.getName().equals("portal-credential")) {
int keepPeriod = 7;
try {
keepPeriod = Integer.parseInt( PropertiesDAO.newInstance()
.findProperty("loginStateKeepPeriod").getValue());
} catch( Exception ex ) {
log.warn("",ex );
}
if( keepPeriod <= 0 ) {
Cookie credentialCookie = new Cookie("portal-credential","");
credentialCookie.setMaxAge( 0 );
credentialCookie.setPath("/");
httpResponse.addCookie( credentialCookie );
log.info("clear auto login credential ["+credentialCookie.getValue()+"]");
} else {
try {
uid = tryAutoLogin( cookie );
httpReq.getSession().setAttribute("Uid",uid );
log.info("auto login success.");
} catch( Exception ex ) {
log.info("auto login failed.",ex );
}
}
}
}
}
}
if( uid == null && SessionCreateConfig.doLogin() && !isExcludePath(httpReq.getServletPath())) {
String requestUri = httpReq.getRequestURI();
String loginUrl = requestUri.lastIndexOf("/admin/") > 0 ?
requestUri.substring( 0,requestUri.lastIndexOf("/"))+"/../login.jsp" : "login.jsp";
httpResponse.sendRedirect(loginUrl);
return;
}
if(log.isInfoEnabled())log.info("### Access from user " + uid + " to " + httpReq.getRequestURL() );
// fix #42
// setUserInfo2Cookie(httpReq, (HttpServletResponse)response, uid);
HttpSession session = httpRequest.getSession();
Subject loginUser = (Subject)session.getAttribute(LOGINUSER_SUBJECT_ATTR_NAME);
if(loginUser == null || ( isChangeLoginUser(uid, loginUser) && !(session instanceof PreviewImpersonationFilter.PreviewHttpSession) )){
if( !SessionCreateConfig.getInstance().hasUidHeader() && uid != null ) {
AuthenticationService service= (AuthenticationService)SpringUtil.getBean("authenticationService");
try {
loginUser = service.getSubject(uid);
} catch (Exception e) {
log.error("",e);
}
}
if( loginUser == null ) {
loginUser = new Subject();
loginUser.getPrincipals().add(new ISPrincipal(ISPrincipal.UID_PRINCIPAL, uid));
}
setLoginUserName(httpRequest, loginUser);
for(Map.Entry entry : SessionCreateConfig.getInstance().getRoleHeaderMap().entrySet()){
String headerName = (String)entry.getKey();
String roleType = (String)entry.getValue();
Enumeration headerValues = httpRequest.getHeaders(headerName);
while(headerValues.hasMoreElements()){
String headerValue = (String)headerValues.nextElement();
try {
Set principals = loginUser.getPrincipals();
principals.add( new ISPrincipal(roleType, headerValue));
// loginUser.getPrincipals().add( roleType.getConstructor(paramTypes).newInstance(initArgs) );
if(log.isInfoEnabled())log.info("Set principal to login subject: " + roleType + "=" + headerValue);
} catch (IllegalArgumentException e) {
log.error("",e);
} catch (SecurityException e) {
log.error("",e);
}
}
}
session.setAttribute(LOGINUSER_SUBJECT_ATTR_NAME, loginUser);
}
SecurityController.registerContextSubject(loginUser);
}
chain.doFilter(request, response);
if(log.isDebugEnabled()){
log.debug("Exit SessionManagerFilter form " + httpReq.getRequestURI());
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doFilter" | "public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpReq = (HttpServletRequest) request;
if(log.isDebugEnabled()){
log.debug("Enter SessionManagerFilter form " + httpReq.getRequestURI());
}
if (request instanceof javax.servlet.http.HttpServletRequest) {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse)response;
String uid = null;
if(SessionCreateConfig.doLogin()){
uid = getUidFromSession(httpReq);
if(redirectPaths.contains(httpReq.getServletPath())){
httpResponse.addCookie(new Cookie("redirect_path", httpReq.getServletPath()));
}
if( uid == null && !isExcludePath(httpReq.getServletPath())){
if (httpRequest.getHeader("MSDPortal-Ajax") != null) {
if(log.isInfoEnabled())
log.info("session timeout has occured. logoff automatically.");
httpResponse.setHeader(HttpStatusCode.HEADER_NAME,
HttpStatusCode.MSD_SESSION_TIMEOUT);
httpResponse.sendError(500);
return;
}
}
}else{
uid = getUidFromHeader(httpReq);
if (uid == null)
uid = getUidFromSession(httpReq);
if (uid != null) {
addUidToSession(uid, request);
}
}
if( uid == null ) {
Cookie[] cookies = httpReq.getCookies();
if( cookies != null ) {
for( Cookie cookie : cookies ) {
if( cookie.getName().equals("portal-credential")) {
int keepPeriod = 7;
try {
keepPeriod = Integer.parseInt( PropertiesDAO.newInstance()
.findProperty("loginStateKeepPeriod").getValue());
} catch( Exception ex ) {
log.warn("",ex );
}
if( keepPeriod <= 0 ) {
Cookie credentialCookie = new Cookie("portal-credential","");
credentialCookie.setMaxAge( 0 );
credentialCookie.setPath("/");
httpResponse.addCookie( credentialCookie );
log.info("clear auto login credential ["+credentialCookie.getValue()+"]");
} else {
try {
uid = tryAutoLogin( cookie );
httpReq.getSession().setAttribute("Uid",uid );
log.info("auto login success.");
} catch( Exception ex ) {
log.info("auto login failed.",ex );
}
}
}
}
}
}
if( uid == null && SessionCreateConfig.doLogin() && !isExcludePath(httpReq.getServletPath())) {
String requestUri = httpReq.getRequestURI();
String loginUrl = requestUri.lastIndexOf("/admin/") > 0 ?
requestUri.substring( 0,requestUri.lastIndexOf("/"))+"/../login.jsp" : "login.jsp";
httpResponse.sendRedirect(loginUrl);
return;
}
if(log.isInfoEnabled())log.info("### Access from user " + uid + " to " + httpReq.getRequestURL() );
// fix #42
// setUserInfo2Cookie(httpReq, (HttpServletResponse)response, uid);
HttpSession session = httpRequest.getSession();
Subject loginUser = (Subject)session.getAttribute(LOGINUSER_SUBJECT_ATTR_NAME);
if(loginUser == null || ( isChangeLoginUser(uid, loginUser) && !(session instanceof PreviewImpersonationFilter.PreviewHttpSession) )){
if( !SessionCreateConfig.getInstance().hasUidHeader() && uid != null ) {
AuthenticationService service= (AuthenticationService)SpringUtil.getBean("authenticationService");
try {
loginUser = service.getSubject(uid);
} catch (Exception e) {
log.error("",e);
}
}
if( loginUser == null ) {
loginUser = new Subject();
loginUser.getPrincipals().add(new ISPrincipal(ISPrincipal.UID_PRINCIPAL, uid));
}
setLoginUserName(httpRequest, loginUser);
for(Map.Entry entry : SessionCreateConfig.getInstance().getRoleHeaderMap().entrySet()){
String headerName = (String)entry.getKey();
String roleType = (String)entry.getValue();
Enumeration headerValues = httpRequest.getHeaders(headerName);
while(headerValues.hasMoreElements()){
String headerValue = (String)headerValues.nextElement();
try {
Set principals = loginUser.getPrincipals();
principals.add( new ISPrincipal(roleType, headerValue));
// loginUser.getPrincipals().add( roleType.getConstructor(paramTypes).newInstance(initArgs) );
if(log.isInfoEnabled())log.info("Set principal to login subject: " + roleType + "=" + headerValue);
} catch (IllegalArgumentException e) {
log.error("",e);
} catch (SecurityException e) {
log.error("",e);
}
}
<MASK>session.setAttribute(LOGINUSER_SUBJECT_ATTR_NAME, loginUser);</MASK>
}
}
SecurityController.registerContextSubject(loginUser);
}
chain.doFilter(request, response);
if(log.isDebugEnabled()){
log.debug("Exit SessionManagerFilter form " + httpReq.getRequestURI());
}
}" |
Inversion-Mutation | megadiff | "private void runFinalizer() {
frameworkVersion = JOptionPane.showInputDialog("Merci de preciser le numéro de version du framework");
if (frameworkVersion == null || frameworkVersion.trim().isEmpty()) {
JOptionPane.showMessageDialog(getMainPanel(),
"Le numéro de version du framework ne peut etre null ou vide",
"Impossible de finaliser la Stabilisation",
JOptionPane.ERROR_MESSAGE);
}
else {
CommandPlayer player = new CommandPlayer();
player.add(new CleanUpDirectoryCommand("C:\\Dev\\platform\\tools\\maven\\local\\maven2\\net\\codjo\\pom"));
player.add(new LockRepoCommand());
player.add(new CleanInhouseSnapshot());
player.add(new MavenCommand(ArtifactType.SUPER_POM, "", "deploy"));
player.add(new MavenCommand(ArtifactType.SUPER_POM, "", "deploy", ArtifactStep.REMOTE_CODJO));
// Rapatriement des librairies postées sur repo.codjo.net avec maven et nexus
player.add(new SetNexusProxySettingsCommand(proxy.getProxyUserName(),
proxy.getProxyPassword(),
properties));
String codjoPomAllDepsDirectory = "pom-alldeps";
String codjoPomAllDepsPath = ArtifactType.LIB.toArtifactPath(codjoPomAllDepsDirectory);
String temporaryLocalRepository = ArtifactType.LIB.toArtifactPath("repo");
player.add(new CleanUpDirectoryCommand(codjoPomAllDepsPath));
player.add(new CopyPomCommand(ArtifactType.SUPER_POM, "", codjoPomAllDepsPath));
player.add(new PrepareAPomToLoadSuperPomDependenciesCommand(codjoPomAllDepsPath, frameworkVersion));
player.add(new CleanUpDirectoryCommand(temporaryLocalRepository));
player.add(new IdeaCommand(ArtifactType.LIB, codjoPomAllDepsDirectory, temporaryLocalRepository));
player.add(new RebuildNexusPomMetaDataCommand(properties));
player.add(new SetNexusProxySettingsCommand(null, null, properties));
player.add(new MavenCommand(ArtifactType.SUPER_POM, "", "codjo:find-release-version"));
player.add(new MavenCommand(ArtifactType.SUPER_POM, "", "codjo:update-confluence-after-release"));
StepInvoker invoker = new StepInvoker("Finalisation", player);
invoker.start();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "runFinalizer" | "private void runFinalizer() {
frameworkVersion = JOptionPane.showInputDialog("Merci de preciser le numéro de version du framework");
if (frameworkVersion == null || frameworkVersion.trim().isEmpty()) {
JOptionPane.showMessageDialog(getMainPanel(),
"Le numéro de version du framework ne peut etre null ou vide",
"Impossible de finaliser la Stabilisation",
JOptionPane.ERROR_MESSAGE);
}
else {
CommandPlayer player = new CommandPlayer();
player.add(new CleanUpDirectoryCommand("C:\\Dev\\platform\\tools\\maven\\local\\maven2\\net\\codjo\\pom"));
player.add(new LockRepoCommand());
player.add(new CleanInhouseSnapshot());
player.add(new MavenCommand(ArtifactType.SUPER_POM, "", "deploy"));
player.add(new MavenCommand(ArtifactType.SUPER_POM, "", "deploy", ArtifactStep.REMOTE_CODJO));
// Rapatriement des librairies postées sur repo.codjo.net avec maven et nexus
player.add(new SetNexusProxySettingsCommand(proxy.getProxyUserName(),
proxy.getProxyPassword(),
properties));
String codjoPomAllDepsDirectory = "pom-alldeps";
String codjoPomAllDepsPath = ArtifactType.LIB.toArtifactPath(codjoPomAllDepsDirectory);
String temporaryLocalRepository = ArtifactType.LIB.toArtifactPath("repo");
player.add(new CleanUpDirectoryCommand(codjoPomAllDepsPath));
player.add(new CopyPomCommand(ArtifactType.SUPER_POM, "", codjoPomAllDepsPath));
player.add(new PrepareAPomToLoadSuperPomDependenciesCommand(codjoPomAllDepsPath, frameworkVersion));
player.add(new CleanUpDirectoryCommand(temporaryLocalRepository));
player.add(new IdeaCommand(ArtifactType.LIB, codjoPomAllDepsDirectory, temporaryLocalRepository));
<MASK>player.add(new MavenCommand(ArtifactType.SUPER_POM, "", "codjo:find-release-version"));</MASK>
player.add(new RebuildNexusPomMetaDataCommand(properties));
player.add(new SetNexusProxySettingsCommand(null, null, properties));
player.add(new MavenCommand(ArtifactType.SUPER_POM, "", "codjo:update-confluence-after-release"));
StepInvoker invoker = new StepInvoker("Finalisation", player);
invoker.start();
}
}" |
Inversion-Mutation | megadiff | "@Override
public void onEnable() {
initEvents();
initPermissions();
getConfig().options().copyDefaults();
log.info("Enabled.");
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onEnable" | "@Override
public void onEnable() {
initEvents();
initPermissions();
<MASK>log.info("Enabled.");</MASK>
getConfig().options().copyDefaults();
}" |
Inversion-Mutation | megadiff | "private HaeinsaRowTransaction checkOrRecoverLock(HaeinsaTransaction tx,
byte[] row, HaeinsaTableTransaction tableState,
@Nullable HaeinsaRowTransaction rowState) throws IOException {
if (rowState != null && rowState.getCurrent() != null) {
// return rowState itself if rowState already exist and contains TRowLock
return rowState;
}
int recoverCount = 0;
while (true) {
if (recoverCount > HaeinsaConstants.RECOVER_MAX_RETRY_COUNT) {
throw new ConflictException("recover retry count is exceeded.");
}
TRowLock currentRowLock = getRowLock(row);
if (checkAndIsShouldRecover(currentRowLock)) {
recover(tx, row);
recoverCount++;
} else {
rowState = tableState.createOrGetRowState(row);
rowState.setCurrent(currentRowLock);
break;
}
}
return rowState;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "checkOrRecoverLock" | "private HaeinsaRowTransaction checkOrRecoverLock(HaeinsaTransaction tx,
byte[] row, HaeinsaTableTransaction tableState,
@Nullable HaeinsaRowTransaction rowState) throws IOException {
if (rowState != null && rowState.getCurrent() != null) {
// return rowState itself if rowState already exist and contains TRowLock
return rowState;
}
int recoverCount = 0;
while (true) {
if (recoverCount > HaeinsaConstants.RECOVER_MAX_RETRY_COUNT) {
throw new ConflictException("recover retry count is exceeded.");
}
TRowLock currentRowLock = getRowLock(row);
if (checkAndIsShouldRecover(currentRowLock)) {
recover(tx, row);
} else {
rowState = tableState.createOrGetRowState(row);
rowState.setCurrent(currentRowLock);
break;
}
<MASK>recoverCount++;</MASK>
}
return rowState;
}" |
Inversion-Mutation | megadiff | "@Override
public boolean commit() {
// Commit any in-process edits
if (getMacroTable().isEditing()) {
getMacroTable().getCellEditor().stopCellEditing();
}
if (getSpeechTable().isEditing()) {
getSpeechTable().getCellEditor().stopCellEditing();
}
if (getPropertyTable().isEditing()) {
getPropertyTable().getCellEditor().stopCellEditing();
}
// Commit the changes to the token properties
if (!super.commit()) {
return false;
}
// SIZE
token.setSnapToScale(getSizeCombo().getSelectedIndex() != 0);
if (getSizeCombo().getSelectedIndex() > 0) {
Grid grid = MapTool.getFrame().getCurrentZoneRenderer().getZone().getGrid();
token.setFootprint(grid, (TokenFootprint) getSizeCombo().getSelectedItem());
}
// Other
token.setPropertyType((String)getPropertyTypeCombo().getSelectedItem());
token.setSightType((String)getSightTypeCombo().getSelectedItem());
// Get the states
Component[] stateComponents = getStatesPanel().getComponents();
Component barPanel = null;
for (int j = 0; j < stateComponents.length; j++) {
if ("bar".equals(stateComponents[j].getName())) {
barPanel = stateComponents[j];
continue;
}
Component[] components = ((Container)stateComponents[j]).getComponents();
for (int i = 0; i < components.length; i++) {
JCheckBox cb = (JCheckBox) components[i];
String state = cb.getText();
token.setState(state, cb.isSelected() ? Boolean.TRUE : Boolean.FALSE);
}
} // endfor
// BARS
if (barPanel != null) {
Component[] bars = ((Container)barPanel).getComponents();
for (int i = 0; i < bars.length; i += 2) {
JCheckBox cb = (JCheckBox)((Container)bars[i]).getComponent(1);
JSlider bar = (JSlider) bars[i + 1];
BigDecimal value = cb.isSelected() ? null : new BigDecimal(bar.getValue()).divide(new BigDecimal(100));
token.setState(bar.getName(), value);
bar.setValue((int)(TokenBarFunction.getBigDecimalValue(token.getState(bar.getName())).doubleValue() * 100));
}
}
// Ownership
token.clearAllOwners();
for (int i = 0; i < getOwnerList().getModel().getSize(); i++) {
DefaultSelectable selectable = (DefaultSelectable) getOwnerList().getModel().getElementAt(i);
if (selectable.isSelected()) {
token.addOwner((String) selectable.getObject());
}
}
// SHAPE
token.setShape((Token.TokenShape)getShapeCombo().getSelectedItem());
// Macros
token.replaceMacroList(((MacroTableModel)getMacroTable().getModel()).getMacroList());
token.setSpeechMap(((KeyValueTableModel)getSpeechTable().getModel()).getMap());
// Properties
((TokenPropertyTableModel)getPropertyTable().getModel()).applyTo(token);
// Charsheet
token.setCharsheetImage(getCharSheetPanel().getImageId());
if (token.getCharsheetImage() != null) {
// Make sure the server has the image
if (!MapTool.getCampaign().containsAsset(token.getCharsheetImage())) {
MapTool.serverCommand().putAsset(AssetManager.getAsset(token.getCharsheetImage()));
}
}
// IMAGE
if (!token.getImageAssetId().equals(getTokenIconPanel().getImageId())) {
MapToolUtil.uploadAsset(AssetManager.getAsset(getTokenIconPanel().getImageId()));
token.setImageAsset(null, getTokenIconPanel().getImageId()); // Default image for now
}
// PORTRAIT
token.setPortraitImage(getPortraitPanel().getImageId());
if (token.getPortraitImage() != null) {
// Make sure the server has the image
if (!MapTool.getCampaign().containsAsset(token.getPortraitImage())) {
MapTool.serverCommand().putAsset(AssetManager.getAsset(token.getPortraitImage()));
}
}
// LAYOUT
token.setSizeScale(getTokenLayoutPanel().getSizeScale());
token.setAnchor(getTokenLayoutPanel().getAnchorX(), getTokenLayoutPanel().getAnchorY());
// OTHER
tokenSaved = true;
// // Character Sheet
// Map<String, Object> properties = controller.getData();
// for (String prop : token.getPropertyNames())
// token.setProperty(prop, properties.get(prop));
// Update UI
MapTool.getFrame().updateTokenTree();
MapTool.getFrame().resetTokenPanels();
return true;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "commit" | "@Override
public boolean commit() {
// Commit any in-process edits
if (getMacroTable().isEditing()) {
getMacroTable().getCellEditor().stopCellEditing();
}
if (getSpeechTable().isEditing()) {
getSpeechTable().getCellEditor().stopCellEditing();
}
if (getPropertyTable().isEditing()) {
getPropertyTable().getCellEditor().stopCellEditing();
}
// Commit the changes to the token properties
if (!super.commit()) {
return false;
}
// SIZE
token.setSnapToScale(getSizeCombo().getSelectedIndex() != 0);
if (getSizeCombo().getSelectedIndex() > 0) {
Grid grid = MapTool.getFrame().getCurrentZoneRenderer().getZone().getGrid();
token.setFootprint(grid, (TokenFootprint) getSizeCombo().getSelectedItem());
}
// Other
token.setPropertyType((String)getPropertyTypeCombo().getSelectedItem());
token.setSightType((String)getSightTypeCombo().getSelectedItem());
// Get the states
Component[] stateComponents = getStatesPanel().getComponents();
Component barPanel = null;
for (int j = 0; j < stateComponents.length; j++) {
if ("bar".equals(stateComponents[j].getName())) {
barPanel = stateComponents[j];
continue;
}
Component[] components = ((Container)stateComponents[j]).getComponents();
for (int i = 0; i < components.length; i++) {
JCheckBox cb = (JCheckBox) components[i];
String state = cb.getText();
token.setState(state, cb.isSelected() ? Boolean.TRUE : Boolean.FALSE);
}
} // endfor
// BARS
if (barPanel != null) {
Component[] bars = ((Container)barPanel).getComponents();
for (int i = 0; i < bars.length; i += 2) {
JCheckBox cb = (JCheckBox)((Container)bars[i]).getComponent(1);
JSlider bar = (JSlider) bars[i + 1];
BigDecimal value = cb.isSelected() ? null : new BigDecimal(bar.getValue()).divide(new BigDecimal(100));
token.setState(bar.getName(), value);
bar.setValue((int)(TokenBarFunction.getBigDecimalValue(token.getState(bar.getName())).doubleValue() * 100));
}
}
// Ownership
token.clearAllOwners();
for (int i = 0; i < getOwnerList().getModel().getSize(); i++) {
DefaultSelectable selectable = (DefaultSelectable) getOwnerList().getModel().getElementAt(i);
if (selectable.isSelected()) {
token.addOwner((String) selectable.getObject());
}
}
// SHAPE
token.setShape((Token.TokenShape)getShapeCombo().getSelectedItem());
// Macros
token.replaceMacroList(((MacroTableModel)getMacroTable().getModel()).getMacroList());
token.setSpeechMap(((KeyValueTableModel)getSpeechTable().getModel()).getMap());
// Properties
((TokenPropertyTableModel)getPropertyTable().getModel()).applyTo(token);
// Charsheet
token.setCharsheetImage(getCharSheetPanel().getImageId());
if (token.getCharsheetImage() != null) {
// Make sure the server has the image
if (!MapTool.getCampaign().containsAsset(token.getCharsheetImage())) {
MapTool.serverCommand().putAsset(AssetManager.getAsset(token.getCharsheetImage()));
}
}
// IMAGE
if (!token.getImageAssetId().equals(getTokenIconPanel().getImageId())) {
<MASK>token.setImageAsset(null, getTokenIconPanel().getImageId()); // Default image for now</MASK>
MapToolUtil.uploadAsset(AssetManager.getAsset(getTokenIconPanel().getImageId()));
}
// PORTRAIT
token.setPortraitImage(getPortraitPanel().getImageId());
if (token.getPortraitImage() != null) {
// Make sure the server has the image
if (!MapTool.getCampaign().containsAsset(token.getPortraitImage())) {
MapTool.serverCommand().putAsset(AssetManager.getAsset(token.getPortraitImage()));
}
}
// LAYOUT
token.setSizeScale(getTokenLayoutPanel().getSizeScale());
token.setAnchor(getTokenLayoutPanel().getAnchorX(), getTokenLayoutPanel().getAnchorY());
// OTHER
tokenSaved = true;
// // Character Sheet
// Map<String, Object> properties = controller.getData();
// for (String prop : token.getPropertyNames())
// token.setProperty(prop, properties.get(prop));
// Update UI
MapTool.getFrame().updateTokenTree();
MapTool.getFrame().resetTokenPanels();
return true;
}" |
Inversion-Mutation | megadiff | "public static void battle(int choice) {
//Declare variables for the moves of the player and monster
boolean monsterHeal = false;
boolean monsterDefend = false;
boolean monsterAttack = false;
boolean playerDefend = false;
boolean playerAttack = false;
boolean playerHeal = false;
//Get the move the monster will make
int monsterAi = monster.getAiChoice();
//Check what input the player has given
if(choice == 1) {
//Set the booleans according to the input for attack
playerAttack = true;
playerDefend = false;
playerHeal = false;
} else if(choice == 2) {
//Set the booleans according to the input for defend
playerDefend = true;
playerAttack = false;
playerHeal = false;
} else if(choice == 3) {
//Set the booleans according to the input for heal
playerAttack = false;
playerDefend = false;
playerHeal = true;
} else {
//Set the player not to do anything if the input is wrong
playerAttack = false;
playerDefend = false;
playerHeal = false;
}
//Link the monster AI choice to a move
if(monsterAi == 1) {
//Set the booleans according to the AI for attack
monsterAttack = true;
monsterDefend = false;
monsterHeal = false;
} else if(monsterAi == 2) {
//Set the booleans according to the AI for defend
monsterAttack = true;
monsterDefend = false;
monsterHeal = false;
} else if(monsterAi == 3) {
//Set the booleans according to the AI for heal
monsterAttack = false;
monsterDefend = false;
monsterHeal = true;
}
String pFirst = "";
String mFirst = "";
String mAttack = "";
String pAttack = "";
String pLife = "";
String mLife = "";
//Player moves
if(playerHeal) {
//Heal the player by 10 life
player.Heal(10);
//Show a message saying the player was healed
pFirst = player.name + " healed 10 life! \n";
} else if(playerDefend) {
//Set the monster not to attack (do damage)
monsterAttack = false;
//Shows a message that the player has defended
pFirst = player.name + " defended and has got 0 damage from " + monster.name + "\n";
} else if(!playerAttack && !playerDefend && !playerHeal) {
//Show a message that the player did not do anything
pFirst = player.name + " did nothing. \n";
}
//Monster moves
if(monsterHeal) {
//heal the monster by 10 life
monster.Heal(10);
//Show a message that the monster was healed
mFirst = (monster.name + " healed 10 life! \n");
} else if(monsterDefend) {
//Set the player not to attack (do damage)
playerAttack = false;
//Show a message that the monster has defended
mFirst = monster.name + " defended and has got 0 damage from " + player.name + "\n";
}
//Attack moves
if(playerAttack) {
//Lower the monsters life by the players power
monster.life -= player.strength;
}
if(monsterAttack) {
//Lower the players life by the monsters power
player.life -= monster.strength;
}
if(playerAttack) {
//Show a message that the player has attacked
pAttack = player.name + " hit " + monster.name + " for " + player.strength + " damage. \n";
}
if(monsterAttack) {
//Show a message that the monster has attacked
mAttack = monster.name + " hit " + player.name + " for " + monster.strength + " damage. \n";
}
//Show the current life for the player and the monster
pLife = player.name + " does now have " + player.life + " life left. \n";
mLife = monster.name + " does now have " + monster.life + " life left. \n";
//Print the moves message
MainGame.display.disp(pFirst + mFirst + pAttack + mAttack + pLife + mLife);
//Check if the player is still alive
if(player.life <= 0) {
//If the player has no life left, show him that he has lost
MainGame.display.disp("Too bad! You lost!" + "\n" + "Play again?");
//Show the option to play again
MainGame.display.Enable(MainGame.display.playAgain);
}
//Check if the monster is still alive
if(monster.life <= 0) {
player.xp += monster.giveXp;
MainGame.display.disp("You beat " + monster.name + "! \n" + "You got " + monster.giveXp + " XP!" + "\n" + "You now have " + player.xp + " XP!");
MainGame.display.Enable(MainGame.display.continueStage);
}
MainGame.display.Enable(MainGame.display.continueFight);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "battle" | "public static void battle(int choice) {
//Declare variables for the moves of the player and monster
boolean monsterHeal = false;
boolean monsterDefend = false;
boolean monsterAttack = false;
boolean playerDefend = false;
boolean playerAttack = false;
boolean playerHeal = false;
//Get the move the monster will make
int monsterAi = monster.getAiChoice();
//Check what input the player has given
if(choice == 1) {
//Set the booleans according to the input for attack
playerAttack = true;
playerDefend = false;
playerHeal = false;
} else if(choice == 2) {
//Set the booleans according to the input for defend
playerDefend = true;
playerAttack = false;
playerHeal = false;
} else if(choice == 3) {
//Set the booleans according to the input for heal
playerAttack = false;
playerDefend = false;
playerHeal = true;
} else {
//Set the player not to do anything if the input is wrong
playerAttack = false;
playerDefend = false;
playerHeal = false;
}
//Link the monster AI choice to a move
if(monsterAi == 1) {
//Set the booleans according to the AI for attack
monsterAttack = true;
monsterDefend = false;
monsterHeal = false;
} else if(monsterAi == 2) {
//Set the booleans according to the AI for defend
monsterAttack = true;
monsterDefend = false;
monsterHeal = false;
} else if(monsterAi == 3) {
//Set the booleans according to the AI for heal
monsterAttack = false;
monsterDefend = false;
monsterHeal = true;
}
String pFirst = "";
String mFirst = "";
String mAttack = "";
String pAttack = "";
String pLife = "";
String mLife = "";
//Player moves
if(playerHeal) {
//Heal the player by 10 life
player.Heal(10);
//Show a message saying the player was healed
pFirst = player.name + " healed 10 life! \n";
} else if(playerDefend) {
//Set the monster not to attack (do damage)
monsterAttack = false;
//Shows a message that the player has defended
pFirst = player.name + " defended and has got 0 damage from " + monster.name + "\n";
} else if(!playerAttack && !playerDefend && !playerHeal) {
//Show a message that the player did not do anything
pFirst = player.name + " did nothing. \n";
}
//Monster moves
if(monsterHeal) {
//heal the monster by 10 life
monster.Heal(10);
//Show a message that the monster was healed
mFirst = (monster.name + " healed 10 life! \n");
} else if(monsterDefend) {
//Set the player not to attack (do damage)
playerAttack = false;
//Show a message that the monster has defended
mFirst = monster.name + " defended and has got 0 damage from " + player.name + "\n";
}
//Attack moves
if(playerAttack) {
//Lower the monsters life by the players power
monster.life -= player.strength;
}
if(monsterAttack) {
//Lower the players life by the monsters power
player.life -= monster.strength;
}
if(playerAttack) {
//Show a message that the player has attacked
pAttack = player.name + " hit " + monster.name + " for " + player.strength + " damage. \n";
}
if(monsterAttack) {
//Show a message that the monster has attacked
mAttack = monster.name + " hit " + player.name + " for " + monster.strength + " damage. \n";
}
//Show the current life for the player and the monster
pLife = player.name + " does now have " + player.life + " life left. \n";
mLife = monster.name + " does now have " + monster.life + " life left. \n";
//Print the moves message
MainGame.display.disp(pFirst + mFirst + pAttack + mAttack + pLife + mLife);
//Check if the player is still alive
if(player.life <= 0) {
//If the player has no life left, show him that he has lost
MainGame.display.disp("Too bad! You lost!" + "\n" + "Play again?");
//Show the option to play again
MainGame.display.Enable(MainGame.display.playAgain);
}
//Check if the monster is still alive
if(monster.life <= 0) {
<MASK>MainGame.display.disp("You beat " + monster.name + "! \n" + "You got " + monster.giveXp + " XP!" + "\n" + "You now have " + player.xp + " XP!");</MASK>
player.xp += monster.giveXp;
MainGame.display.Enable(MainGame.display.continueStage);
}
MainGame.display.Enable(MainGame.display.continueFight);
}" |
Inversion-Mutation | megadiff | "@Override
public void load() {
MinecraftForge.versionDetect("IronChest", 1, 3, 0);
proxy = ServerClientProxy.getProxy();
File cfgFile = new File(proxy.getMinecraftDir(), "config/IronChest.cfg");
Configuration cfg = new Configuration(cfgFile);
try {
cfg.load();
ironChestBlock = new BlockIronChest(Integer.parseInt(cfg.getOrCreateBlockIdProperty("ironChests", 181).value));
IronChestType.initGUIs(cfg);
} catch (Exception e) {
ModLoader.getLogger().severe("IronChest was unable to load it's configuration successfully");
e.printStackTrace(System.err);
throw new RuntimeException(e);
} finally {
cfg.save();
}
ModLoader.RegisterBlock(ironChestBlock, ItemIronChest.class);
MinecraftForge.registerOreHandler(new IOreHandler() {
@Override
public void registerOre(String oreClass, ItemStack ore) {
if ("ingotCopper".equals(oreClass)) {
IronChestType.generateRecipesForType(ironChestBlock, Block.chest, IronChestType.COPPER, ore);
}
if ("ingotSilver".equals(oreClass)) {
IronChestType.generateRecipesForType(ironChestBlock, ironChestBlock, IronChestType.SILVER, ore);
}
if ("ingotRefinedIron".equals(oreClass)) {
IronChestType.generateRecipesForType(ironChestBlock, Block.chest, IronChestType.IRON, ore);
}
}
});
proxy.registerTranslations();
proxy.registerTileEntities();
IronChestType.generateTieredRecipies(ironChestBlock);
proxy.registerRenderInformation();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "load" | "@Override
public void load() {
MinecraftForge.versionDetect("IronChest", 1, 3, 0);
proxy = ServerClientProxy.getProxy();
File cfgFile = new File(proxy.getMinecraftDir(), "config/IronChest.cfg");
Configuration cfg = new Configuration(cfgFile);
try {
cfg.load();
ironChestBlock = new BlockIronChest(Integer.parseInt(cfg.getOrCreateBlockIdProperty("ironChests", 181).value));
IronChestType.initGUIs(cfg);
} catch (Exception e) {
ModLoader.getLogger().severe("IronChest was unable to load it's configuration successfully");
e.printStackTrace(System.err);
throw new RuntimeException(e);
} finally {
cfg.save();
}
MinecraftForge.registerOreHandler(new IOreHandler() {
@Override
public void registerOre(String oreClass, ItemStack ore) {
if ("ingotCopper".equals(oreClass)) {
IronChestType.generateRecipesForType(ironChestBlock, Block.chest, IronChestType.COPPER, ore);
}
if ("ingotSilver".equals(oreClass)) {
IronChestType.generateRecipesForType(ironChestBlock, ironChestBlock, IronChestType.SILVER, ore);
}
if ("ingotRefinedIron".equals(oreClass)) {
IronChestType.generateRecipesForType(ironChestBlock, Block.chest, IronChestType.IRON, ore);
}
}
});
<MASK>ModLoader.RegisterBlock(ironChestBlock, ItemIronChest.class);</MASK>
proxy.registerTranslations();
proxy.registerTileEntities();
IronChestType.generateTieredRecipies(ironChestBlock);
proxy.registerRenderInformation();
}" |
Inversion-Mutation | megadiff | "@Override
public void onClick(View v) {
// TODO Auto-generated method stub
database db = new database(tallyclass.this);
if(!(db.getvalue(v.getTag().toString()).equals("0")))
{
db.subtract(v.getTag().toString());
count_reg-=1;
reading.setText(count_reg+"");
}
else
Toast.makeText(getBaseContext(), "Values can't be negative!", Toast.LENGTH_SHORT).show();
db.close();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onClick" | "@Override
public void onClick(View v) {
// TODO Auto-generated method stub
database db = new database(tallyclass.this);
if(!(db.getvalue(v.getTag().toString()).equals("0")))
{
db.subtract(v.getTag().toString());
<MASK>db.close();</MASK>
count_reg-=1;
reading.setText(count_reg+"");
}
else
Toast.makeText(getBaseContext(), "Values can't be negative!", Toast.LENGTH_SHORT).show();
}" |
Inversion-Mutation | megadiff | "public Object createPersistentCollection(Map<String, Serializable> proxyInformations,
Object underlyingCollection)
{
// Get current opened session
//
Session session = _session.get();
if (session == null)
{
throw new NullPointerException("Cannot load : no session opened !");
}
// Get added and deleted items
//
Object addedItems = removeNewItems(proxyInformations, underlyingCollection);
Collection<?> deletedItems = addDeletedItems(proxyInformations, underlyingCollection);
// Create collection for the class name
//
String className = (String) proxyInformations.get(CLASS_NAME);
PersistentCollection collection = null;
if (PersistentBag.class.getName().equals(className))
{
// Persistent bag creation
//
if (underlyingCollection == null)
{
collection = new PersistentBag((SessionImpl) session);
}
else
{
collection = new PersistentBag((SessionImpl) session,
(Collection<?>) underlyingCollection);
}
}
else if (PersistentList.class.getName().equals(className))
{
// Persistent list creation
//
if (underlyingCollection == null)
{
collection = new PersistentList((SessionImpl) session);
}
else
{
collection = new PersistentList((SessionImpl) session,
(List<?>) underlyingCollection);
}
}
else if (PersistentSet.class.getName().equals(className))
{
// Persistent set creation
//
if (underlyingCollection == null)
{
collection = new PersistentSet((SessionImpl) session);
}
else
{
collection = new PersistentSet((SessionImpl) session,
(Set<?>) underlyingCollection);
}
}
else if (PersistentMap.class.getName().equals(className))
{
// Persistent map creation
//
if (underlyingCollection == null)
{
collection = new PersistentMap((SessionImpl) session);
}
else
{
collection = new PersistentMap((SessionImpl) session,
(Map<?, ?>) underlyingCollection);
}
}
else
{
throw new RuntimeException("Unknown persistent collection class name : " + className);
}
// Fill with serialized parameters
//
String role = (String) proxyInformations.get(ROLE);
Serializable snapshot = null;
if (underlyingCollection != null)
{
// Create snpashot
//
CollectionPersister collectionPersister = _sessionFactory.getCollectionPersister(role);
snapshot = collection.getSnapshot(collectionPersister);
}
collection.setSnapshot(proxyInformations.get(KEY),
role, snapshot);
// Remove deleted items
//
if (deletedItems != null)
{
if (collection instanceof Collection)
{
for (Object key : deletedItems)
{
((Collection)collection).remove(key);
}
}
else if (collection instanceof Map)
{
for (Object key : deletedItems)
{
((Map)collection).remove(key);
}
}
}
// Insert added items
//
if (addedItems != null)
{
if (collection instanceof List)
{
// Keep insert order
//
List<Object> collectionList = (List<Object>) collection;
for (NewItem key : (List<NewItem>)addedItems)
{
collectionList.add(key.index, key.object);
}
}
else if (collection instanceof Collection)
{
// No order
//
for (NewItem key : (List<NewItem>)addedItems)
{
((Collection)collection).add(key.object);
}
}
else if (collection instanceof Map)
{
((Map)collection).putAll((Map)addedItems);
}
}
return collection;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createPersistentCollection" | "public Object createPersistentCollection(Map<String, Serializable> proxyInformations,
Object underlyingCollection)
{
// Get current opened session
//
Session session = _session.get();
if (session == null)
{
throw new NullPointerException("Cannot load : no session opened !");
}
// Get added and deleted items
//
<MASK>Collection<?> deletedItems = addDeletedItems(proxyInformations, underlyingCollection);</MASK>
Object addedItems = removeNewItems(proxyInformations, underlyingCollection);
// Create collection for the class name
//
String className = (String) proxyInformations.get(CLASS_NAME);
PersistentCollection collection = null;
if (PersistentBag.class.getName().equals(className))
{
// Persistent bag creation
//
if (underlyingCollection == null)
{
collection = new PersistentBag((SessionImpl) session);
}
else
{
collection = new PersistentBag((SessionImpl) session,
(Collection<?>) underlyingCollection);
}
}
else if (PersistentList.class.getName().equals(className))
{
// Persistent list creation
//
if (underlyingCollection == null)
{
collection = new PersistentList((SessionImpl) session);
}
else
{
collection = new PersistentList((SessionImpl) session,
(List<?>) underlyingCollection);
}
}
else if (PersistentSet.class.getName().equals(className))
{
// Persistent set creation
//
if (underlyingCollection == null)
{
collection = new PersistentSet((SessionImpl) session);
}
else
{
collection = new PersistentSet((SessionImpl) session,
(Set<?>) underlyingCollection);
}
}
else if (PersistentMap.class.getName().equals(className))
{
// Persistent map creation
//
if (underlyingCollection == null)
{
collection = new PersistentMap((SessionImpl) session);
}
else
{
collection = new PersistentMap((SessionImpl) session,
(Map<?, ?>) underlyingCollection);
}
}
else
{
throw new RuntimeException("Unknown persistent collection class name : " + className);
}
// Fill with serialized parameters
//
String role = (String) proxyInformations.get(ROLE);
Serializable snapshot = null;
if (underlyingCollection != null)
{
// Create snpashot
//
CollectionPersister collectionPersister = _sessionFactory.getCollectionPersister(role);
snapshot = collection.getSnapshot(collectionPersister);
}
collection.setSnapshot(proxyInformations.get(KEY),
role, snapshot);
// Remove deleted items
//
if (deletedItems != null)
{
if (collection instanceof Collection)
{
for (Object key : deletedItems)
{
((Collection)collection).remove(key);
}
}
else if (collection instanceof Map)
{
for (Object key : deletedItems)
{
((Map)collection).remove(key);
}
}
}
// Insert added items
//
if (addedItems != null)
{
if (collection instanceof List)
{
// Keep insert order
//
List<Object> collectionList = (List<Object>) collection;
for (NewItem key : (List<NewItem>)addedItems)
{
collectionList.add(key.index, key.object);
}
}
else if (collection instanceof Collection)
{
// No order
//
for (NewItem key : (List<NewItem>)addedItems)
{
((Collection)collection).add(key.object);
}
}
else if (collection instanceof Map)
{
((Map)collection).putAll((Map)addedItems);
}
}
return collection;
}" |
Inversion-Mutation | megadiff | "public static void removeDuplicateLink(SingleLink head){
if(head == null || head.next == null)
return;
SingleLink node = head;
HashMap<String,Integer> map = new HashMap<String, Integer>();
while (node != null && node.next != null){
SingleLink nextNode = node.next;
if(map.containsKey(nextNode.value)){
//remove node
node.next = nextNode.next;
nextNode.next = null;
}
else{
map.put(nextNode.value,1);
}
node = node.next;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "removeDuplicateLink" | "public static void removeDuplicateLink(SingleLink head){
if(head == null || head.next == null)
return;
SingleLink node = head;
HashMap<String,Integer> map = new HashMap<String, Integer>();
while (node != null && node.next != null){
SingleLink nextNode = node.next;
if(map.containsKey(nextNode.value)){
//remove node
node.next = nextNode.next;
nextNode.next = null;
}
else{
map.put(nextNode.value,1);
<MASK>node = node.next;</MASK>
}
}
}" |
Inversion-Mutation | megadiff | "public void setDataSource(Context context, Uri uri)
throws IllegalArgumentException, SecurityException {
if (uri == null) {
throw new IllegalArgumentException();
}
String scheme = uri.getScheme();
if(scheme == null || scheme.equals("file")) {
setDataSource(uri.getPath());
return;
}
Cursor cursor = null;
try {
String[] proj = { MediaStore.MediaColumns.DATA };
cursor = context.getContentResolver().query(uri, proj, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
if (cursor.moveToFirst()) {
setDataSource(cursor.getString(column_index));
}
cursor.close();
return;
}
} catch (SecurityException ex) {
}
setDataSource(uri.toString());
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setDataSource" | "public void setDataSource(Context context, Uri uri)
throws IllegalArgumentException, SecurityException {
if (uri == null) {
throw new IllegalArgumentException();
}
String scheme = uri.getScheme();
if(scheme == null || scheme.equals("file")) {
setDataSource(uri.getPath());
<MASK>return;</MASK>
}
Cursor cursor = null;
try {
String[] proj = { MediaStore.MediaColumns.DATA };
cursor = context.getContentResolver().query(uri, proj, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
if (cursor.moveToFirst()) {
setDataSource(cursor.getString(column_index));
}
cursor.close();
}
<MASK>return;</MASK>
} catch (SecurityException ex) {
}
setDataSource(uri.toString());
}" |
Inversion-Mutation | megadiff | "protected String serializedArgs() {
final StringBuilder result = new StringBuilder();
result.append(JLSConstants.OPEN_BRACKET);
for (int i = 0; i < args.size(); i++) {
if (i != 0) {
result.append(JLSConstants.ARGS_SEPARATOR);
}
result.append(args.get(i).getJLSCode());
}
result.append(JLSConstants.CLOSE_BRACKET);
return result.toString();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "serializedArgs" | "protected String serializedArgs() {
final StringBuilder result = new StringBuilder();
result.append(JLSConstants.OPEN_BRACKET);
for (int i = 0; i < args.size(); i++) {
<MASK>result.append(args.get(i).getJLSCode());</MASK>
if (i != 0) {
result.append(JLSConstants.ARGS_SEPARATOR);
}
}
result.append(JLSConstants.CLOSE_BRACKET);
return result.toString();
}" |
Inversion-Mutation | megadiff | "public void stopCapture(){
if(mVideoPublish != null){
pauseCapture();
// Because the CameraDevice object is not a shared resource, it's very
// important to release it when it may not be used anymore
if(mVideoPublish.mCamera != null){
mVideoPublish.mCamera.release();
mVideoPublish.mCamera = null;
}
if(mVideoPublish.isCapturing){
mVideoPublish.endNativeEncoder();
mVideoPublish.stopPublisher();
}
mVideoPublish = ((BigBlueButton) getContext().getApplicationContext()).deleteVideoPublish();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "stopCapture" | "public void stopCapture(){
if(mVideoPublish != null){
pauseCapture();
// Because the CameraDevice object is not a shared resource, it's very
// important to release it when it may not be used anymore
if(mVideoPublish.mCamera != null){
mVideoPublish.mCamera.release();
mVideoPublish.mCamera = null;
}
if(mVideoPublish.isCapturing){
mVideoPublish.stopPublisher();
<MASK>mVideoPublish.endNativeEncoder();</MASK>
}
mVideoPublish = ((BigBlueButton) getContext().getApplicationContext()).deleteVideoPublish();
}
}" |
Inversion-Mutation | megadiff | "public void createControl(final Composite parent) {
Composite comp = new Composite(parent, SWT.NONE);
pageControl = comp;
GridLayout layout = new GridLayout();
layout.numColumns = 3;
comp.setLayout(layout);
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
comp.setLayoutData(gd);
// Label for "Provider:"
Label providerLabel = new Label(comp, SWT.LEFT);
providerLabel.setText(Messages.NewRemoteSyncProjectWizardPage_syncProvider);
// combo for providers
fProviderCombo = new Combo(comp, SWT.DROP_DOWN | SWT.READ_ONLY);
// set layout to grab horizontal space
fProviderCombo.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false));
gd = new GridData();
gd.horizontalSpan = 2;
fProviderCombo.setLayoutData(gd);
fProviderCombo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
handleProviderSelected();
}
});
fProviderArea = new Group(comp, SWT.SHADOW_ETCHED_IN);
fProviderStack = new StackLayout();
fProviderArea.setLayout(fProviderStack);
GridData providerAreaData = new GridData(SWT.FILL, SWT.FILL, true, true);
providerAreaData.horizontalSpan = 3;
fProviderArea.setLayoutData(providerAreaData);
// populate the combo with a list of providers
ISynchronizeParticipantDescriptor[] providers = SynchronizeParticipantRegistry.getDescriptors();
fProviderCombo.add(Messages.NewRemoteSyncProjectWizardPage_selectSyncProvider, 0);
for (int k = 0; k < providers.length; k++) {
fProviderCombo.add(providers[k].getName(), k + 1);
fComboIndexToDescriptorMap.put(k, providers[k]);
addProviderControl(providers[k]);
}
if (providers.length == 1) {
fProviderCombo.select(1);
handleProviderSelected();
} else {
fProviderCombo.select(0);
fSelectedProvider = null;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createControl" | "public void createControl(final Composite parent) {
Composite comp = new Composite(parent, SWT.NONE);
pageControl = comp;
GridLayout layout = new GridLayout();
layout.numColumns = 3;
comp.setLayout(layout);
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
comp.setLayoutData(gd);
// Label for "Provider:"
Label providerLabel = new Label(comp, SWT.LEFT);
providerLabel.setText(Messages.NewRemoteSyncProjectWizardPage_syncProvider);
// combo for providers
fProviderCombo = new Combo(comp, SWT.DROP_DOWN | SWT.READ_ONLY);
// set layout to grab horizontal space
fProviderCombo.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false));
gd = new GridData();
gd.horizontalSpan = 2;
fProviderCombo.setLayoutData(gd);
fProviderCombo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
handleProviderSelected();
}
});
fProviderArea = new Group(comp, SWT.SHADOW_ETCHED_IN);
fProviderStack = new StackLayout();
fProviderArea.setLayout(fProviderStack);
GridData providerAreaData = new GridData(SWT.FILL, SWT.FILL, true, true);
providerAreaData.horizontalSpan = 3;
fProviderArea.setLayoutData(providerAreaData);
// populate the combo with a list of providers
ISynchronizeParticipantDescriptor[] providers = SynchronizeParticipantRegistry.getDescriptors();
fProviderCombo.add(Messages.NewRemoteSyncProjectWizardPage_selectSyncProvider, 0);
for (int k = 0; k < providers.length; k++) {
fProviderCombo.add(providers[k].getName(), k + 1);
fComboIndexToDescriptorMap.put(k, providers[k]);
addProviderControl(providers[k]);
}
if (providers.length == 1) {
fProviderCombo.select(1);
handleProviderSelected();
} else {
fProviderCombo.select(0);
}
<MASK>fSelectedProvider = null;</MASK>
}" |
Inversion-Mutation | megadiff | "private String createUpdateMessage(Commit _commit) {
StringBuilder buf = new StringBuilder();
buf.append("Code changed in "+_commit.project+"\n");
buf.append(MessageFormat.format("User: {0}\n",_commit.userName));
buf.append("Path:\n");
if (_commit instanceof CVSCommit) {
CVSCommit commit = (CVSCommit) _commit;
boolean hasFisheye = FISHEYE_CVS_PROJECT.contains(commit.project);
for (CVSChange cc : commit.getCodeChanges()) {
buf.append(MessageFormat.format(" {0} ({1})\n",cc.fileName,cc.revision));
if(!hasFisheye)
buf.append(" "+cc.url+"\n");
}
if(hasFisheye) {
try {
buf.append(MessageFormat.format(
" http://fisheye5.cenqua.com/changelog/{0}/?cs={1}:{2}:{3}\n",
commit.project,
commit.branch==null?"MAIN":commit.branch,
commit.userName,
DATE_FORMAT.format(commit.getCodeChanges().get(0).determineTimstamp())));
} catch (IOException e) {
e.printStackTrace();
buf.append("Failed to compute FishEye link "+e+"\n");
} catch (InterruptedException e) {
e.printStackTrace();
buf.append("Failed to compute FishEye link "+e+"\n");
}
}
} else {
SubversionCommit commit = (SubversionCommit) _commit;
boolean hasFisheye = FISHEYE_SUBVERSION_PROJECT.contains(commit.project);
for (CodeChange cc : commit.getCodeChanges()) {
buf.append(MessageFormat.format(" {0}\n",cc.fileName));
if(!hasFisheye)
buf.append(" "+cc.url+"\n");
}
if(hasFisheye) {
buf.append(MessageFormat.format(
"http://fisheye4.cenqua.com/changelog/{0}/?cs={1}",
commit.project,
commit.revision));
}
}
buf.append("\n");
buf.append("Log:\n");
buf.append(_commit.log);
return buf.toString();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createUpdateMessage" | "private String createUpdateMessage(Commit _commit) {
StringBuilder buf = new StringBuilder();
buf.append("Code changed in "+_commit.project+"\n");
buf.append(MessageFormat.format("User: {0}\n",_commit.userName));
buf.append("Path:\n");
if (_commit instanceof CVSCommit) {
CVSCommit commit = (CVSCommit) _commit;
boolean hasFisheye = FISHEYE_CVS_PROJECT.contains(commit.project);
for (CVSChange cc : commit.getCodeChanges()) {
buf.append(MessageFormat.format(" {0} ({1})\n",cc.fileName,cc.revision));
if(!hasFisheye)
buf.append(" "+cc.url+"\n");
}
if(hasFisheye) {
try {
buf.append(MessageFormat.format(
" http://fisheye5.cenqua.com/changelog/{0}/?cs={1}:{2}:{3}\n",
commit.project,
<MASK>commit.userName,</MASK>
commit.branch==null?"MAIN":commit.branch,
DATE_FORMAT.format(commit.getCodeChanges().get(0).determineTimstamp())));
} catch (IOException e) {
e.printStackTrace();
buf.append("Failed to compute FishEye link "+e+"\n");
} catch (InterruptedException e) {
e.printStackTrace();
buf.append("Failed to compute FishEye link "+e+"\n");
}
}
} else {
SubversionCommit commit = (SubversionCommit) _commit;
boolean hasFisheye = FISHEYE_SUBVERSION_PROJECT.contains(commit.project);
for (CodeChange cc : commit.getCodeChanges()) {
buf.append(MessageFormat.format(" {0}\n",cc.fileName));
if(!hasFisheye)
buf.append(" "+cc.url+"\n");
}
if(hasFisheye) {
buf.append(MessageFormat.format(
"http://fisheye4.cenqua.com/changelog/{0}/?cs={1}",
commit.project,
commit.revision));
}
}
buf.append("\n");
buf.append("Log:\n");
buf.append(_commit.log);
return buf.toString();
}" |
Inversion-Mutation | megadiff | "@Override
public void onReceive(final Context context, Intent intent) {
final String action = intent.getAction();
if (Log.LOGV) Log.v("AlarmInitReceiver" + action);
final PendingResult result = goAsync();
final WakeLock wl = AlarmAlertWakeLock.createPartialWakeLock(context);
wl.acquire();
AsyncHandler.post(new Runnable() {
@Override public void run() {
// Remove the snooze alarm after a boot.
if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
Alarms.saveSnoozeAlert(context, Alarms.INVALID_ALARM_ID, -1);
Alarms.disableExpiredAlarms(context);
}
Alarms.setNextAlert(context);
result.finish();
Log.v("AlarmInitReceiver finished");
wl.release();
}
});
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onReceive" | "@Override
public void onReceive(final Context context, Intent intent) {
final String action = intent.getAction();
if (Log.LOGV) Log.v("AlarmInitReceiver" + action);
final PendingResult result = goAsync();
final WakeLock wl = AlarmAlertWakeLock.createPartialWakeLock(context);
wl.acquire();
AsyncHandler.post(new Runnable() {
@Override public void run() {
// Remove the snooze alarm after a boot.
if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
Alarms.saveSnoozeAlert(context, Alarms.INVALID_ALARM_ID, -1);
}
<MASK>Alarms.disableExpiredAlarms(context);</MASK>
Alarms.setNextAlert(context);
result.finish();
Log.v("AlarmInitReceiver finished");
wl.release();
}
});
}" |
Inversion-Mutation | megadiff | "@Override public void run() {
// Remove the snooze alarm after a boot.
if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
Alarms.saveSnoozeAlert(context, Alarms.INVALID_ALARM_ID, -1);
Alarms.disableExpiredAlarms(context);
}
Alarms.setNextAlert(context);
result.finish();
Log.v("AlarmInitReceiver finished");
wl.release();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run" | "@Override public void run() {
// Remove the snooze alarm after a boot.
if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
Alarms.saveSnoozeAlert(context, Alarms.INVALID_ALARM_ID, -1);
}
<MASK>Alarms.disableExpiredAlarms(context);</MASK>
Alarms.setNextAlert(context);
result.finish();
Log.v("AlarmInitReceiver finished");
wl.release();
}" |
Inversion-Mutation | megadiff | "void start () {
try {
graphics.setupDisplay();
listener.create();
listener.resize(Math.max(1, graphics.getWidth()), Math.max(1, graphics.getHeight()));
} catch (Exception ex) {
stopped();
throw new GdxRuntimeException(ex);
}
EventQueue.invokeLater(new Runnable() {
int lastWidth = Math.max(1, graphics.getWidth());
int lastHeight = Math.max(1, graphics.getHeight());
public void run () {
if (!running) return;
graphics.updateTime();
synchronized (runnables) {
executedRunnables.clear();
executedRunnables.addAll(runnables);
runnables.clear();
for (int i = 0; i < executedRunnables.size(); i++) {
try {
executedRunnables.get(i).run();
} catch (Throwable t) {
t.printStackTrace();
}
}
}
input.update();
int width = Math.max(1, graphics.getWidth());
int height = Math.max(1, graphics.getHeight());
if (lastWidth != width || lastHeight != height) {
lastWidth = width;
lastHeight = height;
Gdx.gl.glViewport(0, 0, lastWidth, lastHeight);
resize(width, height);
listener.resize(width, height);
}
input.processEvents();
listener.render();
audio.update();
Display.update();
canvas.setCursor(cursor);
if (graphics.vsync) Display.sync(60);
if (running && !Display.isCloseRequested())
EventQueue.invokeLater(this);
else
stopped();
}
});
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "start" | "void start () {
try {
graphics.setupDisplay();
listener.create();
listener.resize(Math.max(1, graphics.getWidth()), Math.max(1, graphics.getHeight()));
} catch (Exception ex) {
stopped();
throw new GdxRuntimeException(ex);
}
EventQueue.invokeLater(new Runnable() {
int lastWidth = Math.max(1, graphics.getWidth());
int lastHeight = Math.max(1, graphics.getHeight());
public void run () {
if (!running) return;
<MASK>canvas.setCursor(cursor);</MASK>
graphics.updateTime();
synchronized (runnables) {
executedRunnables.clear();
executedRunnables.addAll(runnables);
runnables.clear();
for (int i = 0; i < executedRunnables.size(); i++) {
try {
executedRunnables.get(i).run();
} catch (Throwable t) {
t.printStackTrace();
}
}
}
input.update();
int width = Math.max(1, graphics.getWidth());
int height = Math.max(1, graphics.getHeight());
if (lastWidth != width || lastHeight != height) {
lastWidth = width;
lastHeight = height;
Gdx.gl.glViewport(0, 0, lastWidth, lastHeight);
resize(width, height);
listener.resize(width, height);
}
input.processEvents();
listener.render();
audio.update();
Display.update();
if (graphics.vsync) Display.sync(60);
if (running && !Display.isCloseRequested())
EventQueue.invokeLater(this);
else
stopped();
}
});
}" |
Inversion-Mutation | megadiff | "public void run () {
if (!running) return;
graphics.updateTime();
synchronized (runnables) {
executedRunnables.clear();
executedRunnables.addAll(runnables);
runnables.clear();
for (int i = 0; i < executedRunnables.size(); i++) {
try {
executedRunnables.get(i).run();
} catch (Throwable t) {
t.printStackTrace();
}
}
}
input.update();
int width = Math.max(1, graphics.getWidth());
int height = Math.max(1, graphics.getHeight());
if (lastWidth != width || lastHeight != height) {
lastWidth = width;
lastHeight = height;
Gdx.gl.glViewport(0, 0, lastWidth, lastHeight);
resize(width, height);
listener.resize(width, height);
}
input.processEvents();
listener.render();
audio.update();
Display.update();
canvas.setCursor(cursor);
if (graphics.vsync) Display.sync(60);
if (running && !Display.isCloseRequested())
EventQueue.invokeLater(this);
else
stopped();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run" | "public void run () {
if (!running) return;
<MASK>canvas.setCursor(cursor);</MASK>
graphics.updateTime();
synchronized (runnables) {
executedRunnables.clear();
executedRunnables.addAll(runnables);
runnables.clear();
for (int i = 0; i < executedRunnables.size(); i++) {
try {
executedRunnables.get(i).run();
} catch (Throwable t) {
t.printStackTrace();
}
}
}
input.update();
int width = Math.max(1, graphics.getWidth());
int height = Math.max(1, graphics.getHeight());
if (lastWidth != width || lastHeight != height) {
lastWidth = width;
lastHeight = height;
Gdx.gl.glViewport(0, 0, lastWidth, lastHeight);
resize(width, height);
listener.resize(width, height);
}
input.processEvents();
listener.render();
audio.update();
Display.update();
if (graphics.vsync) Display.sync(60);
if (running && !Display.isCloseRequested())
EventQueue.invokeLater(this);
else
stopped();
}" |
Inversion-Mutation | megadiff | "@EventHandler
public void interact(PlayerInteractEvent event) {
if (!event.getPlayer().getWorld().getName().equals(name)) return;
try {
Player player = event.getPlayer();
if (selecting.contains(player.getName())) {
player.sendMessage(ChatColor.RED + "You are already selecting a class, please wait!");
return;
}
Block block = event.getClickedBlock();
if (block.getType().equals(Material.SIGN_POST) || block.getType().equals(Material.WALL_SIGN)) {
BlockState state = block.getState();
Sign sign = (Sign) state;
selecting.add(player.getName());
// Sign options
if (sign.getLine(1).contains("Firearms")) {
handKit(player, Group.FIREARMS);
return;
}
if (sign.getLine(1).contains("Spy")) {
if (player.hasPermission("oresomebattles.rank.donator") || player.hasPermission("oresomebattles.rank.donator.plus")) {
handKit(player, Group.SPY);
return;
} else {
player.sendMessage(ChatColor.RED + "That's a donator class!");
}
}
if (sign.getLine(1).contains("Demolition")) {
if (player.hasPermission("oresomebattles.rank.donator.plus")) {
handKit(player, Group.DEMOLITION);
return;
} else {
player.sendMessage(ChatColor.RED + "That's a donator+ class!");
}
}
if (sign.getLine(1).contains("Knight")) {
handKit(player, Group.KNIGHT);
return;
}
if (sign.getLine(1).contains("Archer")) {
handKit(player, Group.ARCHER);
return;
}
if (sign.getLine(1).contains("Medic")) {
handKit(player, Group.MEDIC);
return;
}
if (sign.getLine(1).contains("Tank")) {
handKit(player, Group.TANK);
return;
}
if (sign.getLine(1).contains("Scout")) {
handKit(player, Group.SCOUT);
}
}
} catch (NullPointerException ex) {
// Catches null ClickedBlock
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "interact" | "@EventHandler
public void interact(PlayerInteractEvent event) {
if (!event.getPlayer().getWorld().getName().equals(name)) return;
try {
Player player = event.getPlayer();
if (selecting.contains(player.getName())) {
player.sendMessage(ChatColor.RED + "You are already selecting a class, please wait!");
return;
}
Block block = event.getClickedBlock();
<MASK>selecting.add(player.getName());</MASK>
if (block.getType().equals(Material.SIGN_POST) || block.getType().equals(Material.WALL_SIGN)) {
BlockState state = block.getState();
Sign sign = (Sign) state;
// Sign options
if (sign.getLine(1).contains("Firearms")) {
handKit(player, Group.FIREARMS);
return;
}
if (sign.getLine(1).contains("Spy")) {
if (player.hasPermission("oresomebattles.rank.donator") || player.hasPermission("oresomebattles.rank.donator.plus")) {
handKit(player, Group.SPY);
return;
} else {
player.sendMessage(ChatColor.RED + "That's a donator class!");
}
}
if (sign.getLine(1).contains("Demolition")) {
if (player.hasPermission("oresomebattles.rank.donator.plus")) {
handKit(player, Group.DEMOLITION);
return;
} else {
player.sendMessage(ChatColor.RED + "That's a donator+ class!");
}
}
if (sign.getLine(1).contains("Knight")) {
handKit(player, Group.KNIGHT);
return;
}
if (sign.getLine(1).contains("Archer")) {
handKit(player, Group.ARCHER);
return;
}
if (sign.getLine(1).contains("Medic")) {
handKit(player, Group.MEDIC);
return;
}
if (sign.getLine(1).contains("Tank")) {
handKit(player, Group.TANK);
return;
}
if (sign.getLine(1).contains("Scout")) {
handKit(player, Group.SCOUT);
}
}
} catch (NullPointerException ex) {
// Catches null ClickedBlock
}
}" |
Inversion-Mutation | megadiff | "@RequestMapping(value="/projects/{projectId}/analyses/{analysisId}", method=RequestMethod.GET, produces="application/json")
@PreAuthorize("permitAll")
public void handleJSON(
Authentication authentication,
HttpServletRequest request,
HttpServletResponse response,
@ModelAttribute(value="analysis") Analysis analysis
) throws IOException, JSONException {
if (!hasPermission(authentication, request, analysis, "read")) {
response.setStatus(403);
return;
}
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Expires", "Thu, 01 Jan 1970 00:00:00 GMT");
JSONWriter out = new JSONWriter(response.getWriter());
out.object();
out.key("id").value(analysis.getId());
out.key("params").object();
out.key("queryType").value(analysis.getAnalysisType());
if (analysis.getFromDate() != null) {
out.key("fromDate").value(isoDateFormat.format(analysis.getFromDate()));
}
if (analysis.getToDate() != null) {
out.key("toDate").value(isoDateFormat.format(analysis.getToDate()));
}
out.key("animalIds").array();
for (Animal animal : analysis.getAnimals()) {
out.value(animal.getId());
}
out.endArray();
out.key("animalNames").array();
for (Animal animal : analysis.getAnimals()) {
out.value(animal.getAnimalName());
}
out.endArray();
for (AnalysisParameter parameter : analysis.getParameters()) {
out.key(parameter.getName()).value(parameter.getValue());
}
out.endObject();
out.key("status").value(analysis.getStatus().name());
if (analysis.getMessage() != null) {
out.key("message").value(analysis.getMessage());
}
if (analysis.getStatus() == AnalysisStatus.COMPLETE) {
String resultBaseUrl = String.format("%s/projects/%d/analyses/%d/result", request.getContextPath(), analysis.getProject().getId(), analysis.getId());
out.key("resultFiles").array();
{
out.object();
out.key("title").value("KML");
out.key("format").value("kml");
out.key("url").value(resultBaseUrl + "?format=kml");
out.endObject();
}
if (analysis.getProject().getCrosses180()) {
out.object();
out.key("title").value("KML (outline)");
out.key("format").value("kml");
out.key("url").value(resultBaseUrl + "?format=kml&fill=false");
out.endObject();
}
if (!analysis.getResultFeatures().isEmpty()) {
out.object();
out.key("title").value("SHP");
out.key("format").value("shp");
out.key("url").value(resultBaseUrl + "?format=shp");
out.endObject();
}
out.endArray();
out.key("hasAnimalFeatures").value(analysis.getAnalysisType().getReturnsAnimalFeatures());
}
if (analysis.getDescription() != null) {
out.key("description").value(analysis.getDescription());
}
out.endObject();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handleJSON" | "@RequestMapping(value="/projects/{projectId}/analyses/{analysisId}", method=RequestMethod.GET, produces="application/json")
@PreAuthorize("permitAll")
public void handleJSON(
Authentication authentication,
HttpServletRequest request,
HttpServletResponse response,
@ModelAttribute(value="analysis") Analysis analysis
) throws IOException, JSONException {
if (!hasPermission(authentication, request, analysis, "read")) {
response.setStatus(403);
return;
}
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Expires", "Thu, 01 Jan 1970 00:00:00 GMT");
JSONWriter out = new JSONWriter(response.getWriter());
out.object();
out.key("id").value(analysis.getId());
out.key("params").object();
out.key("queryType").value(analysis.getAnalysisType());
<MASK>out.key("hasAnimalFeatures").value(analysis.getAnalysisType().getReturnsAnimalFeatures());</MASK>
if (analysis.getFromDate() != null) {
out.key("fromDate").value(isoDateFormat.format(analysis.getFromDate()));
}
if (analysis.getToDate() != null) {
out.key("toDate").value(isoDateFormat.format(analysis.getToDate()));
}
out.key("animalIds").array();
for (Animal animal : analysis.getAnimals()) {
out.value(animal.getId());
}
out.endArray();
out.key("animalNames").array();
for (Animal animal : analysis.getAnimals()) {
out.value(animal.getAnimalName());
}
out.endArray();
for (AnalysisParameter parameter : analysis.getParameters()) {
out.key(parameter.getName()).value(parameter.getValue());
}
out.endObject();
out.key("status").value(analysis.getStatus().name());
if (analysis.getMessage() != null) {
out.key("message").value(analysis.getMessage());
}
if (analysis.getStatus() == AnalysisStatus.COMPLETE) {
String resultBaseUrl = String.format("%s/projects/%d/analyses/%d/result", request.getContextPath(), analysis.getProject().getId(), analysis.getId());
out.key("resultFiles").array();
{
out.object();
out.key("title").value("KML");
out.key("format").value("kml");
out.key("url").value(resultBaseUrl + "?format=kml");
out.endObject();
}
if (analysis.getProject().getCrosses180()) {
out.object();
out.key("title").value("KML (outline)");
out.key("format").value("kml");
out.key("url").value(resultBaseUrl + "?format=kml&fill=false");
out.endObject();
}
if (!analysis.getResultFeatures().isEmpty()) {
out.object();
out.key("title").value("SHP");
out.key("format").value("shp");
out.key("url").value(resultBaseUrl + "?format=shp");
out.endObject();
}
out.endArray();
}
if (analysis.getDescription() != null) {
out.key("description").value(analysis.getDescription());
}
out.endObject();
}" |
Inversion-Mutation | megadiff | "@Override
public void update() {
super.update(); // makes sure to execute AppTasks
if (speed == 0 || paused) {
return;
}
float tpf = timer.getTimePerFrame() * speed;
if (showFps) {
secondCounter += timer.getTimePerFrame();
frameCounter ++;
if (secondCounter >= 1.0f) {
int fps = (int) (frameCounter / secondCounter);
fpsText.setText("Frames per second: " + fps);
secondCounter = 0.0f;
frameCounter = 0;
}
}
// update states
stateManager.update(tpf);
// update game specific things
useLatestLocationUpdate();
computeBeams(tpf);
movePlayers(tpf);
menuController.actualizeScreen();
menuController.updateHUD();
// update world and gui
getWorldController().updateLogicalState(tpf);
guiNode.updateLogicalState(tpf);
getWorldController().updateGeometricState();
guiNode.updateGeometricState();
// render states
stateManager.render(renderManager);
renderManager.render(tpf, context.isRenderable());
stateManager.postRender();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "update" | "@Override
public void update() {
super.update(); // makes sure to execute AppTasks
if (speed == 0 || paused) {
return;
}
float tpf = timer.getTimePerFrame() * speed;
if (showFps) {
secondCounter += timer.getTimePerFrame();
frameCounter ++;
if (secondCounter >= 1.0f) {
int fps = (int) (frameCounter / secondCounter);
fpsText.setText("Frames per second: " + fps);
secondCounter = 0.0f;
frameCounter = 0;
}
}
// update states
stateManager.update(tpf);
// update game specific things
useLatestLocationUpdate();
computeBeams(tpf);
movePlayers(tpf);
<MASK>menuController.updateHUD();</MASK>
menuController.actualizeScreen();
// update world and gui
getWorldController().updateLogicalState(tpf);
guiNode.updateLogicalState(tpf);
getWorldController().updateGeometricState();
guiNode.updateGeometricState();
// render states
stateManager.render(renderManager);
renderManager.render(tpf, context.isRenderable());
stateManager.postRender();
}" |
Inversion-Mutation | megadiff | "@Override
public void draw(Graphics g)
{
Graphics2D g2d = (Graphics2D)g;
AffineTransform transform = new AffineTransform();
BufferedImage img = new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB);
Vector right = new Vector(1,0);
// Draw head
try
{
img = ImageIO.read( new File("images/s01_head_closed.png") );
}
catch (Exception e)
{
}
transform.translate(head.lPiv.x, head.lPiv.y - headSize.y/2);
Vector dir = new Vector(head.rPiv.x - head.lPiv.x, head.rPiv.y - head.lPiv.y);
dir.normalize();
double value = Math.atan2(dir.x, dir.y);
transform.rotate(-(value - Math.PI/2), 0, headSize.y/2);
g2d.drawImage(img, transform, null);
// Draw body
try
{
img = ImageIO.read( new File("images/s1_body.png") );
}
catch (Exception e)
{
}
for (Body body : bodyList)
{
transform = new AffineTransform();
transform.translate(body.lPiv.x, body.lPiv.y - bodySize.y/2);
dir = new Vector(body.rPiv.x - body.lPiv.x, body.rPiv.y - body.lPiv.y);
value = Math.atan2(dir.x, dir.y);
transform.rotate(-(value - Math.PI/2), 0, bodySize.y/2);
g2d.drawImage(img, transform, null);
}
// Draw tail
transform = new AffineTransform();
try
{
img = ImageIO.read( new File("images/s01_tail.png") );
}
catch (Exception e)
{
}
transform.translate(tail.lPiv.x, tail.lPiv.y - tailSize.y/2);
dir = new Vector(tail.rPiv.x - tail.lPiv.x, tail.rPiv.y - tail.lPiv.y);
value = Math.atan2(dir.x, dir.y);
transform.rotate(-(value - Math.PI/2), 0, tailSize.y/2);
g2d.drawImage(img, transform, null);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "draw" | "@Override
public void draw(Graphics g)
{
Graphics2D g2d = (Graphics2D)g;
AffineTransform <MASK>transform = new AffineTransform();</MASK>
BufferedImage img = new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB);
Vector right = new Vector(1,0);
// Draw head
try
{
img = ImageIO.read( new File("images/s01_head_closed.png") );
}
catch (Exception e)
{
}
transform.translate(head.lPiv.x, head.lPiv.y - headSize.y/2);
Vector dir = new Vector(head.rPiv.x - head.lPiv.x, head.rPiv.y - head.lPiv.y);
dir.normalize();
double value = Math.atan2(dir.x, dir.y);
transform.rotate(-(value - Math.PI/2), 0, headSize.y/2);
g2d.drawImage(img, transform, null);
// Draw body
<MASK>transform = new AffineTransform();</MASK>
try
{
img = ImageIO.read( new File("images/s1_body.png") );
}
catch (Exception e)
{
}
for (Body body : bodyList)
{
transform.translate(body.lPiv.x, body.lPiv.y - bodySize.y/2);
dir = new Vector(body.rPiv.x - body.lPiv.x, body.rPiv.y - body.lPiv.y);
value = Math.atan2(dir.x, dir.y);
transform.rotate(-(value - Math.PI/2), 0, bodySize.y/2);
g2d.drawImage(img, transform, null);
}
// Draw tail
<MASK>transform = new AffineTransform();</MASK>
try
{
img = ImageIO.read( new File("images/s01_tail.png") );
}
catch (Exception e)
{
}
transform.translate(tail.lPiv.x, tail.lPiv.y - tailSize.y/2);
dir = new Vector(tail.rPiv.x - tail.lPiv.x, tail.rPiv.y - tail.lPiv.y);
value = Math.atan2(dir.x, dir.y);
transform.rotate(-(value - Math.PI/2), 0, tailSize.y/2);
g2d.drawImage(img, transform, null);
}" |
Inversion-Mutation | megadiff | "private Token<JavaFXTokenId> processString(int quote, int startedWith) {
assert (quote == '\'' || quote == '"');
assert( startedWith == RBRACE || startedWith == 0);
while (true) {
int c = inputRead();
switch (c) {
case '\'': // NOI18N
case '"': // NOI18N
if (quote == c) {
if(startedWith == RBRACE) {
stateController.leaveBrace();
if(stateController.inBraceQuote()) stateController.leaveQuote();
return token(JavaFXTokenId.RBRACE_QUOTE_STRING_LITERAL);
}
return token(JavaFXTokenId.STRING_LITERAL);
}
break;
case '\\':
inputRead();
break;
case '\r':
inputConsumeNewline();
case '\n':
inputRead(); // enable the multi-line string literals.
break;
case EOF: // incompleted string literal, i.e. under development.
return tokenFactoryCreateToken(JavaFXTokenId.STRING_LITERAL,
inputReadLength(), PartType.START);
case '{':
if(startedWith == '}') {
return token(JavaFXTokenId.RBRACE_LBRACE_STRING_LITERAL);
}
stateController.enterBrace(quote, false);
return token(JavaFXTokenId.QUOTE_LBRACE_STRING_LITERAL);
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "processString" | "private Token<JavaFXTokenId> processString(int quote, int startedWith) {
assert (quote == '\'' || quote == '"');
assert( startedWith == RBRACE || startedWith == 0);
while (true) {
int c = inputRead();
switch (c) {
case '\'': // NOI18N
case '"': // NOI18N
if (quote == c) {
if(startedWith == RBRACE) {
stateController.leaveBrace();
if(stateController.inBraceQuote()) stateController.leaveQuote();
return token(JavaFXTokenId.RBRACE_QUOTE_STRING_LITERAL);
}
return token(JavaFXTokenId.STRING_LITERAL);
}
break;
case '\\':
inputRead();
break;
case '\r':
inputConsumeNewline();
case '\n':
inputRead(); // enable the multi-line string literals.
break;
case EOF: // incompleted string literal, i.e. under development.
return tokenFactoryCreateToken(JavaFXTokenId.STRING_LITERAL,
inputReadLength(), PartType.START);
case '{':
<MASK>stateController.enterBrace(quote, false);</MASK>
if(startedWith == '}') {
return token(JavaFXTokenId.RBRACE_LBRACE_STRING_LITERAL);
}
return token(JavaFXTokenId.QUOTE_LBRACE_STRING_LITERAL);
}
}
}" |
Inversion-Mutation | megadiff | "RobotType(RobotLevel level,
double maxEnergon,
double maxFlux,
double spawnCost,
double upkeep,
int moveDelayOrthogonal,
double moveCost,
int sensorRadiusSquared,
double sensorAngle,
int attackRadiusMinSquared,
int attackRadiusMaxSquared,
double attackAngle,
int attackDelay,
double attackPower,
boolean canAttackAir,
boolean canAttackGround)
{
this.level=level;
this.maxEnergon=maxEnergon;
this.maxFlux=maxFlux;
this.spawnCost=spawnCost;
this.upkeep=upkeep;
this.moveDelayOrthogonal=moveDelayOrthogonal;
this.moveDelayDiagonal=(int)Math.round(moveDelayOrthogonal*Math.sqrt(2.));
this.moveCost=moveCost;
this.sensorRadiusSquared=sensorRadiusSquared;
this.sensorAngle=sensorAngle;
this.attackRadiusMaxSquared=attackRadiusMaxSquared;
this.attackRadiusMinSquared=attackRadiusMinSquared;
this.attackAngle=attackAngle;
this.attackDelay=attackDelay;
this.attackPower=attackPower;
this.canAttackAir=canAttackAir;
this.canAttackGround=canAttackGround;
this.sensorCosHalfTheta=Math.cos(sensorAngle*Math.PI/360.);
this.attackCosHalfTheta=Math.cos(attackAngle*Math.PI/360.);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "RobotType" | "RobotType(RobotLevel level,
double maxEnergon,
double maxFlux,
double spawnCost,
double upkeep,
int moveDelayOrthogonal,
double moveCost,
int sensorRadiusSquared,
double sensorAngle,
<MASK>int attackRadiusMaxSquared,</MASK>
int attackRadiusMinSquared,
double attackAngle,
int attackDelay,
double attackPower,
boolean canAttackAir,
boolean canAttackGround)
{
this.level=level;
this.maxEnergon=maxEnergon;
this.maxFlux=maxFlux;
this.spawnCost=spawnCost;
this.upkeep=upkeep;
this.moveDelayOrthogonal=moveDelayOrthogonal;
this.moveDelayDiagonal=(int)Math.round(moveDelayOrthogonal*Math.sqrt(2.));
this.moveCost=moveCost;
this.sensorRadiusSquared=sensorRadiusSquared;
this.sensorAngle=sensorAngle;
this.attackRadiusMaxSquared=attackRadiusMaxSquared;
this.attackRadiusMinSquared=attackRadiusMinSquared;
this.attackAngle=attackAngle;
this.attackDelay=attackDelay;
this.attackPower=attackPower;
this.canAttackAir=canAttackAir;
this.canAttackGround=canAttackGround;
this.sensorCosHalfTheta=Math.cos(sensorAngle*Math.PI/360.);
this.attackCosHalfTheta=Math.cos(attackAngle*Math.PI/360.);
}" |
Inversion-Mutation | megadiff | "private void initPlayerListeners() {
final Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (progressEnabled && player.isPlaying() && !isSeeking) {
progressSlider.setValue((int) player.getCurrentSample());
}
if (player.isPlaying())
updateStatus();
}
});
timer.start();
player.addListener(new PlayerListener() {
public void onEvent(PlayerEvent e) {
pauseButton.setSelected(player.isPaused());
switch (e.getEventCode()) {
case PLAYING_STARTED:
timer.start();
break;
case PAUSED:
timer.stop();
break;
case STOPPED:
timer.stop();
progressEnabled = false;
progressSlider.setValue(progressSlider.getMinimum());
statusLabel.setText(null);
break;
case FILE_OPENED:
Track track = player.getTrack();
if (track != null) {
int max = (int) track.getTotalSamples();
if (max == -1) {
progressEnabled = false;
} else {
progressEnabled = true;
progressSlider.setMaximum(max);
}
}
progressSlider.setValue((int) player.getCurrentSample());
updateStatus();
break;
case SEEK_FINISHED:
isSeeking = false;
break;
}
}
});
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "initPlayerListeners" | "private void initPlayerListeners() {
final Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (progressEnabled && player.isPlaying() && !isSeeking) {
progressSlider.setValue((int) player.getCurrentSample());
}
if (player.isPlaying())
<MASK>updateStatus();</MASK>
}
});
timer.start();
player.addListener(new PlayerListener() {
public void onEvent(PlayerEvent e) {
pauseButton.setSelected(player.isPaused());
switch (e.getEventCode()) {
case PLAYING_STARTED:
timer.start();
<MASK>updateStatus();</MASK>
break;
case PAUSED:
timer.stop();
break;
case STOPPED:
timer.stop();
progressEnabled = false;
progressSlider.setValue(progressSlider.getMinimum());
statusLabel.setText(null);
break;
case FILE_OPENED:
Track track = player.getTrack();
if (track != null) {
int max = (int) track.getTotalSamples();
if (max == -1) {
progressEnabled = false;
} else {
progressEnabled = true;
progressSlider.setMaximum(max);
}
}
progressSlider.setValue((int) player.getCurrentSample());
break;
case SEEK_FINISHED:
isSeeking = false;
break;
}
}
});
}" |
Inversion-Mutation | megadiff | "public void onEvent(PlayerEvent e) {
pauseButton.setSelected(player.isPaused());
switch (e.getEventCode()) {
case PLAYING_STARTED:
timer.start();
break;
case PAUSED:
timer.stop();
break;
case STOPPED:
timer.stop();
progressEnabled = false;
progressSlider.setValue(progressSlider.getMinimum());
statusLabel.setText(null);
break;
case FILE_OPENED:
Track track = player.getTrack();
if (track != null) {
int max = (int) track.getTotalSamples();
if (max == -1) {
progressEnabled = false;
} else {
progressEnabled = true;
progressSlider.setMaximum(max);
}
}
progressSlider.setValue((int) player.getCurrentSample());
updateStatus();
break;
case SEEK_FINISHED:
isSeeking = false;
break;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onEvent" | "public void onEvent(PlayerEvent e) {
pauseButton.setSelected(player.isPaused());
switch (e.getEventCode()) {
case PLAYING_STARTED:
timer.start();
<MASK>updateStatus();</MASK>
break;
case PAUSED:
timer.stop();
break;
case STOPPED:
timer.stop();
progressEnabled = false;
progressSlider.setValue(progressSlider.getMinimum());
statusLabel.setText(null);
break;
case FILE_OPENED:
Track track = player.getTrack();
if (track != null) {
int max = (int) track.getTotalSamples();
if (max == -1) {
progressEnabled = false;
} else {
progressEnabled = true;
progressSlider.setMaximum(max);
}
}
progressSlider.setValue((int) player.getCurrentSample());
break;
case SEEK_FINISHED:
isSeeking = false;
break;
}
}" |
Inversion-Mutation | megadiff | "public static boolean makeConnections(EOObjectStore os, String tag) {
Logger logger = Logger.getLogger("rujel.dbConnection");
SettingsReader dbSettings = SettingsReader.settingsForPath("dbConnection", false);
if(dbSettings == null) {
logger.log(WOLogLevel.CONFIG,
"No database connection settings found. Using predefined connections.");
return false;
}
EOModelGroup mg = EOModelGroup.defaultGroup();
String prototypes = dbSettings.get("prototypes",null);
if(prototypes != null) {
EOEntity jdbcPrototypesEntity = mg.entityNamed("EOJDBCPrototypes");
if(prototypesEntity == null)
prototypesEntity = mg.entityNamed(prototypes);
if(prototypesEntity == null) {
NSDictionary plist = (NSDictionary)PlistReader.readPlist(prototypes, null);
if(plist != null) {
EOModel model = jdbcPrototypesEntity.model();
prototypesEntity = new EOEntity(plist,model);
model.addEntity(prototypesEntity);
}
}
if(prototypesEntity != null && !prototypesEntity.equals(jdbcPrototypesEntity)) {
logger.log(WOLogLevel.CONFIG,"Using prototypes from " + prototypes);
Enumeration enu = jdbcPrototypesEntity.attributes().objectEnumerator();
while (enu.hasMoreElements()) {
EOAttribute jdbcPrototype = (EOAttribute)enu.nextElement();
String prototypesName = (String)jdbcPrototype.name();
EOAttribute dbPrototype =
(EOAttribute)prototypesEntity.attributeNamed(prototypesName);
if (dbPrototype != null) {
jdbcPrototype.setDefinition(dbPrototype.definition());
jdbcPrototype.setExternalType(dbPrototype.externalType());
jdbcPrototype.setPrecision(dbPrototype.precision());
jdbcPrototype.setReadFormat(dbPrototype.readFormat());
jdbcPrototype.setScale(dbPrototype.scale());
jdbcPrototype.setUserInfo(dbPrototype.userInfo());
jdbcPrototype.setValueType(dbPrototype.valueType());
jdbcPrototype.setWidth(dbPrototype.width());
jdbcPrototype.setWriteFormat(dbPrototype.writeFormat());
}
}
} else {
logger.log(WOLogLevel.WARNING,"Could not load prototypes " + prototypes);
}
}
Enumeration enu = mg.models().immutableClone().objectEnumerator();
String serverURL = dbSettings.get("serverURL",null);
String urlSuffix = dbSettings.get("urlSuffix",null);
boolean success = true;
NSMutableDictionary connDict = connectionDictionaryFromSettings(dbSettings, null);
EOEditingContext ec = (os != null)?new EOEditingContext(os):new EOEditingContext();
SettingsReader dbMapping = dbSettings.subreaderForPath("dbMapping", false);
while (enu.hasMoreElements()) {
EOModel model = (EOModel) enu.nextElement();
if(model.name().endsWith("Prototypes")) {
Enumeration ents = model.entityNames().immutableClone().objectEnumerator();
while (ents.hasMoreElements()) {
String entName = (String) ents.nextElement();
if(!entName.equals("EOJDBCPrototypes")) {
model.removeEntity(model.entityNamed(entName));
}
}
continue;
}
SettingsReader currSettings = dbSettings.subreaderForPath(model.name(), false);
boolean noSettings = (currSettings == null);
if(!noSettings && currSettings.getBoolean("skip", false)) {
mg.removeModel(model);
logger.config("Skipping model '" + model.name() + '\'');
continue;
}
NSMutableDictionary cd = connDict.mutableClone();
String url = null;
String dbName = null;
if(currSettings != null) {
cd = connectionDictionaryFromSettings(currSettings, cd);
url = currSettings.get("URL", null);
if(url == null)
dbName = currSettings.get("dbName", null);
if(dbName != null && dbMapping != null) {
Object mapped = dbMapping.valueForKey(dbName);
if(mapped == null && tag != null)
mapped = dbMapping.valueForKey(String.format(dbName, tag));
if(mapped != null) {
if(mapped instanceof String) {
dbName = (String)mapped;
if(dbName.startsWith("jdbc")) {
url = dbName;
dbName = null;
}
} else if(mapped instanceof SettingsReader) {
cd = connectionDictionaryFromSettings((SettingsReader)mapped, cd);
url = ((SettingsReader)mapped).get("URL", null);
if(url == null)
dbName = ((SettingsReader)mapped).get("dbName", null);
}
}
}
}
if(url == null && serverURL != null) {
boolean onlyHostname = !serverURL.startsWith("jdbc");
String urlFromModel = (String)model.connectionDictionary().valueForKey("URL");
if(dbName == null && onlyHostname) {
url = urlFromModel.replaceFirst("localhost", serverURL);
if(urlSuffix != null) {
int idx = url.indexOf('?');
if(idx > 0)
url = url.substring(0,idx);
url = url + urlSuffix;
}
} else {
int index = urlFromModel.indexOf("localhost");
StringBuffer buf = new StringBuffer(serverURL);
if (onlyHostname)
buf.insert(0, urlFromModel.substring(0, index));
if(buf.charAt(buf.length() -1) == '/')
buf.deleteCharAt(buf.length() -1);
if(dbName == null) {
int idx = urlFromModel.indexOf('?',index + 9);
if(idx > 0 && urlSuffix != null) {
buf.append(urlFromModel.substring(index + 9,idx));
} else {
buf.append(urlFromModel.substring(index + 9));
}
} else {
if(onlyHostname)
buf.append(urlFromModel.charAt(index + 9));
else {
char c = buf.charAt(buf.length() -1);
if((c>='a'&&c<='z')||(c>='A'&&c<='Z')||(c>='0'&&c<='9'))
buf.append('/');
}
if(tag != null)
dbName = String.format(dbName, tag);
buf.append(dbName);
}
if(urlSuffix != null)
buf.append(urlSuffix);
url = buf.toString();
}
} // if(url == null && serverURL != null)
if(url != null) {
cd.takeValueForKey(url, "URL");
}
if(cd.count() > 0) {
try {
ec.lock();
EODatabaseContext.forceConnectionWithModel(model, cd, ec);
String message = "Model '" + model.name() + "' connected to database";
if(url != null)
message = message + '\n' + url;
logger.config(message);
} catch (Exception e) {
String message = "Model '" + model.name() +
"' could not connect to database";
if(url != null)
message = message + '\n' + url;
if(noSettings) {
logger.log(WOLogLevel.INFO, message);
// mg.removeModel(model);
} else {
logger.log(WOLogLevel.WARNING, message, e);
success = false;
if(url != null) {
String untagged = (currSettings==null)?null:
currSettings.get("untagged", null);
if(untagged != null) {
url = url.replaceFirst(dbName, untagged);
cd.takeValueForKey(url, "URL");
try {
EODatabaseContext.forceConnectionWithModel(model, cd, ec);
message = "Model '" + model.name() +
"' connected to untagged database" + '\n' + url;
logger.config(message);
success = true;
} catch (Exception ex) {
message = "Model '" + model.name() +
"' also could not connect to database" + '\n' + url;
logger.log(WOLogLevel.WARNING, message, ex);
}
}
}
}
} finally {
ec.unlock();
}
}
} // while (models.hasMoreElements())
if(success && tag != null && os != null) {
if(coordinatorsByTag == null)
coordinatorsByTag = new NSMutableDictionary(os,tag);
else
coordinatorsByTag.takeValueForKey(os, tag);
}
ec.dispose();
return success;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "makeConnections" | "public static boolean makeConnections(EOObjectStore os, String tag) {
Logger logger = Logger.getLogger("rujel.dbConnection");
SettingsReader dbSettings = SettingsReader.settingsForPath("dbConnection", false);
if(dbSettings == null) {
logger.log(WOLogLevel.CONFIG,
"No database connection settings found. Using predefined connections.");
return false;
}
EOModelGroup mg = EOModelGroup.defaultGroup();
String prototypes = dbSettings.get("prototypes",null);
if(prototypes != null) {
EOEntity jdbcPrototypesEntity = mg.entityNamed("EOJDBCPrototypes");
if(prototypesEntity == null)
prototypesEntity = mg.entityNamed(prototypes);
if(prototypesEntity == null) {
NSDictionary plist = (NSDictionary)PlistReader.readPlist(prototypes, null);
if(plist != null) {
EOModel model = jdbcPrototypesEntity.model();
prototypesEntity = new EOEntity(plist,model);
model.addEntity(prototypesEntity);
}
}
if(prototypesEntity != null && !prototypesEntity.equals(jdbcPrototypesEntity)) {
logger.log(WOLogLevel.CONFIG,"Using prototypes from " + prototypes);
Enumeration enu = jdbcPrototypesEntity.attributes().objectEnumerator();
while (enu.hasMoreElements()) {
EOAttribute jdbcPrototype = (EOAttribute)enu.nextElement();
String prototypesName = (String)jdbcPrototype.name();
EOAttribute dbPrototype =
(EOAttribute)prototypesEntity.attributeNamed(prototypesName);
if (dbPrototype != null) {
jdbcPrototype.setDefinition(dbPrototype.definition());
jdbcPrototype.setExternalType(dbPrototype.externalType());
jdbcPrototype.setPrecision(dbPrototype.precision());
jdbcPrototype.setReadFormat(dbPrototype.readFormat());
jdbcPrototype.setScale(dbPrototype.scale());
jdbcPrototype.setUserInfo(dbPrototype.userInfo());
jdbcPrototype.setValueType(dbPrototype.valueType());
jdbcPrototype.setWidth(dbPrototype.width());
jdbcPrototype.setWriteFormat(dbPrototype.writeFormat());
}
}
} else {
logger.log(WOLogLevel.WARNING,"Could not load prototypes " + prototypes);
}
}
Enumeration enu = mg.models().immutableClone().objectEnumerator();
String serverURL = dbSettings.get("serverURL",null);
<MASK>boolean onlyHostname = !serverURL.startsWith("jdbc");</MASK>
String urlSuffix = dbSettings.get("urlSuffix",null);
boolean success = true;
NSMutableDictionary connDict = connectionDictionaryFromSettings(dbSettings, null);
EOEditingContext ec = (os != null)?new EOEditingContext(os):new EOEditingContext();
SettingsReader dbMapping = dbSettings.subreaderForPath("dbMapping", false);
while (enu.hasMoreElements()) {
EOModel model = (EOModel) enu.nextElement();
if(model.name().endsWith("Prototypes")) {
Enumeration ents = model.entityNames().immutableClone().objectEnumerator();
while (ents.hasMoreElements()) {
String entName = (String) ents.nextElement();
if(!entName.equals("EOJDBCPrototypes")) {
model.removeEntity(model.entityNamed(entName));
}
}
continue;
}
SettingsReader currSettings = dbSettings.subreaderForPath(model.name(), false);
boolean noSettings = (currSettings == null);
if(!noSettings && currSettings.getBoolean("skip", false)) {
mg.removeModel(model);
logger.config("Skipping model '" + model.name() + '\'');
continue;
}
NSMutableDictionary cd = connDict.mutableClone();
String url = null;
String dbName = null;
if(currSettings != null) {
cd = connectionDictionaryFromSettings(currSettings, cd);
url = currSettings.get("URL", null);
if(url == null)
dbName = currSettings.get("dbName", null);
if(dbName != null && dbMapping != null) {
Object mapped = dbMapping.valueForKey(dbName);
if(mapped == null && tag != null)
mapped = dbMapping.valueForKey(String.format(dbName, tag));
if(mapped != null) {
if(mapped instanceof String) {
dbName = (String)mapped;
if(dbName.startsWith("jdbc")) {
url = dbName;
dbName = null;
}
} else if(mapped instanceof SettingsReader) {
cd = connectionDictionaryFromSettings((SettingsReader)mapped, cd);
url = ((SettingsReader)mapped).get("URL", null);
if(url == null)
dbName = ((SettingsReader)mapped).get("dbName", null);
}
}
}
}
if(url == null && serverURL != null) {
String urlFromModel = (String)model.connectionDictionary().valueForKey("URL");
if(dbName == null && onlyHostname) {
url = urlFromModel.replaceFirst("localhost", serverURL);
if(urlSuffix != null) {
int idx = url.indexOf('?');
if(idx > 0)
url = url.substring(0,idx);
url = url + urlSuffix;
}
} else {
int index = urlFromModel.indexOf("localhost");
StringBuffer buf = new StringBuffer(serverURL);
if (onlyHostname)
buf.insert(0, urlFromModel.substring(0, index));
if(buf.charAt(buf.length() -1) == '/')
buf.deleteCharAt(buf.length() -1);
if(dbName == null) {
int idx = urlFromModel.indexOf('?',index + 9);
if(idx > 0 && urlSuffix != null) {
buf.append(urlFromModel.substring(index + 9,idx));
} else {
buf.append(urlFromModel.substring(index + 9));
}
} else {
if(onlyHostname)
buf.append(urlFromModel.charAt(index + 9));
else {
char c = buf.charAt(buf.length() -1);
if((c>='a'&&c<='z')||(c>='A'&&c<='Z')||(c>='0'&&c<='9'))
buf.append('/');
}
if(tag != null)
dbName = String.format(dbName, tag);
buf.append(dbName);
}
if(urlSuffix != null)
buf.append(urlSuffix);
url = buf.toString();
}
} // if(url == null && serverURL != null)
if(url != null) {
cd.takeValueForKey(url, "URL");
}
if(cd.count() > 0) {
try {
ec.lock();
EODatabaseContext.forceConnectionWithModel(model, cd, ec);
String message = "Model '" + model.name() + "' connected to database";
if(url != null)
message = message + '\n' + url;
logger.config(message);
} catch (Exception e) {
String message = "Model '" + model.name() +
"' could not connect to database";
if(url != null)
message = message + '\n' + url;
if(noSettings) {
logger.log(WOLogLevel.INFO, message);
// mg.removeModel(model);
} else {
logger.log(WOLogLevel.WARNING, message, e);
success = false;
if(url != null) {
String untagged = (currSettings==null)?null:
currSettings.get("untagged", null);
if(untagged != null) {
url = url.replaceFirst(dbName, untagged);
cd.takeValueForKey(url, "URL");
try {
EODatabaseContext.forceConnectionWithModel(model, cd, ec);
message = "Model '" + model.name() +
"' connected to untagged database" + '\n' + url;
logger.config(message);
success = true;
} catch (Exception ex) {
message = "Model '" + model.name() +
"' also could not connect to database" + '\n' + url;
logger.log(WOLogLevel.WARNING, message, ex);
}
}
}
}
} finally {
ec.unlock();
}
}
} // while (models.hasMoreElements())
if(success && tag != null && os != null) {
if(coordinatorsByTag == null)
coordinatorsByTag = new NSMutableDictionary(os,tag);
else
coordinatorsByTag.takeValueForKey(os, tag);
}
ec.dispose();
return success;
}" |
Inversion-Mutation | megadiff | "public Response callAndWait( String recipientId, Map msg, int timeout )
throws SampException {
long finish = timeout > 0
? System.currentTimeMillis() + timeout * 1000
: Long.MAX_VALUE; // 3e8 years
HubConnection connection = getConnection();
String msgTag = generateTag();
responseMap_.put( msgTag, null );
connection.call( recipientId, msgTag, msg );
synchronized ( responseMap_ ) {
while ( responseMap_.containsKey( msgTag ) &&
responseMap_.get( msgTag ) == null &&
System.currentTimeMillis() < finish ) {
long millis = finish - System.currentTimeMillis();
if ( millis > 0 ) {
try {
responseMap_.wait( millis );
}
catch ( InterruptedException e ) {
throw new SampException( "Wait interrupted", e );
}
}
}
if ( responseMap_.containsKey( msgTag ) ) {
Response response = (Response) responseMap_.remove( msgTag );
if ( response != null ) {
return response;
}
else {
assert System.currentTimeMillis() >= finish;
throw new SampException( "Synchronous call timeout" );
}
}
else {
if ( connection != connection_ ) {
throw new SampException( "Hub connection lost" );
}
else {
throw new AssertionError();
}
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "callAndWait" | "public Response callAndWait( String recipientId, Map msg, int timeout )
throws SampException {
long finish = timeout > 0
? System.currentTimeMillis() + timeout * 1000
: Long.MAX_VALUE; // 3e8 years
HubConnection connection = getConnection();
String msgTag = generateTag();
connection.call( recipientId, msgTag, msg );
synchronized ( responseMap_ ) {
<MASK>responseMap_.put( msgTag, null );</MASK>
while ( responseMap_.containsKey( msgTag ) &&
responseMap_.get( msgTag ) == null &&
System.currentTimeMillis() < finish ) {
long millis = finish - System.currentTimeMillis();
if ( millis > 0 ) {
try {
responseMap_.wait( millis );
}
catch ( InterruptedException e ) {
throw new SampException( "Wait interrupted", e );
}
}
}
if ( responseMap_.containsKey( msgTag ) ) {
Response response = (Response) responseMap_.remove( msgTag );
if ( response != null ) {
return response;
}
else {
assert System.currentTimeMillis() >= finish;
throw new SampException( "Synchronous call timeout" );
}
}
else {
if ( connection != connection_ ) {
throw new SampException( "Hub connection lost" );
}
else {
throw new AssertionError();
}
}
}
}" |
Inversion-Mutation | megadiff | "public void link(final Canvas newCanvas) {
if (canvas == newCanvas) return;
final Canvas oldCanvas = canvas;
canvas = newCanvas;
Display.getDefault().asyncExec(new Runnable(){
@Override
public void run() {
linkInternal(newCanvas);
unlinkInternal(oldCanvas);
canvas.redraw();
}
});
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "link" | "public void link(final Canvas newCanvas) {
if (canvas == newCanvas) return;
final Canvas oldCanvas = canvas;
Display.getDefault().asyncExec(new Runnable(){
@Override
public void run() {
linkInternal(newCanvas);
unlinkInternal(oldCanvas);
<MASK>canvas = newCanvas;</MASK>
canvas.redraw();
}
});
}" |
Inversion-Mutation | megadiff | "public UpstreamBridge(ProxyServer bungee, UserConnection con)
{
this.bungee = bungee;
this.con = con;
BungeeCord.getInstance().addConnection( con );
bungee.getTabListHandler().onConnect( con );
con.unsafe().sendPacket( BungeeCord.getInstance().registerChannels() );
TexturePackInfo texture = con.getPendingConnection().getListener().getTexturePack();
if ( texture != null )
{
con.setTexturePack( texture );
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "UpstreamBridge" | "public UpstreamBridge(ProxyServer bungee, UserConnection con)
{
this.bungee = bungee;
this.con = con;
<MASK>bungee.getTabListHandler().onConnect( con );</MASK>
BungeeCord.getInstance().addConnection( con );
con.unsafe().sendPacket( BungeeCord.getInstance().registerChannels() );
TexturePackInfo texture = con.getPendingConnection().getListener().getTexturePack();
if ( texture != null )
{
con.setTexturePack( texture );
}
}" |
Inversion-Mutation | megadiff | "private void cameraZoomOut(State toState, boolean animated) {
final Resources res = getResources();
final boolean toAllApps = (toState == State.ALL_APPS);
final int duration = toAllApps ?
res.getInteger(R.integer.config_allAppsZoomInTime) :
res.getInteger(R.integer.config_customizeZoomInTime);
final float scale = toAllApps ?
(float) res.getInteger(R.integer.config_allAppsZoomScaleFactor) :
(float) res.getInteger(R.integer.config_customizeZoomScaleFactor);
final View toView = toAllApps ? (View) mAllAppsGrid : mHomeCustomizationDrawer;
setPivotsForZoom(toView, toState, scale);
if (toAllApps) {
mWorkspace.shrink(ShrinkState.BOTTOM_HIDDEN, animated);
} else {
mWorkspace.shrink(ShrinkState.TOP, animated);
}
if (animated) {
ValueAnimator scaleAnim = ObjectAnimator.ofPropertyValuesHolder(toView,
PropertyValuesHolder.ofFloat("scaleX", scale, 1.0f),
PropertyValuesHolder.ofFloat("scaleY", scale, 1.0f));
scaleAnim.setDuration(duration);
if (toAllApps) {
toView.setAlpha(0f);
ObjectAnimator alphaAnim = ObjectAnimator.ofPropertyValuesHolder(toView,
PropertyValuesHolder.ofFloat("alpha", 1.0f));
alphaAnim.setInterpolator(new DecelerateInterpolator(1.5f));
alphaAnim.setDuration(duration);
alphaAnim.start();
}
scaleAnim.setInterpolator(new Workspace.ZoomOutInterpolator());
scaleAnim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
// Prepare the position
toView.setTranslationX(0.0f);
toView.setTranslationY(0.0f);
toView.setVisibility(View.VISIBLE);
if (!toAllApps) {
toView.setAlpha(1.0f);
}
}
@Override
public void onAnimationEnd(Animator animation) {
// If we don't set the final scale values here, if this animation is cancelled
// it will have the wrong scale value and subsequent cameraPan animations will
// not fix that
toView.setScaleX(1.0f);
toView.setScaleY(1.0f);
}
});
AnimatorSet toolbarHideAnim = new AnimatorSet();
AnimatorSet toolbarShowAnim = new AnimatorSet();
hideAndShowToolbarButtons(toState, toolbarShowAnim, toolbarHideAnim);
// toView should appear right at the end of the workspace shrink animation
final int startDelay = 0;
if (mStateAnimation != null) mStateAnimation.cancel();
mStateAnimation = new AnimatorSet();
mStateAnimation.playTogether(scaleAnim, toolbarHideAnim);
mStateAnimation.play(scaleAnim).after(startDelay);
// Show the new toolbar buttons just as the main animation is ending
final int fadeInTime = res.getInteger(R.integer.config_toolbarButtonFadeInTime);
mStateAnimation.play(toolbarShowAnim).after(duration + startDelay - fadeInTime);
mStateAnimation.start();
} else {
toView.setTranslationX(0.0f);
toView.setTranslationY(0.0f);
toView.setScaleX(1.0f);
toView.setScaleY(1.0f);
toView.setVisibility(View.VISIBLE);
hideAndShowToolbarButtons(toState, null, null);
}
mWorkspace.setVerticalWallpaperOffset(toAllApps ?
Workspace.WallpaperVerticalOffset.TOP : Workspace.WallpaperVerticalOffset.BOTTOM);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "cameraZoomOut" | "private void cameraZoomOut(State toState, boolean animated) {
final Resources res = getResources();
final boolean toAllApps = (toState == State.ALL_APPS);
final int duration = toAllApps ?
res.getInteger(R.integer.config_allAppsZoomInTime) :
res.getInteger(R.integer.config_customizeZoomInTime);
final float scale = toAllApps ?
(float) res.getInteger(R.integer.config_allAppsZoomScaleFactor) :
(float) res.getInteger(R.integer.config_customizeZoomScaleFactor);
final View toView = toAllApps ? (View) mAllAppsGrid : mHomeCustomizationDrawer;
setPivotsForZoom(toView, toState, scale);
if (toAllApps) {
mWorkspace.shrink(ShrinkState.BOTTOM_HIDDEN, animated);
<MASK>toView.setAlpha(0f);</MASK>
} else {
mWorkspace.shrink(ShrinkState.TOP, animated);
}
if (animated) {
ValueAnimator scaleAnim = ObjectAnimator.ofPropertyValuesHolder(toView,
PropertyValuesHolder.ofFloat("scaleX", scale, 1.0f),
PropertyValuesHolder.ofFloat("scaleY", scale, 1.0f));
scaleAnim.setDuration(duration);
if (toAllApps) {
ObjectAnimator alphaAnim = ObjectAnimator.ofPropertyValuesHolder(toView,
PropertyValuesHolder.ofFloat("alpha", 1.0f));
alphaAnim.setInterpolator(new DecelerateInterpolator(1.5f));
alphaAnim.setDuration(duration);
alphaAnim.start();
}
scaleAnim.setInterpolator(new Workspace.ZoomOutInterpolator());
scaleAnim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
// Prepare the position
toView.setTranslationX(0.0f);
toView.setTranslationY(0.0f);
toView.setVisibility(View.VISIBLE);
if (!toAllApps) {
toView.setAlpha(1.0f);
}
}
@Override
public void onAnimationEnd(Animator animation) {
// If we don't set the final scale values here, if this animation is cancelled
// it will have the wrong scale value and subsequent cameraPan animations will
// not fix that
toView.setScaleX(1.0f);
toView.setScaleY(1.0f);
}
});
AnimatorSet toolbarHideAnim = new AnimatorSet();
AnimatorSet toolbarShowAnim = new AnimatorSet();
hideAndShowToolbarButtons(toState, toolbarShowAnim, toolbarHideAnim);
// toView should appear right at the end of the workspace shrink animation
final int startDelay = 0;
if (mStateAnimation != null) mStateAnimation.cancel();
mStateAnimation = new AnimatorSet();
mStateAnimation.playTogether(scaleAnim, toolbarHideAnim);
mStateAnimation.play(scaleAnim).after(startDelay);
// Show the new toolbar buttons just as the main animation is ending
final int fadeInTime = res.getInteger(R.integer.config_toolbarButtonFadeInTime);
mStateAnimation.play(toolbarShowAnim).after(duration + startDelay - fadeInTime);
mStateAnimation.start();
} else {
toView.setTranslationX(0.0f);
toView.setTranslationY(0.0f);
toView.setScaleX(1.0f);
toView.setScaleY(1.0f);
toView.setVisibility(View.VISIBLE);
hideAndShowToolbarButtons(toState, null, null);
}
mWorkspace.setVerticalWallpaperOffset(toAllApps ?
Workspace.WallpaperVerticalOffset.TOP : Workspace.WallpaperVerticalOffset.BOTTOM);
}" |
Inversion-Mutation | megadiff | "public void printTree(){
System.out.println(name + ":" + subTreeString() + "\n");
for(Block b : successors)
{
if(!b.visited){
b.visited = true;
b.printTree();
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "printTree" | "public void printTree(){
System.out.println(name + ":" + subTreeString() + "\n");
for(Block b : successors)
{
if(!b.visited){
b.printTree();
}
<MASK>b.visited = true;</MASK>
}
}" |
Inversion-Mutation | megadiff | "@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
UIHelper.SetTheme(this, null);
super.onCreate(savedInstanceState);
UIHelper.SetActionBarDisplayHomeAsUp(this, true);
activity = this;
//This man is deprecated but but we may want to be able to run on older API
addPreferencesFromResource(R.xml.preferences);
// Screen Orientation
Preference lockHorizontal = (Preference) findPreference(Constants.PREF_LOCK_HORIZONTAL);
lockHorizontal.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference p) {
if(p.getSharedPreferences().getBoolean(Constants.PREF_LOCK_HORIZONTAL, false)){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
return true;
}
});
// Invert Color
Preference invertColors = (Preference) findPreference(Constants.PREF_INVERT_COLOR);
invertColors.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference p) {
UIHelper.Recreate(activity);
return true;
}
});
Preference clearDatabase = (Preference) findPreference("clear_database");
clearDatabase.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference p) {
/*
* CODE TO CLEAR DATABASE HERE
*/
NovelsDao dao = NovelsDao.getInstance(getApplicationContext());
dao.deleteDB();
Toast.makeText(getApplicationContext(), "Database cleared!", Toast.LENGTH_LONG).show();
return true;
}
});
Preference clearImages = (Preference) findPreference("clear_image_cache");
clearImages.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference p) {
/*
* CODE TO CLEAR IMAGE CACHE HERE
*/
DeleteRecursive(new File(Constants.IMAGE_ROOT));
Toast.makeText(getApplicationContext(), "Image cache cleared!", Toast.LENGTH_LONG).show();
return true;
}
});
Preference updatesInterval = (Preference) findPreference("updates_interval");
updatesInterval.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference p) {
MyScheduleReceiver.reschedule(getApplicationContext());
return true;
}
});
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCreate" | "@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
<MASK>UIHelper.SetTheme(this, null);</MASK>
UIHelper.SetActionBarDisplayHomeAsUp(this, true);
activity = this;
//This man is deprecated but but we may want to be able to run on older API
addPreferencesFromResource(R.xml.preferences);
// Screen Orientation
Preference lockHorizontal = (Preference) findPreference(Constants.PREF_LOCK_HORIZONTAL);
lockHorizontal.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference p) {
if(p.getSharedPreferences().getBoolean(Constants.PREF_LOCK_HORIZONTAL, false)){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
return true;
}
});
// Invert Color
Preference invertColors = (Preference) findPreference(Constants.PREF_INVERT_COLOR);
invertColors.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference p) {
UIHelper.Recreate(activity);
return true;
}
});
Preference clearDatabase = (Preference) findPreference("clear_database");
clearDatabase.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference p) {
/*
* CODE TO CLEAR DATABASE HERE
*/
NovelsDao dao = NovelsDao.getInstance(getApplicationContext());
dao.deleteDB();
Toast.makeText(getApplicationContext(), "Database cleared!", Toast.LENGTH_LONG).show();
return true;
}
});
Preference clearImages = (Preference) findPreference("clear_image_cache");
clearImages.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference p) {
/*
* CODE TO CLEAR IMAGE CACHE HERE
*/
DeleteRecursive(new File(Constants.IMAGE_ROOT));
Toast.makeText(getApplicationContext(), "Image cache cleared!", Toast.LENGTH_LONG).show();
return true;
}
});
Preference updatesInterval = (Preference) findPreference("updates_interval");
updatesInterval.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference p) {
MyScheduleReceiver.reschedule(getApplicationContext());
return true;
}
});
}" |
Inversion-Mutation | megadiff | "private boolean checkPing() {
if (mPingCollector != null) {
IQ result = (IQ) mPingCollector.pollResult();
mPingCollector.cancel();
mPingCollector = null;
if (result == null || result.getError() != null) {
Log.e(TAG, "ping timeout");
return false;
}
}
return true;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "checkPing" | "private boolean checkPing() {
if (mPingCollector != null) {
IQ result = (IQ) mPingCollector.pollResult();
mPingCollector.cancel();
if (result == null || result.getError() != null) {
<MASK>mPingCollector = null;</MASK>
Log.e(TAG, "ping timeout");
return false;
}
}
return true;
}" |
Inversion-Mutation | megadiff | "@Override
public void onCreate(Bundle icicle) {
this.mTestPath = (String) icicle.get("path");
String timeout_str = (String) icicle.get("timeout");
if (timeout_str != null) {
try {
this.mTimeoutInMillis = Integer.parseInt(timeout_str);
} catch (Exception e) {
e.printStackTrace();
}
}
String r = (String)icicle.get("rebaseline");
this.mRebaseline = (r != null && r.toLowerCase().equals("true"));
super.onCreate(icicle);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCreate" | "@Override
public void onCreate(Bundle icicle) {
<MASK>super.onCreate(icicle);</MASK>
this.mTestPath = (String) icicle.get("path");
String timeout_str = (String) icicle.get("timeout");
if (timeout_str != null) {
try {
this.mTimeoutInMillis = Integer.parseInt(timeout_str);
} catch (Exception e) {
e.printStackTrace();
}
}
String r = (String)icicle.get("rebaseline");
this.mRebaseline = (r != null && r.toLowerCase().equals("true"));
}" |
Inversion-Mutation | megadiff | "protected AttributedList<Path> listObjects(String bucket, String prefix, String delimiter)
throws IOException, ServiceException {
final AttributedList<Path> children = new AttributedList<Path>();
// Null if listing is complete
String priorLastKey = null;
do {
// Read directory listing in chunks. List results are always returned
// in lexicographic (alphabetical) order.
StorageObjectsChunk chunk = this.getSession().getClient().listObjectsChunked(
bucket, prefix, delimiter,
Preferences.instance().getInteger("s3.listing.chunksize"), priorLastKey);
final StorageObject[] objects = chunk.getObjects();
for(StorageObject object : objects) {
final S3Path p = (S3Path) PathFactory.createPath(this.getSession(), bucket,
object.getKey(), Path.FILE_TYPE);
if(!p.isChild(this)) {
// #Workaround for key that end with /. Refer to #3347.
log.warn("Skipping object " + object.getKey());
continue;
}
p.setParent(this);
p.attributes().setSize(object.getContentLength());
p.attributes().setModificationDate(object.getLastModifiedDate().getTime());
p.attributes().setOwner(this.getContainer().attributes().getOwner());
if(0 == object.getContentLength()) {
final StorageObject details = p.getDetails();
if(Mimetypes.MIMETYPE_JETS3T_DIRECTORY.equals(details.getContentType())) {
p.attributes().setType(Path.DIRECTORY_TYPE);
p.attributes().setPlaceholder(true);
}
}
p.attributes().setStorageClass(object.getStorageClass());
if(object instanceof S3Object) {
p.attributes().setVersionId(((S3Object) object).getVersionId());
}
children.add(p);
}
final String[] prefixes = chunk.getCommonPrefixes();
for(String common : prefixes) {
if(common.equals(String.valueOf(Path.DELIMITER))) {
log.warn("Skipping prefix " + common);
continue;
}
final Path p = PathFactory.createPath(this.getSession(),
bucket, common, Path.DIRECTORY_TYPE);
p.setParent(this);
if(children.contains(p.getReference())) {
continue;
}
p.attributes().setOwner(this.getContainer().attributes().getOwner());
children.add(p);
}
priorLastKey = chunk.getPriorLastKey();
}
while(priorLastKey != null && !status().isCanceled());
return children;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "listObjects" | "protected AttributedList<Path> listObjects(String bucket, String prefix, String delimiter)
throws IOException, ServiceException {
final AttributedList<Path> children = new AttributedList<Path>();
// Null if listing is complete
String priorLastKey = null;
do {
// Read directory listing in chunks. List results are always returned
// in lexicographic (alphabetical) order.
StorageObjectsChunk chunk = this.getSession().getClient().listObjectsChunked(
bucket, prefix, delimiter,
Preferences.instance().getInteger("s3.listing.chunksize"), priorLastKey);
final StorageObject[] objects = chunk.getObjects();
for(StorageObject object : objects) {
final S3Path p = (S3Path) PathFactory.createPath(this.getSession(), bucket,
object.getKey(), Path.FILE_TYPE);
<MASK>p.setParent(this);</MASK>
if(!p.isChild(this)) {
// #Workaround for key that end with /. Refer to #3347.
log.warn("Skipping object " + object.getKey());
continue;
}
p.attributes().setSize(object.getContentLength());
p.attributes().setModificationDate(object.getLastModifiedDate().getTime());
p.attributes().setOwner(this.getContainer().attributes().getOwner());
if(0 == object.getContentLength()) {
final StorageObject details = p.getDetails();
if(Mimetypes.MIMETYPE_JETS3T_DIRECTORY.equals(details.getContentType())) {
p.attributes().setType(Path.DIRECTORY_TYPE);
p.attributes().setPlaceholder(true);
}
}
p.attributes().setStorageClass(object.getStorageClass());
if(object instanceof S3Object) {
p.attributes().setVersionId(((S3Object) object).getVersionId());
}
children.add(p);
}
final String[] prefixes = chunk.getCommonPrefixes();
for(String common : prefixes) {
if(common.equals(String.valueOf(Path.DELIMITER))) {
log.warn("Skipping prefix " + common);
continue;
}
final Path p = PathFactory.createPath(this.getSession(),
bucket, common, Path.DIRECTORY_TYPE);
<MASK>p.setParent(this);</MASK>
if(children.contains(p.getReference())) {
continue;
}
p.attributes().setOwner(this.getContainer().attributes().getOwner());
children.add(p);
}
priorLastKey = chunk.getPriorLastKey();
}
while(priorLastKey != null && !status().isCanceled());
return children;
}" |
Inversion-Mutation | megadiff | "@Override public void writeTo(final DataOutput out) throws IOException {
super.writeTo(out);
out.writeInt(numDocs);
out.writeInt(maxDoc);
out.writeInt(numDeletedDocs);
out.writeInt(fieldsTermsFreqs.size());
for (Map.Entry<String, TObjectIntHashMap<String>> entry : fieldsTermsFreqs.entrySet()) {
out.writeUTF(entry.getKey());
out.writeInt(entry.getValue().size());
for (TObjectIntIterator<String> it = entry.getValue().iterator(); it.hasNext();) {
it.advance();
out.writeUTF(it.key());
out.writeInt(it.value());
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "writeTo" | "@Override public void writeTo(final DataOutput out) throws IOException {
super.writeTo(out);
out.writeInt(numDocs);
out.writeInt(maxDoc);
out.writeInt(numDeletedDocs);
out.writeInt(fieldsTermsFreqs.size());
for (Map.Entry<String, TObjectIntHashMap<String>> entry : fieldsTermsFreqs.entrySet()) {
out.writeUTF(entry.getKey());
out.writeInt(entry.getValue().size());
for (TObjectIntIterator<String> it = entry.getValue().iterator(); it.hasNext();) {
out.writeUTF(it.key());
out.writeInt(it.value());
<MASK>it.advance();</MASK>
}
}
}" |
Inversion-Mutation | megadiff | "private boolean expr2()
{
CLexer.TokenTypeEnum currToken;
double dblValue;
currToken = CLexer.TokenTypeEnum.T_EOL;
currToken = m_Lexer.m_currToken.Type;
if ( m_Lexer.m_currToken.Type == CLexer.TokenTypeEnum.T_UMINUS )
{
m_Lexer.GetNextToken();
}
if ( !expr3() )
return false;
if ( currToken == CLexer.TokenTypeEnum.T_UMINUS )
{
dblValue = m_stack[m_top--];
dblValue *= -1;
m_stack[++m_top] = dblValue;
}
return true;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "expr2" | "private boolean expr2()
{
CLexer.TokenTypeEnum currToken;
double dblValue;
currToken = CLexer.TokenTypeEnum.T_EOL;
if ( m_Lexer.m_currToken.Type == CLexer.TokenTypeEnum.T_UMINUS )
{
<MASK>currToken = m_Lexer.m_currToken.Type;</MASK>
m_Lexer.GetNextToken();
}
if ( !expr3() )
return false;
if ( currToken == CLexer.TokenTypeEnum.T_UMINUS )
{
dblValue = m_stack[m_top--];
dblValue *= -1;
m_stack[++m_top] = dblValue;
}
return true;
}" |
Inversion-Mutation | megadiff | "private static void testStatementRemembersTimeout(Statement stmt)
throws SQLException, TestFailedException
{
System.out.println("Testing that Statement remembers timeout.");
stmt.setQueryTimeout(1);
long runTime=0;
for (int i = 0; i < 3; i++) {
try {
long startTime = System.currentTimeMillis();
ResultSet rs = stmt.executeQuery(getFetchQuery("t"));
while (rs.next());
long endTime = System.currentTimeMillis();
runTime = endTime - startTime;
throw new TestFailedException("Should have timed out, for " +
"statement, iteration: " +i+ ", took (millis): "+runTime);
} catch (SQLException sqle) {
expectException("XCL52", sqle, "Should have timed out, got " +
"unexpected exception, for statement, iteration: " + i +
", time taken (millis): " + runTime);
}
}
stmt.close();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "testStatementRemembersTimeout" | "private static void testStatementRemembersTimeout(Statement stmt)
throws SQLException, TestFailedException
{
System.out.println("Testing that Statement remembers timeout.");
stmt.setQueryTimeout(1);
long runTime=0;
for (int i = 0; i < 3; i++) {
try {
<MASK>ResultSet rs = stmt.executeQuery(getFetchQuery("t"));</MASK>
long startTime = System.currentTimeMillis();
while (rs.next());
long endTime = System.currentTimeMillis();
runTime = endTime - startTime;
throw new TestFailedException("Should have timed out, for " +
"statement, iteration: " +i+ ", took (millis): "+runTime);
} catch (SQLException sqle) {
expectException("XCL52", sqle, "Should have timed out, got " +
"unexpected exception, for statement, iteration: " + i +
", time taken (millis): " + runTime);
}
}
stmt.close();
}" |
Inversion-Mutation | megadiff | "private void byeHandler(ByeMessage message) {
Host host = this.getOrCreateHost(message.getSource().getAddress());
if (host.getPort() != Host.UNKNOWN_PORT) {
RemoteShare tmp;
if (this.guiCallbacks != null) {
this.guiCallbacks.hostWentOffline(host);
}
for (String hash : host.getSharedFiles().keySet()) {
tmp = this.knownShares.get(hash);
tmp.removeFileSource(host.getSharedFiles().get(hash));
if (tmp.noSourcesAvailable()) {
this.knownShares.remove(hash);
}
}
this.knownHosts.remove(host.getAddress());
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "byeHandler" | "private void byeHandler(ByeMessage message) {
Host host = this.getOrCreateHost(message.getSource().getAddress());
if (host.getPort() != Host.UNKNOWN_PORT) {
RemoteShare tmp;
if (this.guiCallbacks != null) {
this.guiCallbacks.hostWentOffline(host);
}
for (String hash : host.getSharedFiles().keySet()) {
tmp = this.knownShares.get(hash);
tmp.removeFileSource(host.getSharedFiles().get(hash));
if (tmp.noSourcesAvailable()) {
this.knownShares.remove(hash);
}
<MASK>this.knownHosts.remove(host.getAddress());</MASK>
}
}
}" |
Inversion-Mutation | megadiff | "private void updateDetails() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
details.clear();
if (error == null) {
id.setText("");
date.setText("");
level.setText("");
status.setText("");
return;
}
id.setText(String.valueOf(error.getID()));
date.setText(error.getDate().toString());
level.setText(error.getLevel().toString());
status.setText(error.getStatus().toString());
details.addText(new AttributedString(error.getMessage()));
final String[] trace = error.getTrace();
for (String traceLine : trace) {
details.addText(new AttributedString(traceLine));
}
details.setScrollBarPosition(0);
}
});
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "updateDetails" | "private void updateDetails() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (error == null) {
id.setText("");
date.setText("");
level.setText("");
status.setText("");
<MASK>details.clear();</MASK>
return;
}
id.setText(String.valueOf(error.getID()));
date.setText(error.getDate().toString());
level.setText(error.getLevel().toString());
status.setText(error.getStatus().toString());
details.addText(new AttributedString(error.getMessage()));
final String[] trace = error.getTrace();
for (String traceLine : trace) {
details.addText(new AttributedString(traceLine));
}
details.setScrollBarPosition(0);
}
});
}" |
Inversion-Mutation | megadiff | "public void run() {
details.clear();
if (error == null) {
id.setText("");
date.setText("");
level.setText("");
status.setText("");
return;
}
id.setText(String.valueOf(error.getID()));
date.setText(error.getDate().toString());
level.setText(error.getLevel().toString());
status.setText(error.getStatus().toString());
details.addText(new AttributedString(error.getMessage()));
final String[] trace = error.getTrace();
for (String traceLine : trace) {
details.addText(new AttributedString(traceLine));
}
details.setScrollBarPosition(0);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run" | "public void run() {
if (error == null) {
id.setText("");
date.setText("");
level.setText("");
status.setText("");
<MASK>details.clear();</MASK>
return;
}
id.setText(String.valueOf(error.getID()));
date.setText(error.getDate().toString());
level.setText(error.getLevel().toString());
status.setText(error.getStatus().toString());
details.addText(new AttributedString(error.getMessage()));
final String[] trace = error.getTrace();
for (String traceLine : trace) {
details.addText(new AttributedString(traceLine));
}
details.setScrollBarPosition(0);
}" |
Inversion-Mutation | megadiff | "public double convert() throws IllegalStateException, IOException, JSONException {
if (isOnline()) {
// Checking if we have a copy of the exchange rates yet, or if they
// are old
if (exRatesMap == null || exRatesMap.isEmpty()
|| ((int) (System.currentTimeMillis() / 1000L) - prefs.getLong("timestamp", (System.currentTimeMillis() / 1000L))) > updateFreq) {
getExchangeRates();
}
}
cDB.open();
// Lets convert that stuff!
if ((exRatesMap = cDB.getAllCurrencies()) != null && !exRatesMap.isEmpty()) {
cDB.close();
return convertFromSavedEx();
}
// No internet and no saved rates = no currency convertion possible :(
else {
cDB.close();
throw new IOException("No internet or saved exchange rates!");
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "convert" | "public double convert() throws IllegalStateException, IOException, JSONException {
<MASK>cDB.open();</MASK>
if (isOnline()) {
// Checking if we have a copy of the exchange rates yet, or if they
// are old
if (exRatesMap == null || exRatesMap.isEmpty()
|| ((int) (System.currentTimeMillis() / 1000L) - prefs.getLong("timestamp", (System.currentTimeMillis() / 1000L))) > updateFreq) {
getExchangeRates();
}
}
// Lets convert that stuff!
if ((exRatesMap = cDB.getAllCurrencies()) != null && !exRatesMap.isEmpty()) {
cDB.close();
return convertFromSavedEx();
}
// No internet and no saved rates = no currency convertion possible :(
else {
cDB.close();
throw new IOException("No internet or saved exchange rates!");
}
}" |
Inversion-Mutation | megadiff | "private DownloadImagesTaskResult processImages() throws DownloadTaskException {
List<TestbedMapImage> testbedMapImages = MainApplication.getTestbedParsedPage().getAllTestbedImages();
int totalImagesNotDownloaded = MainApplication.getTestbedParsedPage().getNotDownloadedCount();
int i= 1;
for(TestbedMapImage image : testbedMapImages) {
if (!image.hasBitmapDataDownloaded()) {
String progressText = activity.getString(R.string.progress_anim_downloading,
i, totalImagesNotDownloaded);
this.activity.updateDownloadProgressInfo(progressText);
i++;
}
if (isAbort()) {
doCancel();
return null;
}
image.downloadAndCacheImage();
}
return new DownloadImagesTaskResult(TaskResultType.OK, "All images downloaded");
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "processImages" | "private DownloadImagesTaskResult processImages() throws DownloadTaskException {
List<TestbedMapImage> testbedMapImages = MainApplication.getTestbedParsedPage().getAllTestbedImages();
int totalImagesNotDownloaded = MainApplication.getTestbedParsedPage().getNotDownloadedCount();
int i= 1;
for(TestbedMapImage image : testbedMapImages) {
if (!image.hasBitmapDataDownloaded()) {
String progressText = activity.getString(R.string.progress_anim_downloading,
i, totalImagesNotDownloaded);
this.activity.updateDownloadProgressInfo(progressText);
}
if (isAbort()) {
doCancel();
return null;
}
image.downloadAndCacheImage();
<MASK>i++;</MASK>
}
return new DownloadImagesTaskResult(TaskResultType.OK, "All images downloaded");
}" |
Inversion-Mutation | megadiff | "@Override
protected void onCreate( Bundle savedInstanceState )
{
super.onCreate( savedInstanceState );
setContentView( R.layout.section_read_view );
setupPresenter();
}" | 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 );
<MASK>setupPresenter();</MASK>
setContentView( R.layout.section_read_view );
}" |
Inversion-Mutation | megadiff | "public void updateContact(TransportBuddy contact) {
RosterEntry user2Update;
String mail = getTransport().convertJIDToID(contact.getJID());
user2Update = conn.getRoster().getEntry(mail);
user2Update.setName(contact.getNickname());
Collection<String> newgroups = contact.getGroups();
if (newgroups == null) {
newgroups = new ArrayList<String>();
}
for (RosterGroup group : conn.getRoster().getGroups()) {
if (newgroups.contains(group.getName())) {
if (!group.contains(user2Update)) {
try {
group.addEntry(user2Update);
}
catch (XMPPException e) {
Log.debug("XMPP: Unable to add roster item to group.");
}
newgroups.remove(group.getName());
}
}
else {
if (group.contains(user2Update)) {
try {
group.removeEntry(user2Update);
}
catch (XMPPException e) {
Log.debug("XMPP: Unable to delete roster item from group.");
}
}
}
}
for (String group : newgroups) {
RosterGroup newgroup = conn.getRoster().createGroup(group);
try {
newgroup.addEntry(user2Update);
}
catch (XMPPException e) {
Log.debug("XMPP: Unable to add roster item to new group.");
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "updateContact" | "public void updateContact(TransportBuddy contact) {
RosterEntry user2Update;
String mail = getTransport().convertJIDToID(contact.getJID());
user2Update = conn.getRoster().getEntry(mail);
user2Update.setName(contact.getNickname());
Collection<String> newgroups = contact.getGroups();
if (newgroups == null) {
newgroups = new ArrayList<String>();
}
for (RosterGroup group : conn.getRoster().getGroups()) {
if (newgroups.contains(group.getName())) {
if (!group.contains(user2Update)) {
try {
group.addEntry(user2Update);
<MASK>newgroups.remove(group.getName());</MASK>
}
catch (XMPPException e) {
Log.debug("XMPP: Unable to add roster item to group.");
}
}
}
else {
if (group.contains(user2Update)) {
try {
group.removeEntry(user2Update);
}
catch (XMPPException e) {
Log.debug("XMPP: Unable to delete roster item from group.");
}
}
}
}
for (String group : newgroups) {
RosterGroup newgroup = conn.getRoster().createGroup(group);
try {
newgroup.addEntry(user2Update);
}
catch (XMPPException e) {
Log.debug("XMPP: Unable to add roster item to new group.");
}
}
}" |
Inversion-Mutation | megadiff | "public int forwardRemotePort(String fwdAddress, int fwdPort, IProgressMonitor monitor) throws RemoteConnectionException {
if (!isOpen()) {
throw new RemoteConnectionException(Messages.RemoteToolsConnection_connectionNotOpen);
}
SubMonitor progress = SubMonitor.convert(monitor, 10);
try {
progress.beginTask(Messages.RemoteToolsConnection_forwarding, 10);
/*
* Start with a different port number, in case we're doing this all
* on localhost.
*/
int remotePort = fwdPort + 1;
/*
* Try to find a free port on the remote machine. This take a while,
* so allow it to be canceled. If we've tried all ports (which could
* take a very long while) then bail out.
*/
while (!progress.isCanceled()) {
try {
forwardRemotePort(remotePort, fwdAddress, fwdPort);
return remotePort;
} catch (AddressInUseException e) {
if (++remotePort == fwdPort) {
throw new UnableToForwardPortException(Messages.RemoteToolsConnection_remotePort);
}
progress.worked(1);
}
}
return -1;
} finally {
if (monitor != null) {
monitor.done();
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "forwardRemotePort" | "public int forwardRemotePort(String fwdAddress, int fwdPort, IProgressMonitor monitor) throws RemoteConnectionException {
if (!isOpen()) {
throw new RemoteConnectionException(Messages.RemoteToolsConnection_connectionNotOpen);
}
SubMonitor progress = SubMonitor.convert(monitor, 10);
try {
progress.beginTask(Messages.RemoteToolsConnection_forwarding, 10);
/*
* Start with a different port number, in case we're doing this all
* on localhost.
*/
int remotePort = fwdPort + 1;
/*
* Try to find a free port on the remote machine. This take a while,
* so allow it to be canceled. If we've tried all ports (which could
* take a very long while) then bail out.
*/
while (!progress.isCanceled()) {
try {
forwardRemotePort(remotePort, fwdAddress, fwdPort);
} catch (AddressInUseException e) {
if (++remotePort == fwdPort) {
throw new UnableToForwardPortException(Messages.RemoteToolsConnection_remotePort);
}
progress.worked(1);
}
<MASK>return remotePort;</MASK>
}
return -1;
} finally {
if (monitor != null) {
monitor.done();
}
}
}" |
Inversion-Mutation | megadiff | "public void popupDismissed(boolean topPopupOnly) {
initializePopup();
// if the 2nd level popup gets dismissed
if (mPopupStatus == POPUP_SECOND_LEVEL) {
mPopupStatus = POPUP_FIRST_LEVEL;
if (topPopupOnly) mUI.showPopup(mPopup);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "popupDismissed" | "public void popupDismissed(boolean topPopupOnly) {
// if the 2nd level popup gets dismissed
if (mPopupStatus == POPUP_SECOND_LEVEL) {
<MASK>initializePopup();</MASK>
mPopupStatus = POPUP_FIRST_LEVEL;
if (topPopupOnly) mUI.showPopup(mPopup);
}
}" |
Inversion-Mutation | megadiff | "public void dispose() {
if (dataSource.isEditable()) {
try {
dataSource.removeEditionListener(dataSourceListener);
dataSource.removeMetadataEditionListener(dataSourceListener);
} catch (UnsupportedOperationException ex) {
// Ignore
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "dispose" | "public void dispose() {
<MASK>dataSource.removeEditionListener(dataSourceListener);</MASK>
if (dataSource.isEditable()) {
try {
dataSource.removeMetadataEditionListener(dataSourceListener);
} catch (UnsupportedOperationException ex) {
// Ignore
}
}
}" |
Inversion-Mutation | megadiff | "@Override
public ActionForward execute(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
HttpServletResponse response, User user) throws Exception {
request.setAttribute("myGames", findGamesForUser(user));
request.setAttribute("game", user.getActiveGame());
Board board = null;
if(user.getActiveGame() != null) {
board = new Board();
board.populateDetails(user.getActiveGame());
MoveProcessor.processMoves(board, user.getActiveGame().getMoves());
board.preMove(); //upkeep stuff before player makes a move
request.setAttribute("board", board);
}
return mapping.findForward("view");
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "execute" | "@Override
public ActionForward execute(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
HttpServletResponse response, User user) throws Exception {
request.setAttribute("myGames", findGamesForUser(user));
request.setAttribute("game", user.getActiveGame());
Board board = null;
if(user.getActiveGame() != null) {
board = new Board();
board.populateDetails(user.getActiveGame());
MoveProcessor.processMoves(board, user.getActiveGame().getMoves());
request.setAttribute("board", board);
}
<MASK>board.preMove(); //upkeep stuff before player makes a move</MASK>
return mapping.findForward("view");
}" |
Inversion-Mutation | megadiff | "private void addTemporaryWallpaperTile(Uri uri) {
mTempWallpaperTiles.add(uri);
// Add a tile for the image picked from Gallery
FrameLayout pickedImageThumbnail = (FrameLayout) getLayoutInflater().
inflate(R.layout.wallpaper_picker_item, mWallpapersView, false);
setWallpaperItemPaddingToZero(pickedImageThumbnail);
// Load the thumbnail
ImageView image = (ImageView) pickedImageThumbnail.findViewById(R.id.wallpaper_image);
Point defaultSize = getDefaultThumbnailSize(this.getResources());
Bitmap thumb = createThumbnail(defaultSize, this, uri, null, null, 0, false);
if (thumb != null) {
image.setImageBitmap(thumb);
Drawable thumbDrawable = image.getDrawable();
thumbDrawable.setDither(true);
} else {
Log.e(TAG, "Error loading thumbnail for uri=" + uri);
}
mWallpapersView.addView(pickedImageThumbnail, 0);
UriWallpaperInfo info = new UriWallpaperInfo(uri);
pickedImageThumbnail.setTag(info);
info.setView(pickedImageThumbnail);
updateTileIndices();
pickedImageThumbnail.setOnClickListener(mThumbnailOnClickListener);
mThumbnailOnClickListener.onClick(pickedImageThumbnail);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addTemporaryWallpaperTile" | "private void addTemporaryWallpaperTile(Uri uri) {
mTempWallpaperTiles.add(uri);
// Add a tile for the image picked from Gallery
FrameLayout pickedImageThumbnail = (FrameLayout) getLayoutInflater().
inflate(R.layout.wallpaper_picker_item, mWallpapersView, false);
setWallpaperItemPaddingToZero(pickedImageThumbnail);
// Load the thumbnail
ImageView image = (ImageView) pickedImageThumbnail.findViewById(R.id.wallpaper_image);
Point defaultSize = getDefaultThumbnailSize(this.getResources());
Bitmap thumb = createThumbnail(defaultSize, this, uri, null, null, 0, false);
if (thumb != null) {
image.setImageBitmap(thumb);
Drawable thumbDrawable = image.getDrawable();
thumbDrawable.setDither(true);
} else {
Log.e(TAG, "Error loading thumbnail for uri=" + uri);
}
mWallpapersView.addView(pickedImageThumbnail, 0);
<MASK>updateTileIndices();</MASK>
UriWallpaperInfo info = new UriWallpaperInfo(uri);
pickedImageThumbnail.setTag(info);
info.setView(pickedImageThumbnail);
pickedImageThumbnail.setOnClickListener(mThumbnailOnClickListener);
mThumbnailOnClickListener.onClick(pickedImageThumbnail);
}" |
Inversion-Mutation | megadiff | "@Override
public boolean onTouch(View v, MotionEvent event) {
if (mIsAnswering) {
return true;
}
if (gestureDetector.onTouchEvent(event)) {
return true;
}
if (mPrefTextSelection && !mLongClickWorkaround) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mTouchStarted = true;
longClickHandler.postDelayed(longClickTestRunnable, 800);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_MOVE:
if(mTouchStarted) {
longClickHandler.removeCallbacks(longClickTestRunnable);
mTouchStarted = false;
}
break;
}
}
try {
if (event != null) {
mCard.dispatchTouchEvent(event);
}
} catch (NullPointerException e) {
Log.e(AnkiDroidApp.TAG, "Error on dispatching touch event: " + e);
if (mInputWorkaround) {
Log.e(AnkiDroidApp.TAG, "Error on using InputWorkaround: " + e + " --> disabled");
PrefSettings.getSharedPrefs(getBaseContext()).edit().putBoolean("inputWorkaround", false).commit();
finish();
}
}
return false;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onTouch" | "@Override
public boolean onTouch(View v, MotionEvent event) {
if (mIsAnswering) {
return true;
}
if (gestureDetector.onTouchEvent(event)) {
return true;
}
if (mPrefTextSelection && !mLongClickWorkaround) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mTouchStarted = true;
longClickHandler.postDelayed(longClickTestRunnable, 800);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_MOVE:
if(mTouchStarted) {
longClickHandler.removeCallbacks(longClickTestRunnable);
mTouchStarted = false;
}
break;
}
}
try {
if (event != null) {
mCard.dispatchTouchEvent(event);
}
} catch (NullPointerException e) {
Log.e(AnkiDroidApp.TAG, "Error on dispatching touch event: " + e);
if (mInputWorkaround) {
Log.e(AnkiDroidApp.TAG, "Error on using InputWorkaround: " + e + " --> disabled");
PrefSettings.getSharedPrefs(getBaseContext()).edit().putBoolean("inputWorkaround", false).commit();
}
<MASK>finish();</MASK>
}
return false;
}" |
Inversion-Mutation | megadiff | "public static CharSequence scrape(final String url, final boolean isPost, final String request, String encoding, final boolean cookieHandling)
throws IOException
{
if (encoding == null)
encoding = SCRAPE_DEFAULT_ENCODING;
int tries = 3;
while (true)
{
try
{
final StringBuilder buffer = new StringBuilder(SCRAPE_INITIAL_CAPACITY);
final HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setDoInput(true);
connection.setDoOutput(request != null);
connection.setConnectTimeout(SCRAPE_CONNECT_TIMEOUT);
connection.setReadTimeout(SCRAPE_READ_TIMEOUT);
connection.addRequestProperty("User-Agent", SCRAPE_USER_AGENT);
// workaround to disable Vodafone compression
connection.addRequestProperty("Cache-Control", "no-cache");
if (cookieHandling && stateCookie != null)
{
connection.addRequestProperty("Cookie", stateCookie);
}
if (request != null)
{
if (isPost)
{
connection.setRequestMethod("POST");
connection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.addRequestProperty("Content-Length", Integer.toString(request.length()));
}
final Writer writer = new OutputStreamWriter(connection.getOutputStream(), encoding);
writer.write(request);
writer.close();
}
final Reader pageReader = new InputStreamReader(connection.getInputStream(), encoding);
copy(pageReader, buffer);
pageReader.close();
if (buffer.length() > 0)
{
if (cookieHandling)
{
for (final Map.Entry<String, List<String>> entry : connection.getHeaderFields().entrySet())
{
if (entry.getKey().equalsIgnoreCase("set-cookie"))
{
for (final String value : entry.getValue())
{
if (value.startsWith("NSC_"))
{
stateCookie = value.split(";", 2)[0];
}
}
}
}
}
return buffer;
}
else
{
if (tries-- > 0)
System.out.println("got empty page, retrying...");
else
throw new IOException("got empty page: " + url);
}
}
catch (final SocketTimeoutException x)
{
if (tries-- > 0)
System.out.println("socket timed out, retrying...");
else
throw x;
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "scrape" | "public static CharSequence scrape(final String url, final boolean isPost, final String request, String encoding, final boolean cookieHandling)
throws IOException
{
if (encoding == null)
encoding = SCRAPE_DEFAULT_ENCODING;
<MASK>final StringBuilder buffer = new StringBuilder(SCRAPE_INITIAL_CAPACITY);</MASK>
int tries = 3;
while (true)
{
try
{
final HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setDoInput(true);
connection.setDoOutput(request != null);
connection.setConnectTimeout(SCRAPE_CONNECT_TIMEOUT);
connection.setReadTimeout(SCRAPE_READ_TIMEOUT);
connection.addRequestProperty("User-Agent", SCRAPE_USER_AGENT);
// workaround to disable Vodafone compression
connection.addRequestProperty("Cache-Control", "no-cache");
if (cookieHandling && stateCookie != null)
{
connection.addRequestProperty("Cookie", stateCookie);
}
if (request != null)
{
if (isPost)
{
connection.setRequestMethod("POST");
connection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.addRequestProperty("Content-Length", Integer.toString(request.length()));
}
final Writer writer = new OutputStreamWriter(connection.getOutputStream(), encoding);
writer.write(request);
writer.close();
}
final Reader pageReader = new InputStreamReader(connection.getInputStream(), encoding);
copy(pageReader, buffer);
pageReader.close();
if (buffer.length() > 0)
{
if (cookieHandling)
{
for (final Map.Entry<String, List<String>> entry : connection.getHeaderFields().entrySet())
{
if (entry.getKey().equalsIgnoreCase("set-cookie"))
{
for (final String value : entry.getValue())
{
if (value.startsWith("NSC_"))
{
stateCookie = value.split(";", 2)[0];
}
}
}
}
}
return buffer;
}
else
{
if (tries-- > 0)
System.out.println("got empty page, retrying...");
else
throw new IOException("got empty page: " + url);
}
}
catch (final SocketTimeoutException x)
{
if (tries-- > 0)
System.out.println("socket timed out, retrying...");
else
throw x;
}
}
}" |
Inversion-Mutation | megadiff | "public static void establishMidiBridge(BluetoothMidiService service, BluetoothSppObserver observer) throws IOException {
BluetoothMidiBridge bridge = new BluetoothMidiBridge(service, observer);
service.init(bridge);
PdBase.setMidiReceiver(bridge);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "establishMidiBridge" | "public static void establishMidiBridge(BluetoothMidiService service, BluetoothSppObserver observer) throws IOException {
BluetoothMidiBridge bridge = new BluetoothMidiBridge(service, observer);
<MASK>PdBase.setMidiReceiver(bridge);</MASK>
service.init(bridge);
}" |
Inversion-Mutation | megadiff | "public static boolean parseTrackLine(String nextLine, TrackProperties trackProperties)
throws NumberFormatException {
boolean foundProperties = false;
try {
// track type=wiggle_0 name="CSF +" description="CSF +" visibility=full autoScale=off viewLimits=-50:50
List<String> tokens = StringUtils.breakQuotedString(nextLine, ' ');
for (String pair : tokens) {
List<String> kv = StringUtils.breakQuotedString(pair, '=');
if (kv.size() == 2) {
foundProperties = true;
String key = kv.get(0).toLowerCase().trim();
String value = kv.get(1).replaceAll("\"", "");
if (key.equals("coords")) {
if (value.equals("0")) {
trackProperties.setBaseCoord(TrackProperties.BaseCoord.ZERO);
} else if (value.equals("1")) {
trackProperties.setBaseCoord(TrackProperties.BaseCoord.ONE);
}
}
if (key.equals("name")) {
trackProperties.setName(value);
//dhmay adding name check for TopHat junctions files. graphType is also checked.
if (value.equals("junctions")) {
trackProperties.setRendererClass(SpliceJunctionRenderer.class);
trackProperties.setHeight(60);
}
} else if (key.equals("description")) {
trackProperties.setDescription(value);
} else if (key.equals("itemrgb")) {
trackProperties.setItemRGB(value.toLowerCase().equals("on"));
} else if (key.equals("usescore")) {
trackProperties.setUseScore(value.equals("1"));
} else if (key.equals("color")) {
Color color = ColorUtilities.convertRGBStringToColor(value);
trackProperties.setColor(color);
} else if (key.equals("altcolor")) {
Color color = ColorUtilities.convertRGBStringToColor(value);
trackProperties.setAltColor(color);
} else if (key.equals("midcolor")) {
Color color = ColorUtilities.convertRGBStringToColor(value);
trackProperties.setMidColor(color);
} else if (key.equals("autoscale")) {
boolean autoscale = value.equals("on");
trackProperties.setAutoScale(autoscale);
} else if (key.equals("maxheightpixels")) {
// Ignore the min and max
String[] maxDefMin = value.split(":");
trackProperties.setMinHeight(Integer.parseInt(maxDefMin[1].trim()));
trackProperties.setHeight(Integer.parseInt(maxDefMin[0].trim()));
} else if (key.equals("url")) {
trackProperties.setUrl(value);
} else if (key.equals("graphtype")) {
if (value.equals("bar")) {
trackProperties.setRendererClass(BarChartRenderer.class);
} else if (value.equals("points")) {
trackProperties.setRendererClass(ScatterplotRenderer.class);
} else if (value.equals("line")) {
trackProperties.setRendererClass(LineplotRenderer.class);
} else if (value.equals("heatmap")) {
trackProperties.setRendererClass(HeatmapRenderer.class);
} else if (value.equals("junctions")) {
//dhmay adding check for graphType=junction. name is also checked
trackProperties.setRendererClass(SpliceJunctionRenderer.class);
}
} else if (key.toLowerCase().equals("viewlimits")) {
String[] limits = value.split(":");
if (limits.length == 2) {
try {
float min = Float.parseFloat(limits[0].trim());
float max = Float.parseFloat(limits[1].trim());
trackProperties.setMinValue(min);
trackProperties.setMaxValue(max);
} catch (NumberFormatException e) {
log.error("viewLimits values must be numeric: " + value);
}
}
} else if (key.equals("midrange")) {
String[] limits = value.split(":");
if (limits.length == 2) {
try {
float from = Float.parseFloat(limits[0].trim());
float to = Float.parseFloat(limits[1].trim());
trackProperties.setNeutralFromValue(from);
trackProperties.setNeutralToValue(to);
} catch (NumberFormatException e) {
log.error("midrange values must be numeric: " + value);
}
}
} else if (key.equals("ylinemark")) {
try {
float midValue = Float.parseFloat(value);
trackProperties.setMidValue(midValue);
} catch (NumberFormatException e) {
log.error("Number format exception in track line (ylinemark): " + nextLine);
}
} else if (key.equals("ylineonoff")) {
trackProperties.setDrawMidValue(value.equals("on"));
} else if (key.equals("windowingfunction")) {
if (value.equals("maximum")) {
trackProperties.setWindowingFunction(WindowFunction.max);
} else if (value.equals("minimum")) {
trackProperties.setWindowingFunction(WindowFunction.min);
} else if (value.equals("mean")) {
trackProperties.setWindowingFunction(WindowFunction.mean);
} else if (value.equals("median")) {
trackProperties.setWindowingFunction(WindowFunction.median);
} else if (value.equals("percentile10")) {
trackProperties.setWindowingFunction(WindowFunction.percentile10);
} else if (value.equals("percentile90")) {
trackProperties.setWindowingFunction(WindowFunction.percentile90);
}
} else if(key.equals("maxfeaturewindow") || key.equals("featurevisibilitywindow")) {
// These options are deprecated. Use visibilityWindow
try {
int windowSize = Integer.parseInt(value);
trackProperties.setFeatureVisibilityWindow(windowSize);
} catch (NumberFormatException e) {
log.error("featureVisibilityWindow must be numeric: " + nextLine);
}
} else if(key.equals("visibilitywindow")) {
try {
int windowSize = Integer.parseInt(value) * 1000;
trackProperties.setFeatureVisibilityWindow(windowSize);
} catch (NumberFormatException e) {
log.error("featureVisibilityWindow must be an integer: " + nextLine);
}
}
else if(key.equals("scaletype")) {
if(value.equals("log")) {
trackProperties.setLogScale(true);
}
}
}
}
}
catch (
Exception exception
)
{
MessageUtils.showMessage("Error parsing track line: " + nextLine + " (" + exception.getMessage() + ")");
}
return foundProperties;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "parseTrackLine" | "public static boolean parseTrackLine(String nextLine, TrackProperties trackProperties)
throws NumberFormatException {
boolean foundProperties = false;
try {
// track type=wiggle_0 name="CSF +" description="CSF +" visibility=full autoScale=off viewLimits=-50:50
List<String> tokens = StringUtils.breakQuotedString(nextLine, ' ');
for (String pair : tokens) {
List<String> kv = StringUtils.breakQuotedString(pair, '=');
if (kv.size() == 2) {
foundProperties = true;
String key = kv.get(0).toLowerCase().trim();
String value = kv.get(1).replaceAll("\"", "");
if (key.equals("coords")) {
if (value.equals("0")) {
trackProperties.setBaseCoord(TrackProperties.BaseCoord.ZERO);
} else if (value.equals("1")) {
trackProperties.setBaseCoord(TrackProperties.BaseCoord.ONE);
}
}
if (key.equals("name")) {
trackProperties.setName(value);
//dhmay adding name check for TopHat junctions files. graphType is also checked.
if (value.equals("junctions")) {
trackProperties.setRendererClass(SpliceJunctionRenderer.class);
trackProperties.setHeight(60);
}
} else if (key.equals("description")) {
trackProperties.setDescription(value);
} else if (key.equals("itemrgb")) {
trackProperties.setItemRGB(value.toLowerCase().equals("on"));
} else if (key.equals("usescore")) {
trackProperties.setUseScore(value.equals("1"));
} else if (key.equals("color")) {
Color color = ColorUtilities.convertRGBStringToColor(value);
trackProperties.setColor(color);
} else if (key.equals("altcolor")) {
Color color = ColorUtilities.convertRGBStringToColor(value);
trackProperties.setAltColor(color);
} else if (key.equals("midcolor")) {
Color color = ColorUtilities.convertRGBStringToColor(value);
trackProperties.setMidColor(color);
} else if (key.equals("autoscale")) {
boolean autoscale = value.equals("on");
trackProperties.setAutoScale(autoscale);
} else if (key.equals("maxheightpixels")) {
// Ignore the min and max
String[] maxDefMin = value.split(":");
<MASK>trackProperties.setHeight(Integer.parseInt(maxDefMin[0].trim()));</MASK>
trackProperties.setMinHeight(Integer.parseInt(maxDefMin[1].trim()));
} else if (key.equals("url")) {
trackProperties.setUrl(value);
} else if (key.equals("graphtype")) {
if (value.equals("bar")) {
trackProperties.setRendererClass(BarChartRenderer.class);
} else if (value.equals("points")) {
trackProperties.setRendererClass(ScatterplotRenderer.class);
} else if (value.equals("line")) {
trackProperties.setRendererClass(LineplotRenderer.class);
} else if (value.equals("heatmap")) {
trackProperties.setRendererClass(HeatmapRenderer.class);
} else if (value.equals("junctions")) {
//dhmay adding check for graphType=junction. name is also checked
trackProperties.setRendererClass(SpliceJunctionRenderer.class);
}
} else if (key.toLowerCase().equals("viewlimits")) {
String[] limits = value.split(":");
if (limits.length == 2) {
try {
float min = Float.parseFloat(limits[0].trim());
float max = Float.parseFloat(limits[1].trim());
trackProperties.setMinValue(min);
trackProperties.setMaxValue(max);
} catch (NumberFormatException e) {
log.error("viewLimits values must be numeric: " + value);
}
}
} else if (key.equals("midrange")) {
String[] limits = value.split(":");
if (limits.length == 2) {
try {
float from = Float.parseFloat(limits[0].trim());
float to = Float.parseFloat(limits[1].trim());
trackProperties.setNeutralFromValue(from);
trackProperties.setNeutralToValue(to);
} catch (NumberFormatException e) {
log.error("midrange values must be numeric: " + value);
}
}
} else if (key.equals("ylinemark")) {
try {
float midValue = Float.parseFloat(value);
trackProperties.setMidValue(midValue);
} catch (NumberFormatException e) {
log.error("Number format exception in track line (ylinemark): " + nextLine);
}
} else if (key.equals("ylineonoff")) {
trackProperties.setDrawMidValue(value.equals("on"));
} else if (key.equals("windowingfunction")) {
if (value.equals("maximum")) {
trackProperties.setWindowingFunction(WindowFunction.max);
} else if (value.equals("minimum")) {
trackProperties.setWindowingFunction(WindowFunction.min);
} else if (value.equals("mean")) {
trackProperties.setWindowingFunction(WindowFunction.mean);
} else if (value.equals("median")) {
trackProperties.setWindowingFunction(WindowFunction.median);
} else if (value.equals("percentile10")) {
trackProperties.setWindowingFunction(WindowFunction.percentile10);
} else if (value.equals("percentile90")) {
trackProperties.setWindowingFunction(WindowFunction.percentile90);
}
} else if(key.equals("maxfeaturewindow") || key.equals("featurevisibilitywindow")) {
// These options are deprecated. Use visibilityWindow
try {
int windowSize = Integer.parseInt(value);
trackProperties.setFeatureVisibilityWindow(windowSize);
} catch (NumberFormatException e) {
log.error("featureVisibilityWindow must be numeric: " + nextLine);
}
} else if(key.equals("visibilitywindow")) {
try {
int windowSize = Integer.parseInt(value) * 1000;
trackProperties.setFeatureVisibilityWindow(windowSize);
} catch (NumberFormatException e) {
log.error("featureVisibilityWindow must be an integer: " + nextLine);
}
}
else if(key.equals("scaletype")) {
if(value.equals("log")) {
trackProperties.setLogScale(true);
}
}
}
}
}
catch (
Exception exception
)
{
MessageUtils.showMessage("Error parsing track line: " + nextLine + " (" + exception.getMessage() + ")");
}
return foundProperties;
}" |
Inversion-Mutation | megadiff | "private static void decodeTextSegment(BitSource bits, StringBuffer result) throws FormatException {
// Three Text values are encoded in a 16-bit value as
// (1600 * C1) + (40 * C2) + C3 + 1
// TODO(bbrown): The Upper Shift with Text doesn't work in the 4 value scenario all the time
boolean upperShift = false;
int[] cValues = new int[3];
int shift = 0;
do {
// If there is only one byte left then it will be encoded as ASCII
if (bits.available() == 8) {
return;
}
int firstByte = bits.readBits(8);
if (firstByte == 254) { // Unlatch codeword
return;
}
parseTwoBytes(firstByte, bits.readBits(8), cValues);
for (int i = 0; i < 3; i++) {
int cValue = cValues[i];
switch (shift) {
case 0:
if (cValue < 3) {
shift = cValue + 1;
} else {
if (upperShift) {
result.append((char) (TEXT_BASIC_SET_CHARS[cValue] + 128));
upperShift = false;
} else {
result.append(TEXT_BASIC_SET_CHARS[cValue]);
}
}
break;
case 1:
if (upperShift) {
result.append((char) (cValue + 128));
upperShift = false;
} else {
result.append(cValue);
}
shift = 0;
break;
case 2:
// Shift 2 for Text is the same encoding as C40
if (cValue < 27) {
if (upperShift) {
result.append((char) (C40_SHIFT2_SET_CHARS[cValue] + 128));
upperShift = false;
} else {
result.append(C40_SHIFT2_SET_CHARS[cValue]);
}
} else if (cValue == 27) { // FNC1
throw FormatException.getFormatInstance();
} else if (cValue == 30) { // Upper Shift
upperShift = true;
} else {
throw FormatException.getFormatInstance();
}
shift = 0;
break;
case 3:
if (upperShift) {
result.append((char) (TEXT_SHIFT3_SET_CHARS[cValue] + 128));
upperShift = false;
} else {
result.append(TEXT_SHIFT3_SET_CHARS[cValue]);
}
shift = 0;
break;
default:
throw FormatException.getFormatInstance();
}
}
} while (bits.available() > 0);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "decodeTextSegment" | "private static void decodeTextSegment(BitSource bits, StringBuffer result) throws FormatException {
// Three Text values are encoded in a 16-bit value as
// (1600 * C1) + (40 * C2) + C3 + 1
// TODO(bbrown): The Upper Shift with Text doesn't work in the 4 value scenario all the time
boolean upperShift = false;
int[] cValues = new int[3];
do {
// If there is only one byte left then it will be encoded as ASCII
if (bits.available() == 8) {
return;
}
int firstByte = bits.readBits(8);
if (firstByte == 254) { // Unlatch codeword
return;
}
parseTwoBytes(firstByte, bits.readBits(8), cValues);
<MASK>int shift = 0;</MASK>
for (int i = 0; i < 3; i++) {
int cValue = cValues[i];
switch (shift) {
case 0:
if (cValue < 3) {
shift = cValue + 1;
} else {
if (upperShift) {
result.append((char) (TEXT_BASIC_SET_CHARS[cValue] + 128));
upperShift = false;
} else {
result.append(TEXT_BASIC_SET_CHARS[cValue]);
}
}
break;
case 1:
if (upperShift) {
result.append((char) (cValue + 128));
upperShift = false;
} else {
result.append(cValue);
}
shift = 0;
break;
case 2:
// Shift 2 for Text is the same encoding as C40
if (cValue < 27) {
if (upperShift) {
result.append((char) (C40_SHIFT2_SET_CHARS[cValue] + 128));
upperShift = false;
} else {
result.append(C40_SHIFT2_SET_CHARS[cValue]);
}
} else if (cValue == 27) { // FNC1
throw FormatException.getFormatInstance();
} else if (cValue == 30) { // Upper Shift
upperShift = true;
} else {
throw FormatException.getFormatInstance();
}
shift = 0;
break;
case 3:
if (upperShift) {
result.append((char) (TEXT_SHIFT3_SET_CHARS[cValue] + 128));
upperShift = false;
} else {
result.append(TEXT_SHIFT3_SET_CHARS[cValue]);
}
shift = 0;
break;
default:
throw FormatException.getFormatInstance();
}
}
} while (bits.available() > 0);
}" |
Inversion-Mutation | megadiff | "private FeatureResultSet queryByIdFilterRelational( IdFilter filter, SortProperty[] sortCrit )
throws FeatureStoreException {
LinkedHashMap<QName, List<IdAnalysis>> ftNameToIdAnalysis = new LinkedHashMap<QName, List<IdAnalysis>>();
try {
for ( String fid : filter.getMatchingIds() ) {
IdAnalysis analysis = getSchema().analyzeId( fid );
FeatureType ft = analysis.getFeatureType();
List<IdAnalysis> idKernels = ftNameToIdAnalysis.get( ft.getName() );
if ( idKernels == null ) {
idKernels = new ArrayList<IdAnalysis>();
ftNameToIdAnalysis.put( ft.getName(), idKernels );
}
idKernels.add( analysis );
}
} catch ( IllegalArgumentException e ) {
throw new FeatureStoreException( e.getMessage(), e );
}
if ( ftNameToIdAnalysis.size() != 1 ) {
throw new FeatureStoreException(
"Currently, only relational id queries are supported that target single feature types." );
}
QName ftName = ftNameToIdAnalysis.keySet().iterator().next();
FeatureType ft = getSchema().getFeatureType( ftName );
FeatureTypeMapping ftMapping = getSchema().getFtMapping( ftName );
FIDMapping fidMapping = ftMapping.getFidMapping();
List<IdAnalysis> idKernels = ftNameToIdAnalysis.get( ftName );
FeatureResultSet result = null;
PreparedStatement stmt = null;
ResultSet rs = null;
Connection conn = null;
try {
long begin = System.currentTimeMillis();
conn = ConnectionManager.getConnection( getConnId() );
FeatureBuilder builder = new FeatureBuilderRelational( this, ft, ftMapping, conn );
List<String> columns = builder.getInitialSelectColumns();
StringBuilder sql = new StringBuilder( "SELECT " );
sql.append( columns.get( 0 ) );
for ( int i = 1; i < columns.size(); i++ ) {
sql.append( ',' );
sql.append( columns.get( i ) );
}
sql.append( " FROM " );
sql.append( ftMapping.getFtTable() );
sql.append( " WHERE " );
boolean first = true;
for ( IdAnalysis idKernel : idKernels ) {
if ( !first ) {
sql.append( " OR " );
}
sql.append( "(" );
boolean firstCol = true;
for ( Pair<String, PrimitiveType> fidColumn : fidMapping.getColumns() ) {
if ( !firstCol ) {
sql.append( " AND " );
}
sql.append( fidColumn.first );
sql.append( "=?" );
firstCol = false;
}
sql.append( ")" );
first = false;
}
LOG.debug( "SQL: {}", sql );
stmt = conn.prepareStatement( sql.toString() );
LOG.debug( "Preparing SELECT took {} [ms] ", System.currentTimeMillis() - begin );
int i = 1;
for ( IdAnalysis idKernel : idKernels ) {
for ( Object o : idKernel.getIdKernels() ) {
// TODO
PrimitiveValue value = new PrimitiveValue( o, PrimitiveType.STRING );
Object sqlValue = SQLValueMangler.internalToSQL( value );
stmt.setObject( i++, sqlValue );
}
}
begin = System.currentTimeMillis();
rs = stmt.executeQuery();
LOG.debug( "Executing SELECT took {} [ms] ", System.currentTimeMillis() - begin );
result = new IteratorResultSet( new PostGISResultSetIterator( builder, rs, conn, stmt ) );
} catch ( Exception e ) {
close( rs, stmt, conn, LOG );
String msg = "Error performing query by id filter (relational mode): " + e.getMessage();
LOG.error( msg, e );
throw new FeatureStoreException( msg, e );
}
return result;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "queryByIdFilterRelational" | "private FeatureResultSet queryByIdFilterRelational( IdFilter filter, SortProperty[] sortCrit )
throws FeatureStoreException {
LinkedHashMap<QName, List<IdAnalysis>> ftNameToIdAnalysis = new LinkedHashMap<QName, List<IdAnalysis>>();
try {
for ( String fid : filter.getMatchingIds() ) {
IdAnalysis analysis = getSchema().analyzeId( fid );
FeatureType ft = analysis.getFeatureType();
List<IdAnalysis> idKernels = ftNameToIdAnalysis.get( ft.getName() );
if ( idKernels == null ) {
idKernels = new ArrayList<IdAnalysis>();
ftNameToIdAnalysis.put( ft.getName(), idKernels );
}
idKernels.add( analysis );
}
} catch ( IllegalArgumentException e ) {
throw new FeatureStoreException( e.getMessage(), e );
}
if ( ftNameToIdAnalysis.size() != 1 ) {
throw new FeatureStoreException(
"Currently, only relational id queries are supported that target single feature types." );
}
QName ftName = ftNameToIdAnalysis.keySet().iterator().next();
FeatureType ft = getSchema().getFeatureType( ftName );
FeatureTypeMapping ftMapping = getSchema().getFtMapping( ftName );
FIDMapping fidMapping = ftMapping.getFidMapping();
List<IdAnalysis> idKernels = ftNameToIdAnalysis.get( ftName );
FeatureResultSet result = null;
PreparedStatement stmt = null;
ResultSet rs = null;
Connection conn = null;
try {
long begin = System.currentTimeMillis();
FeatureBuilder builder = new FeatureBuilderRelational( this, ft, ftMapping, conn );
List<String> columns = builder.getInitialSelectColumns();
StringBuilder sql = new StringBuilder( "SELECT " );
sql.append( columns.get( 0 ) );
for ( int i = 1; i < columns.size(); i++ ) {
sql.append( ',' );
sql.append( columns.get( i ) );
}
sql.append( " FROM " );
sql.append( ftMapping.getFtTable() );
sql.append( " WHERE " );
boolean first = true;
for ( IdAnalysis idKernel : idKernels ) {
if ( !first ) {
sql.append( " OR " );
}
sql.append( "(" );
boolean firstCol = true;
for ( Pair<String, PrimitiveType> fidColumn : fidMapping.getColumns() ) {
if ( !firstCol ) {
sql.append( " AND " );
}
sql.append( fidColumn.first );
sql.append( "=?" );
firstCol = false;
}
sql.append( ")" );
first = false;
}
LOG.debug( "SQL: {}", sql );
<MASK>conn = ConnectionManager.getConnection( getConnId() );</MASK>
stmt = conn.prepareStatement( sql.toString() );
LOG.debug( "Preparing SELECT took {} [ms] ", System.currentTimeMillis() - begin );
int i = 1;
for ( IdAnalysis idKernel : idKernels ) {
for ( Object o : idKernel.getIdKernels() ) {
// TODO
PrimitiveValue value = new PrimitiveValue( o, PrimitiveType.STRING );
Object sqlValue = SQLValueMangler.internalToSQL( value );
stmt.setObject( i++, sqlValue );
}
}
begin = System.currentTimeMillis();
rs = stmt.executeQuery();
LOG.debug( "Executing SELECT took {} [ms] ", System.currentTimeMillis() - begin );
result = new IteratorResultSet( new PostGISResultSetIterator( builder, rs, conn, stmt ) );
} catch ( Exception e ) {
close( rs, stmt, conn, LOG );
String msg = "Error performing query by id filter (relational mode): " + e.getMessage();
LOG.error( msg, e );
throw new FeatureStoreException( msg, e );
}
return result;
}" |
Inversion-Mutation | megadiff | "public void start() {
if(started) {
throw new IllegalStateException("Proxy branch alredy started!");
}
if(canceled) {
throw new IllegalStateException("Proxy branch was cancelled, you must create a new branch!");
}
if(timedOut) {
throw new IllegalStateException("Proxy brnach has timed out!");
}
if(proxy.getAckReceived()) {
throw new IllegalStateException("An ACK request has been received on this proxy. Can not start new branches.");
}
// Initialize these here for efficiency.
updateTimer(false);
SipURI recordRoute = null;
// If the proxy is not adding record-route header, set it to null and it
// will be ignored in the Proxying
if(proxy.getRecordRoute() || this.getRecordRoute()) {
if(recordRouteURI == null) {
recordRouteURI = proxy.getSipFactoryImpl().createSipURI("proxy", "localhost");
}
recordRoute = recordRouteURI;
}
Request cloned = ProxyUtils.createProxiedRequest(
outgoingRequest,
this,
this.targetURI,
this.outboundInterface,
recordRoute,
this.pathURI);
//tells the application dispatcher to stop routing the original request
//since it has been proxied
originalRequest.setRoutingState(RoutingState.PROXIED);
if(logger.isDebugEnabled()) {
logger.debug("Proxy Branch 1xx Timeout set to " + proxyBranch1xxTimeout);
}
if(proxyBranch1xxTimeout > 0) {
proxy1xxTimeoutTask = new ProxyBranchTimerTask(this, ResponseType.INFORMATIONAL);
timer.schedule(proxy1xxTimeoutTask, proxyBranch1xxTimeout * 1000L);
proxyBranch1xxTimerStarted = true;
}
started = true;
forwardRequest(cloned, false);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "start" | "public void start() {
if(started) {
throw new IllegalStateException("Proxy branch alredy started!");
}
if(canceled) {
throw new IllegalStateException("Proxy branch was cancelled, you must create a new branch!");
}
if(timedOut) {
throw new IllegalStateException("Proxy brnach has timed out!");
}
if(proxy.getAckReceived()) {
throw new IllegalStateException("An ACK request has been received on this proxy. Can not start new branches.");
}
// Initialize these here for efficiency.
updateTimer(false);
SipURI recordRoute = null;
// If the proxy is not adding record-route header, set it to null and it
// will be ignored in the Proxying
if(proxy.getRecordRoute() || this.getRecordRoute()) {
if(recordRouteURI == null) {
recordRouteURI = proxy.getSipFactoryImpl().createSipURI("proxy", "localhost");
}
recordRoute = recordRouteURI;
}
Request cloned = ProxyUtils.createProxiedRequest(
outgoingRequest,
this,
this.targetURI,
this.outboundInterface,
recordRoute,
this.pathURI);
//tells the application dispatcher to stop routing the original request
//since it has been proxied
originalRequest.setRoutingState(RoutingState.PROXIED);
if(logger.isDebugEnabled()) {
logger.debug("Proxy Branch 1xx Timeout set to " + proxyBranch1xxTimeout);
}
if(proxyBranch1xxTimeout > 0) {
proxy1xxTimeoutTask = new ProxyBranchTimerTask(this, ResponseType.INFORMATIONAL);
timer.schedule(proxy1xxTimeoutTask, proxyBranch1xxTimeout * 1000L);
proxyBranch1xxTimerStarted = true;
}
<MASK>forwardRequest(cloned, false);</MASK>
started = true;
}" |
Inversion-Mutation | megadiff | "public void onDisable()
{
if (isReady)
{
HeroesDamageFix.reset();
debugLogger.info(savePets(true) + " pet/pets saved.");
for (MyPet myPet : MyPetList.getAllMyPets())
{
myPet.removePet();
}
}
getTimer().stopTimer();
MyPetList.clearList();
getPlugin().getServer().getScheduler().cancelTasks(getPlugin());
debugLogger.info("MyPet disabled!");
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onDisable" | "public void onDisable()
{
if (isReady)
{
debugLogger.info(savePets(true) + " pet/pets saved.");
for (MyPet myPet : MyPetList.getAllMyPets())
{
myPet.removePet();
}
}
getTimer().stopTimer();
MyPetList.clearList();
getPlugin().getServer().getScheduler().cancelTasks(getPlugin());
<MASK>HeroesDamageFix.reset();</MASK>
debugLogger.info("MyPet disabled!");
}" |
Inversion-Mutation | megadiff | "@Override
public void buttonClick(ClickEvent event) {
if (event.getButton()
.getCaption()
.equals("Zurücksetzen")) {
controlledView.reset();
} else if (event.getButton()
.getCaption()
.equals("Beantragen")) {
Request r = controlledView.getRequest();
if (r == null) {
MainController.get()
.print("Nicht alle Pflichtfelder gefüllt");
return;
}
String headline = "Antrag erfolgreich angelegt!";
String subline = "Sie können nun über die Navigationsleiste zur "
+ "Startseite zurückkehren.";
try {
LoggingService.getInstance()
.log( "Request successfully created and "
+ "persisted",
LogLevel.INFO);
dao.insertRequest(r);
r.start();
} catch (Exception e) {
LoggingService.getInstance()
.log(e.getMessage(), LogLevel.ERROR);
e.printStackTrace();
headline = "Antrag nicht angelegt!";
subline = "Der Antrag konnte leider nicht angelegt werden. "
+ "Versuchen Sie es erneut. Sollte das Problem "
+ "weiterhin bestehen, kontaktieren Sie einen "
+ "Administrator.";
}
MainController.get()
.changeView(new PostButtonPage( headline,
subline));
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "buttonClick" | "@Override
public void buttonClick(ClickEvent event) {
if (event.getButton()
.getCaption()
.equals("Zurücksetzen")) {
controlledView.reset();
} else if (event.getButton()
.getCaption()
.equals("Beantragen")) {
Request r = controlledView.getRequest();
if (r == null) {
MainController.get()
.print("Nicht alle Pflichtfelder gefüllt");
return;
}
String headline = "Antrag erfolgreich angelegt!";
String subline = "Sie können nun über die Navigationsleiste zur "
+ "Startseite zurückkehren.";
try {
<MASK>dao.insertRequest(r);</MASK>
LoggingService.getInstance()
.log( "Request successfully created and "
+ "persisted",
LogLevel.INFO);
r.start();
} catch (Exception e) {
LoggingService.getInstance()
.log(e.getMessage(), LogLevel.ERROR);
e.printStackTrace();
headline = "Antrag nicht angelegt!";
subline = "Der Antrag konnte leider nicht angelegt werden. "
+ "Versuchen Sie es erneut. Sollte das Problem "
+ "weiterhin bestehen, kontaktieren Sie einen "
+ "Administrator.";
}
MainController.get()
.changeView(new PostButtonPage( headline,
subline));
}
}" |
Inversion-Mutation | megadiff | "@Override
public void onDestroy() {
synchronized(sSyncLock) {
alwaysLog("!!! EAS ExchangeService, onDestroy");
// Stop the sync manager thread and return
synchronized (sSyncLock) {
if (sServiceThread != null) {
sStop = true;
sServiceThread.interrupt();
}
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onDestroy" | "@Override
public void onDestroy() {
synchronized(sSyncLock) {
alwaysLog("!!! EAS ExchangeService, onDestroy");
// Stop the sync manager thread and return
synchronized (sSyncLock) {
<MASK>sStop = true;</MASK>
if (sServiceThread != null) {
sServiceThread.interrupt();
}
}
}
}" |
Inversion-Mutation | megadiff | "public String replaceMacros(CommandSender sender, String message) {
Player[] online = getServer().getOnlinePlayers();
message = message.replace("%name%", toName(sender));
message = message.replace("%id%", toUniqueName(sender));
message = message.replace("%online%", String.valueOf(online.length));
if (sender instanceof Player) {
Player player = (Player) sender;
World world = player.getWorld();
message = message.replace("%world%", world.getName());
message = message.replace("%health%", String.valueOf(player.getHealth()));
}
return message;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "replaceMacros" | "public String replaceMacros(CommandSender sender, String message) {
Player[] online = getServer().getOnlinePlayers();
message = message.replace("%name%", toName(sender));
message = message.replace("%id%", toUniqueName(sender));
if (sender instanceof Player) {
Player player = (Player) sender;
World world = player.getWorld();
message = message.replace("%world%", world.getName());
<MASK>message = message.replace("%online%", String.valueOf(online.length));</MASK>
message = message.replace("%health%", String.valueOf(player.getHealth()));
}
return message;
}" |
Inversion-Mutation | megadiff | "public static RubyDebuggerProxy startRubyDebug(
final Descriptor descriptor,
final String rdebugExecutable,
final String interpreter,
final int timeout) throws IOException, RubyDebuggerException {
descriptor.setType(RUBY_DEBUG);
List<String> args = new ArrayList<String>();
if (interpreter != null) {
args.add(interpreter);
appendIOSynchronizer(args, descriptor);
}
args.addAll(descriptor.getAddtionalOptions());
args.add(rdebugExecutable);
args.add("-p");
args.add(String.valueOf(descriptor.getPort()));
if (descriptor.isVerbose()) {
args.add("-d");
}
args.add("--");
args.add(descriptor.getScriptPath());
if (descriptor.getScriptArguments() != null) {
args.addAll(Arrays.asList(descriptor.getScriptArguments()));
}
return startDebugger(descriptor, args, timeout);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "startRubyDebug" | "public static RubyDebuggerProxy startRubyDebug(
final Descriptor descriptor,
final String rdebugExecutable,
final String interpreter,
final int timeout) throws IOException, RubyDebuggerException {
descriptor.setType(RUBY_DEBUG);
List<String> args = new ArrayList<String>();
if (interpreter != null) {
args.add(interpreter);
appendIOSynchronizer(args, descriptor);
}
args.add(rdebugExecutable);
args.add("-p");
args.add(String.valueOf(descriptor.getPort()));
if (descriptor.isVerbose()) {
args.add("-d");
}
<MASK>args.addAll(descriptor.getAddtionalOptions());</MASK>
args.add("--");
args.add(descriptor.getScriptPath());
if (descriptor.getScriptArguments() != null) {
args.addAll(Arrays.asList(descriptor.getScriptArguments()));
}
return startDebugger(descriptor, args, timeout);
}" |
Inversion-Mutation | megadiff | "protected void handleClasspathDefaultButtonSelected() {
boolean useDefault = fClassPathDefaultButton.getSelection();
fClassPathDefaultButton.setSelection(useDefault);
if (useDefault) {
displayDefaultClasspath();
}
fClasspathViewer.setEnabled(!useDefault);
fBootpathViewer.setEnabled(!useDefault);
setDirty(true);
updateLaunchConfigurationDialog();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handleClasspathDefaultButtonSelected" | "protected void handleClasspathDefaultButtonSelected() {
boolean useDefault = fClassPathDefaultButton.getSelection();
fClassPathDefaultButton.setSelection(useDefault);
if (useDefault) {
displayDefaultClasspath();
}
fClasspathViewer.setEnabled(!useDefault);
fBootpathViewer.setEnabled(!useDefault);
<MASK>updateLaunchConfigurationDialog();</MASK>
setDirty(true);
}" |
Inversion-Mutation | megadiff | "@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
sonido = R.raw.fua3;
btnFua = (Button) findViewById(R.id.button1);
imageView=(ImageView) findViewById(R.id.ImageView1);
btnFua.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
imageView.setImageResource(img);
Thread x = new Thread(new Runnable() {
@Override
public void run() {
MediaPlayer mp = MediaPlayer.create(FuaaaActivity.this,
sonido);
mp.start();
while (mp.isPlaying()) {
}
}
});
x.start();
}
});
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCreate" | "@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
sonido = R.raw.fua3;
btnFua = (Button) findViewById(R.id.button1);
imageView=(ImageView) findViewById(R.id.ImageView1);
btnFua.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Thread x = new Thread(new Runnable() {
@Override
public void run() {
MediaPlayer mp = MediaPlayer.create(FuaaaActivity.this,
sonido);
<MASK>imageView.setImageResource(img);</MASK>
mp.start();
while (mp.isPlaying()) {
}
}
});
x.start();
}
});
}" |
Inversion-Mutation | megadiff | "@Override
public void onClick(View v) {
imageView.setImageResource(img);
Thread x = new Thread(new Runnable() {
@Override
public void run() {
MediaPlayer mp = MediaPlayer.create(FuaaaActivity.this,
sonido);
mp.start();
while (mp.isPlaying()) {
}
}
});
x.start();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onClick" | "@Override
public void onClick(View v) {
Thread x = new Thread(new Runnable() {
@Override
public void run() {
MediaPlayer mp = MediaPlayer.create(FuaaaActivity.this,
sonido);
<MASK>imageView.setImageResource(img);</MASK>
mp.start();
while (mp.isPlaying()) {
}
}
});
x.start();
}" |
Inversion-Mutation | megadiff | "public DataSourceTableModel(TableEditableElement element) {
this.element = element;
dataSource = element.getDataSource();
dataSourceListener = new ModificationListener();
if(dataSource.isEditable()) {
try {
dataSource.addEditionListener(dataSourceListener);
dataSource.addMetadataEditionListener(dataSourceListener);
} catch (UnsupportedOperationException ex) {
LOGGER.warn(I18N.tr("The TableEditor cannot listen to source modifications"), ex);
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "DataSourceTableModel" | "public DataSourceTableModel(TableEditableElement element) {
this.element = element;
dataSource = element.getDataSource();
dataSourceListener = new ModificationListener();
if(dataSource.isEditable()) {
try {
dataSource.addEditionListener(dataSourceListener);
} catch (UnsupportedOperationException ex) {
LOGGER.warn(I18N.tr("The TableEditor cannot listen to source modifications"), ex);
}
}
<MASK>dataSource.addMetadataEditionListener(dataSourceListener);</MASK>
}" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.