type
stringclasses
1 value
dataset
stringclasses
1 value
input
stringlengths
75
160k
instruction
stringlengths
117
171
output
stringlengths
88
168k
Inversion-Mutation
megadiff
"private void initializeProperties () throws Exception { String userHome = System.getProperty("user.home"); String userDir = System.getProperty("user.dir"); String hackyHome = userHome + "/.hackystat"; String sensorBaseHome = hackyHome + "/sensorbase"; String propFile = userHome + "/.hackystat/sensorbase/sensorbase.properties"; String defaultAdmin = "[email protected]"; this.properties = new Properties(); // Set defaults for 'standard' operation. These will override any previously properties.setProperty(ADMIN_EMAIL_KEY, defaultAdmin); properties.setProperty(ADMIN_PASSWORD_KEY, defaultAdmin); properties.setProperty(CONTEXT_ROOT_KEY, "sensorbase"); properties.setProperty(DB_DIR_KEY, sensorBaseHome + "/db"); properties.setProperty(DB_IMPL_KEY, "org.hackystat.sensorbase.db.derby.DerbyImplementation"); properties.setProperty(HOSTNAME_KEY, "localhost"); properties.setProperty(LOGGING_LEVEL_KEY, "INFO"); properties.setProperty(RESTLET_LOGGING_KEY, FALSE); properties.setProperty(SMTP_HOST_KEY, "mail.hawaii.edu"); properties.setProperty(PORT_KEY, "9876"); properties.setProperty(XML_DIR_KEY, userDir + "/xml"); properties.setProperty(TEST_DOMAIN_KEY, "hackystat.org"); properties.setProperty(TEST_INSTALL_KEY, FALSE); properties.setProperty(TEST_ADMIN_EMAIL_KEY, defaultAdmin); properties.setProperty(TEST_ADMIN_PASSWORD_KEY, defaultAdmin); properties.setProperty(TEST_DB_DIR_KEY, sensorBaseHome + "/testdb"); properties.setProperty(TEST_PORT_KEY, "9976"); properties.setProperty(TEST_HOSTNAME_KEY, "localhost"); properties.setProperty(COMPRESS_ON_STARTUP_KEY, FALSE); properties.setProperty(REINDEX_ON_STARTUP_KEY, FALSE); FileInputStream stream = null; try { stream = new FileInputStream(propFile); properties.load(stream); System.out.println("Loading SensorBase properties from: " + propFile); } catch (IOException e) { System.out.println(propFile + " not found. Using default sensorbase properties."); } finally { if (stream != null) { stream.close(); } } addSensorBaseSystemProperties(this.properties); trimProperties(properties); // Now add to System properties. Since the Mailer class expects to find this stuff on the // System Properties, we will add everything to it. In general, however, clients should not // use the System Properties to get at these values, since that precludes running several // SensorBases in a single JVM. And just is generally bogus. Properties systemProperties = System.getProperties(); systemProperties.putAll(properties); System.setProperties(systemProperties); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "initializeProperties"
"private void initializeProperties () throws Exception { String userHome = System.getProperty("user.home"); String userDir = System.getProperty("user.dir"); String hackyHome = userHome + "/.hackystat"; String sensorBaseHome = hackyHome + "/sensorbase"; String propFile = userHome + "/.hackystat/sensorbase/sensorbase.properties"; String defaultAdmin = "[email protected]"; this.properties = new Properties(); <MASK>addSensorBaseSystemProperties(this.properties);</MASK> // Set defaults for 'standard' operation. These will override any previously properties.setProperty(ADMIN_EMAIL_KEY, defaultAdmin); properties.setProperty(ADMIN_PASSWORD_KEY, defaultAdmin); properties.setProperty(CONTEXT_ROOT_KEY, "sensorbase"); properties.setProperty(DB_DIR_KEY, sensorBaseHome + "/db"); properties.setProperty(DB_IMPL_KEY, "org.hackystat.sensorbase.db.derby.DerbyImplementation"); properties.setProperty(HOSTNAME_KEY, "localhost"); properties.setProperty(LOGGING_LEVEL_KEY, "INFO"); properties.setProperty(RESTLET_LOGGING_KEY, FALSE); properties.setProperty(SMTP_HOST_KEY, "mail.hawaii.edu"); properties.setProperty(PORT_KEY, "9876"); properties.setProperty(XML_DIR_KEY, userDir + "/xml"); properties.setProperty(TEST_DOMAIN_KEY, "hackystat.org"); properties.setProperty(TEST_INSTALL_KEY, FALSE); properties.setProperty(TEST_ADMIN_EMAIL_KEY, defaultAdmin); properties.setProperty(TEST_ADMIN_PASSWORD_KEY, defaultAdmin); properties.setProperty(TEST_DB_DIR_KEY, sensorBaseHome + "/testdb"); properties.setProperty(TEST_PORT_KEY, "9976"); properties.setProperty(TEST_HOSTNAME_KEY, "localhost"); properties.setProperty(COMPRESS_ON_STARTUP_KEY, FALSE); properties.setProperty(REINDEX_ON_STARTUP_KEY, FALSE); FileInputStream stream = null; try { stream = new FileInputStream(propFile); properties.load(stream); System.out.println("Loading SensorBase properties from: " + propFile); } catch (IOException e) { System.out.println(propFile + " not found. Using default sensorbase properties."); } finally { if (stream != null) { stream.close(); } } trimProperties(properties); // Now add to System properties. Since the Mailer class expects to find this stuff on the // System Properties, we will add everything to it. In general, however, clients should not // use the System Properties to get at these values, since that precludes running several // SensorBases in a single JVM. And just is generally bogus. Properties systemProperties = System.getProperties(); systemProperties.putAll(properties); System.setProperties(systemProperties); }"
Inversion-Mutation
megadiff
"private UserHistoryDictionary(final Context context, final String locale, final int dicTypeId, SharedPreferences sp) { super(context, dicTypeId); mLocale = locale; mPrefs = sp; if (sOpenHelper == null) { sOpenHelper = new DatabaseHelper(getContext()); } if (mLocale != null && mLocale.length() > 1) { loadDictionary(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "UserHistoryDictionary"
"private UserHistoryDictionary(final Context context, final String locale, final int dicTypeId, SharedPreferences sp) { super(context, dicTypeId); mLocale = locale; if (sOpenHelper == null) { sOpenHelper = new DatabaseHelper(getContext()); } if (mLocale != null && mLocale.length() > 1) { loadDictionary(); } <MASK>mPrefs = sp;</MASK> }"
Inversion-Mutation
megadiff
"public void propertyChange(PropertyChangeEvent event) { if (fSourceViewer == null) return; String property= event.getProperty(); // IMPORTANT: Do not call isBlockSelectionModeEnabled() before checking the property! if (BLOCK_SELECTION_MODE_FONT.equals(property) && isBlockSelectionModeEnabled()) { Font blockFont= JFaceResources.getFont(BLOCK_SELECTION_MODE_FONT); setFont(fSourceViewer, blockFont); disposeFont(); return; } if (getFontPropertyPreferenceKey().equals(property) && !isBlockSelectionModeEnabled()) { initializeViewerFont(fSourceViewer); updateCaret(); return; } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "propertyChange"
"public void propertyChange(PropertyChangeEvent event) { if (fSourceViewer == null) return; String property= event.getProperty(); // IMPORTANT: Do not call isBlockSelectionModeEnabled() before checking the property! if (BLOCK_SELECTION_MODE_FONT.equals(property) && isBlockSelectionModeEnabled()) { Font blockFont= JFaceResources.getFont(BLOCK_SELECTION_MODE_FONT); <MASK>disposeFont();</MASK> setFont(fSourceViewer, blockFont); return; } if (getFontPropertyPreferenceKey().equals(property) && !isBlockSelectionModeEnabled()) { initializeViewerFont(fSourceViewer); updateCaret(); return; } }"
Inversion-Mutation
megadiff
"public void run(String[] args) { final TimerFrame tf = new TimerFrame(); if (args.length == 2) { tf.sync(Integer.parseInt(args[1])); tf.setStatus(Integer.parseInt(args[0])); } else { Pcms2 connection = new Pcms2(Settings.instance().host); connection.hookLengthChange(new Callback<Long>() { @Override public void exec(Long arg) { length = arg; tf.sync(length - time); } }); connection.hookTimeChange(new Callback<Long>() { @Override public void exec(Long arg) { time = arg; tf.sync(length - time); } }); connection.hookStatusChange(new Callback<Integer>() { @Override public void exec(Integer arg) { tf.setStatus(arg); } }); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"public void run(String[] args) { final TimerFrame tf = new TimerFrame(); if (args.length == 2) { <MASK>tf.setStatus(Integer.parseInt(args[0]));</MASK> tf.sync(Integer.parseInt(args[1])); } else { Pcms2 connection = new Pcms2(Settings.instance().host); connection.hookLengthChange(new Callback<Long>() { @Override public void exec(Long arg) { length = arg; tf.sync(length - time); } }); connection.hookTimeChange(new Callback<Long>() { @Override public void exec(Long arg) { time = arg; tf.sync(length - time); } }); connection.hookStatusChange(new Callback<Integer>() { @Override public void exec(Integer arg) { tf.setStatus(arg); } }); } }"
Inversion-Mutation
megadiff
"public boolean isProtected(Block block, Player player){ checkChunk(block, player); switch(block.getType()){ case WALL_SIGN: checkSign(block, player); return result; case CHEST: checkChest(block, player); return result; case IRON_DOOR: return false; case WOODEN_DOOR: return false; case TRAP_DOOR: return false; default: checkBlock(block, player); } return result; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "isProtected"
"public boolean isProtected(Block block, Player player){ switch(block.getType()){ case WALL_SIGN: checkSign(block, player); return result; case CHEST: checkChest(block, player); return result; case IRON_DOOR: return false; case WOODEN_DOOR: return false; case TRAP_DOOR: return false; default: <MASK>checkChunk(block, player);</MASK> checkBlock(block, player); } return result; }"
Inversion-Mutation
megadiff
"@Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.edit_filter_delete) { Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.edit_filter_delete_dialog_title); builder.setNegativeButton(R.string.default_buttons_no, null); builder.setPositiveButton(R.string.default_buttons_yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (helper.removePoiFilter(filter)) { Toast.makeText( EditPOIFilterActivity.this, MessageFormat.format(EditPOIFilterActivity.this.getText(R.string.edit_filter_delete_message).toString(), filter.getName()), Toast.LENGTH_SHORT).show(); EditPOIFilterActivity.this.finish(); } } }); builder.create().show(); return true; } else if (item.getItemId() == R.id.edit_filter_save_as) { Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.edit_filter_save_as_menu_item); final EditText editText = new EditText(this); builder.setView(editText); builder.setNegativeButton(R.string.default_buttons_cancel, null); builder.setPositiveButton(R.string.default_buttons_yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { PoiFilter nFilter = new PoiFilter(editText.getText().toString(), null, filter.getAcceptedTypes(), (OsmandApplication) getApplication()); if (helper.createPoiFilter(nFilter)) { Toast.makeText( EditPOIFilterActivity.this, MessageFormat.format(EditPOIFilterActivity.this.getText(R.string.edit_filter_create_message).toString(), editText.getText().toString()), Toast.LENGTH_SHORT).show(); } EditPOIFilterActivity.this.finish(); } }); builder.create().show(); return true; } return super.onOptionsItemSelected(item); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onOptionsItemSelected"
"@Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.edit_filter_delete) { <MASK>EditPOIFilterActivity.this.finish();</MASK> Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.edit_filter_delete_dialog_title); builder.setNegativeButton(R.string.default_buttons_no, null); builder.setPositiveButton(R.string.default_buttons_yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (helper.removePoiFilter(filter)) { Toast.makeText( EditPOIFilterActivity.this, MessageFormat.format(EditPOIFilterActivity.this.getText(R.string.edit_filter_delete_message).toString(), filter.getName()), Toast.LENGTH_SHORT).show(); } } }); builder.create().show(); return true; } else if (item.getItemId() == R.id.edit_filter_save_as) { Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.edit_filter_save_as_menu_item); final EditText editText = new EditText(this); builder.setView(editText); builder.setNegativeButton(R.string.default_buttons_cancel, null); builder.setPositiveButton(R.string.default_buttons_yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { PoiFilter nFilter = new PoiFilter(editText.getText().toString(), null, filter.getAcceptedTypes(), (OsmandApplication) getApplication()); if (helper.createPoiFilter(nFilter)) { Toast.makeText( EditPOIFilterActivity.this, MessageFormat.format(EditPOIFilterActivity.this.getText(R.string.edit_filter_create_message).toString(), editText.getText().toString()), Toast.LENGTH_SHORT).show(); } <MASK>EditPOIFilterActivity.this.finish();</MASK> } }); builder.create().show(); return true; } return super.onOptionsItemSelected(item); }"
Inversion-Mutation
megadiff
"public void run(String[] args) { registerDefaultCommands(commands); if (args.length == 0) { help(); } String cmd = args[0].toLowerCase(); if (cmd.equals("help") && args.length == 2) { help(args[1]); } Command command = getCommand(commands.get(cmd)); if (command == null) { help(); } command.setName(cmd); if (args.length > 1) { args = Arrays.asList(args).subList(1, args.length) .toArray(new String[args.length - 1]); } else { args = new String[0]; } CommandLineParser parser = new GnuParser(); try { CommandLine cl = parser.parse(command.getOptions(), args); UserData userData = new UserData(); File dataFile = getUserDataFile(); if (dataFile != null) { if (!dataFile.exists()) { System.out.println("Creating " + dataFile); dataFile.createNewFile(); } userData = UserData.load(dataFile); } else { throw new RuntimeException("Unimplemented"); } command.handle(cl, userData); if (dataFile != null && userData.isDirty()) { System.out.println("Saving to " + dataFile + "..."); userData.store(dataFile); } } catch (MissingOptionException e) { System.err.println(e.getMessage()); command.usage(); } catch (Exception e) { e.printStackTrace(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"public void run(String[] args) { registerDefaultCommands(commands); if (args.length == 0) { help(); } String cmd = args[0].toLowerCase(); if (cmd.equals("help") && args.length == 2) { help(args[1]); } Command command = getCommand(commands.get(cmd)); <MASK>command.setName(cmd);</MASK> if (command == null) { help(); } if (args.length > 1) { args = Arrays.asList(args).subList(1, args.length) .toArray(new String[args.length - 1]); } else { args = new String[0]; } CommandLineParser parser = new GnuParser(); try { CommandLine cl = parser.parse(command.getOptions(), args); UserData userData = new UserData(); File dataFile = getUserDataFile(); if (dataFile != null) { if (!dataFile.exists()) { System.out.println("Creating " + dataFile); dataFile.createNewFile(); } userData = UserData.load(dataFile); } else { throw new RuntimeException("Unimplemented"); } command.handle(cl, userData); if (dataFile != null && userData.isDirty()) { System.out.println("Saving to " + dataFile + "..."); userData.store(dataFile); } } catch (MissingOptionException e) { System.err.println(e.getMessage()); command.usage(); } catch (Exception e) { e.printStackTrace(); } }"
Inversion-Mutation
megadiff
"public void popupDismissed(boolean topPopupOnly) { initializePopup(); // if the 2nd level popup gets dismissed if (mPopupStatus == POPUP_SECOND_LEVEL) { mPopupStatus = POPUP_FIRST_LEVEL; if (topPopupOnly) mModule.showPopup(mPopup); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "popupDismissed"
"public void popupDismissed(boolean topPopupOnly) { // if the 2nd level popup gets dismissed if (mPopupStatus == POPUP_SECOND_LEVEL) { <MASK>initializePopup();</MASK> mPopupStatus = POPUP_FIRST_LEVEL; if (topPopupOnly) mModule.showPopup(mPopup); } }"
Inversion-Mutation
megadiff
"Multipart composeMessageBody(QueryListResponse response) throws MessagingException { String html = htmlCreator.generateHtmlForResponse(response); BodyPart mediaPart = new MimeBodyPart(); mediaPart.setContent(html, "text/html"); BodyPart textPart = new MimeBodyPart(); textPart.setText(response.dump()); Multipart messageBody = new MimeMultipart(); messageBody.addBodyPart(textPart); messageBody.addBodyPart(mediaPart); return messageBody; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "composeMessageBody"
"Multipart composeMessageBody(QueryListResponse response) throws MessagingException { String html = htmlCreator.generateHtmlForResponse(response); BodyPart mediaPart = new MimeBodyPart(); mediaPart.setContent(html, "text/html"); BodyPart textPart = new MimeBodyPart(); textPart.setText(response.dump()); Multipart messageBody = new MimeMultipart(); <MASK>messageBody.addBodyPart(mediaPart);</MASK> messageBody.addBodyPart(textPart); return messageBody; }"
Inversion-Mutation
megadiff
"private void listen(final InputStream is) { final BufferedInputStream bi = new BufferedInputStream(is); new Thread() { @Override public void run() { try { while(true) { ByteArrayOutputStream os = new ByteArrayOutputStream(); receive(bi, os); final String name = new String(os.toByteArray(), UTF8); os = new ByteArrayOutputStream(); receive(bi, os); final String data = new String(os.toByteArray(), UTF8); notifiers.get(name).notify(data); } } catch(final IOException ex) { // loop will be quit if no data can be received anymore } } }.start(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "listen"
"private void listen(final InputStream is) { new Thread() { @Override public void run() { try { <MASK>final BufferedInputStream bi = new BufferedInputStream(is);</MASK> while(true) { ByteArrayOutputStream os = new ByteArrayOutputStream(); receive(bi, os); final String name = new String(os.toByteArray(), UTF8); os = new ByteArrayOutputStream(); receive(bi, os); final String data = new String(os.toByteArray(), UTF8); notifiers.get(name).notify(data); } } catch(final IOException ex) { // loop will be quit if no data can be received anymore } } }.start(); }"
Inversion-Mutation
megadiff
"@Override public Element visit(UmlEnum o, OclCopier.Argument argument) { if (argument.map.containsKey(o)) { return argument.map.get(o); } UmlEnum result = new UmlEnum(); argument.map.put(o, result); result.setName(o.getName()); visitElement(o, result, argument); for (UmlClass subClass : o.getSubClasses()) { result.addSubClass((UmlClass) subClass.accept((UmlVisitor<Element, OclCopier.Argument>) this, argument)); } for (UmlClass superClass : o.getSuperClasses()) { result.addSuperClass((UmlClass) superClass.accept((UmlVisitor<Element, OclCopier.Argument>) this, argument)); } for (Operation operation : o.getOperations()) { result.addOperation((Operation) operation.accept(this, argument)); } for (AssociationEnd associationEnd : o.getOwnedAssociationEnds()) { result.addOwnedAssociationEnd((AssociationEnd) associationEnd.accept(this, argument)); } for (Attribute attribute : o.getOwnedAttributes()) { result.addOwnedAttribute((Attribute) attribute.accept(this, argument)); } for (UmlEnumLiteral umlEnumLiteral : o.getLiterals()) { result.addLiteral((UmlEnumLiteral) umlEnumLiteral.accept(this, argument)); } return result; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "visit"
"@Override public Element visit(UmlEnum o, OclCopier.Argument argument) { if (argument.map.containsKey(o)) { return argument.map.get(o); } UmlEnum result = new UmlEnum(); argument.map.put(o, result); visitElement(o, result, argument); <MASK>result.setName(o.getName());</MASK> for (UmlClass subClass : o.getSubClasses()) { result.addSubClass((UmlClass) subClass.accept((UmlVisitor<Element, OclCopier.Argument>) this, argument)); } for (UmlClass superClass : o.getSuperClasses()) { result.addSuperClass((UmlClass) superClass.accept((UmlVisitor<Element, OclCopier.Argument>) this, argument)); } for (Operation operation : o.getOperations()) { result.addOperation((Operation) operation.accept(this, argument)); } for (AssociationEnd associationEnd : o.getOwnedAssociationEnds()) { result.addOwnedAssociationEnd((AssociationEnd) associationEnd.accept(this, argument)); } for (Attribute attribute : o.getOwnedAttributes()) { result.addOwnedAttribute((Attribute) attribute.accept(this, argument)); } for (UmlEnumLiteral umlEnumLiteral : o.getLiterals()) { result.addLiteral((UmlEnumLiteral) umlEnumLiteral.accept(this, argument)); } return result; }"
Inversion-Mutation
megadiff
"public synchronized Future<?> addIndexedColumn(ColumnDefinition cdef) { if (indexesByColumn.containsKey(cdef.name)) return null; assert cdef.getIndexType() != null; SecondaryIndex index; try { index = SecondaryIndex.createInstance(baseCfs, cdef); } catch (ConfigurationException e) { throw new RuntimeException(e); } // Keep a single instance of the index per-cf for row level indexes // since we want all columns to be under the index if (index instanceof PerRowSecondaryIndex) { SecondaryIndex currentIndex = rowLevelIndexMap.get(index.getClass()); if (currentIndex == null) { rowLevelIndexMap.put(index.getClass(), index); index.init(); } else { index = currentIndex; index.addColumnDef(cdef); logger.info("Creating new index : {}",cdef); } } else { index.init(); } // link in indexedColumns. this means that writes will add new data to // the index immediately, // so we don't have to lock everything while we do the build. it's up to // the operator to wait // until the index is actually built before using in queries. indexesByColumn.put(cdef.name, index); // if we're just linking in the index to indexedColumns on an // already-built index post-restart, we're done if (index.isIndexBuilt(cdef.name)) return null; return index.buildIndexAsync(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addIndexedColumn"
"public synchronized Future<?> addIndexedColumn(ColumnDefinition cdef) { if (indexesByColumn.containsKey(cdef.name)) return null; assert cdef.getIndexType() != null; <MASK>logger.info("Creating new index : {}",cdef);</MASK> SecondaryIndex index; try { index = SecondaryIndex.createInstance(baseCfs, cdef); } catch (ConfigurationException e) { throw new RuntimeException(e); } // Keep a single instance of the index per-cf for row level indexes // since we want all columns to be under the index if (index instanceof PerRowSecondaryIndex) { SecondaryIndex currentIndex = rowLevelIndexMap.get(index.getClass()); if (currentIndex == null) { rowLevelIndexMap.put(index.getClass(), index); index.init(); } else { index = currentIndex; index.addColumnDef(cdef); } } else { index.init(); } // link in indexedColumns. this means that writes will add new data to // the index immediately, // so we don't have to lock everything while we do the build. it's up to // the operator to wait // until the index is actually built before using in queries. indexesByColumn.put(cdef.name, index); // if we're just linking in the index to indexedColumns on an // already-built index post-restart, we're done if (index.isIndexBuilt(cdef.name)) return null; return index.buildIndexAsync(); }"
Inversion-Mutation
megadiff
"@Override public void onEnable() { Bukkit.getPluginManager().registerEvents(this, this); Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable() { public void run() { if(new Date().getTime() - lastEgg.getTime() < EGG_FREQUENCY * 1000) return; List<Player> players = new ArrayList<Player>(); List<Item> items = new ArrayList<Item>(); for(World world : Bukkit.getWorlds()) { switch(world.getEnvironment()) { // tall grass check below only applies to normal worlds case NORMAL: // stash all players in this world for random selection later players.addAll(world.getPlayers()); // stash all egg-like items for throttling spawns for(Item item : world.getEntitiesByClass(Item.class)) { switch(item.getItemStack().getType()) { case MONSTER_EGG: case DIAMOND: items.add(item); break; } } break; } } // remove past players to give others a chance players.removeAll(pastPlayers); if(players.isEmpty()) { debug("SKIP! No new players in normal world(s)"); pastPlayers.clear(); return; } if(items.size() > 20) { debug("SKIP! Too many items already spawned"); return; } // select a random player Player player = players.get(random.nextInt(players.size())); debug("Player {0} selected", player); pastPlayers.add(player); World world = player.getWorld(); Location loc = player.getLocation(); int x = loc.getBlockX(); int z = loc.getBlockZ(); // get all nearby long grass blocks List<Block> blocks = new ArrayList<Block>(); for(int dx = -15; dx <= 15; dx++) { // search within 15 x blocks of player if(dx >= -5 && dx <= 5) continue; // skip if within 5 x blocks from player for(int dz = -15; dz <= 15; dz++) { // search within 15 z blocks of player if(dz >= -5 && dz <= 5) continue; // skip if within 5 z blocks from player for(int y = 63; y <= 127; y++) { if(world.getBlockTypeIdAt(x + dx, y, z + dz) == LONG_GRASS) { blocks.add(world.getBlockAt(x + dx, y, z + dz)); } } } } if(blocks.isEmpty()) { debug("SKIP! No nearby long grass blocks found for player"); return; } // select a random long grass block Block block = blocks.get(random.nextInt(blocks.size())); debug("Block {0} selected at {1}", block, block.getLocation()); // drop a random egg-like item within the long grass Item item = block.getWorld().dropItem(block.getLocation(), eggChoices[random.nextInt(eggChoices.length)]); debug("Spawned item {0} at {1}", item, item.getLocation()); // notify server Bukkit.broadcastMessage(String.format("%sA colorful egg was hidden in the tall grass near %s%s.", ChatColor.GRAY, player.getDisplayName(), ChatColor.GRAY)); // update last egg spawn date lastEgg = new Date(); } }, 20 * 60, 20 * 60); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onEnable"
"@Override public void onEnable() { Bukkit.getPluginManager().registerEvents(this, this); Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable() { public void run() { if(new Date().getTime() - lastEgg.getTime() < EGG_FREQUENCY * 1000) return; List<Player> players = new ArrayList<Player>(); List<Item> items = new ArrayList<Item>(); for(World world : Bukkit.getWorlds()) { switch(world.getEnvironment()) { // tall grass check below only applies to normal worlds case NORMAL: // stash all players in this world for random selection later players.addAll(world.getPlayers()); // stash all egg-like items for throttling spawns for(Item item : world.getEntitiesByClass(Item.class)) { switch(item.getItemStack().getType()) { case MONSTER_EGG: case DIAMOND: items.add(item); break; } } break; } } // remove past players to give others a chance players.removeAll(pastPlayers); if(players.isEmpty()) { debug("SKIP! No new players in normal world(s)"); pastPlayers.clear(); return; } if(items.size() > 20) { debug("SKIP! Too many items already spawned"); return; } // select a random player Player player = players.get(random.nextInt(players.size())); debug("Player {0} selected", player); World world = player.getWorld(); Location loc = player.getLocation(); int x = loc.getBlockX(); int z = loc.getBlockZ(); // get all nearby long grass blocks List<Block> blocks = new ArrayList<Block>(); for(int dx = -15; dx <= 15; dx++) { // search within 15 x blocks of player if(dx >= -5 && dx <= 5) continue; // skip if within 5 x blocks from player for(int dz = -15; dz <= 15; dz++) { // search within 15 z blocks of player if(dz >= -5 && dz <= 5) continue; // skip if within 5 z blocks from player for(int y = 63; y <= 127; y++) { if(world.getBlockTypeIdAt(x + dx, y, z + dz) == LONG_GRASS) { blocks.add(world.getBlockAt(x + dx, y, z + dz)); } } } } if(blocks.isEmpty()) { debug("SKIP! No nearby long grass blocks found for player"); return; } // select a random long grass block Block block = blocks.get(random.nextInt(blocks.size())); debug("Block {0} selected at {1}", block, block.getLocation()); // drop a random egg-like item within the long grass Item item = block.getWorld().dropItem(block.getLocation(), eggChoices[random.nextInt(eggChoices.length)]); debug("Spawned item {0} at {1}", item, item.getLocation()); // notify server Bukkit.broadcastMessage(String.format("%sA colorful egg was hidden in the tall grass near %s%s.", ChatColor.GRAY, player.getDisplayName(), ChatColor.GRAY)); // update last egg spawn date lastEgg = new Date(); <MASK>pastPlayers.add(player);</MASK> } }, 20 * 60, 20 * 60); }"
Inversion-Mutation
megadiff
"public void run() { if(new Date().getTime() - lastEgg.getTime() < EGG_FREQUENCY * 1000) return; List<Player> players = new ArrayList<Player>(); List<Item> items = new ArrayList<Item>(); for(World world : Bukkit.getWorlds()) { switch(world.getEnvironment()) { // tall grass check below only applies to normal worlds case NORMAL: // stash all players in this world for random selection later players.addAll(world.getPlayers()); // stash all egg-like items for throttling spawns for(Item item : world.getEntitiesByClass(Item.class)) { switch(item.getItemStack().getType()) { case MONSTER_EGG: case DIAMOND: items.add(item); break; } } break; } } // remove past players to give others a chance players.removeAll(pastPlayers); if(players.isEmpty()) { debug("SKIP! No new players in normal world(s)"); pastPlayers.clear(); return; } if(items.size() > 20) { debug("SKIP! Too many items already spawned"); return; } // select a random player Player player = players.get(random.nextInt(players.size())); debug("Player {0} selected", player); pastPlayers.add(player); World world = player.getWorld(); Location loc = player.getLocation(); int x = loc.getBlockX(); int z = loc.getBlockZ(); // get all nearby long grass blocks List<Block> blocks = new ArrayList<Block>(); for(int dx = -15; dx <= 15; dx++) { // search within 15 x blocks of player if(dx >= -5 && dx <= 5) continue; // skip if within 5 x blocks from player for(int dz = -15; dz <= 15; dz++) { // search within 15 z blocks of player if(dz >= -5 && dz <= 5) continue; // skip if within 5 z blocks from player for(int y = 63; y <= 127; y++) { if(world.getBlockTypeIdAt(x + dx, y, z + dz) == LONG_GRASS) { blocks.add(world.getBlockAt(x + dx, y, z + dz)); } } } } if(blocks.isEmpty()) { debug("SKIP! No nearby long grass blocks found for player"); return; } // select a random long grass block Block block = blocks.get(random.nextInt(blocks.size())); debug("Block {0} selected at {1}", block, block.getLocation()); // drop a random egg-like item within the long grass Item item = block.getWorld().dropItem(block.getLocation(), eggChoices[random.nextInt(eggChoices.length)]); debug("Spawned item {0} at {1}", item, item.getLocation()); // notify server Bukkit.broadcastMessage(String.format("%sA colorful egg was hidden in the tall grass near %s%s.", ChatColor.GRAY, player.getDisplayName(), ChatColor.GRAY)); // update last egg spawn date lastEgg = new Date(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"public void run() { if(new Date().getTime() - lastEgg.getTime() < EGG_FREQUENCY * 1000) return; List<Player> players = new ArrayList<Player>(); List<Item> items = new ArrayList<Item>(); for(World world : Bukkit.getWorlds()) { switch(world.getEnvironment()) { // tall grass check below only applies to normal worlds case NORMAL: // stash all players in this world for random selection later players.addAll(world.getPlayers()); // stash all egg-like items for throttling spawns for(Item item : world.getEntitiesByClass(Item.class)) { switch(item.getItemStack().getType()) { case MONSTER_EGG: case DIAMOND: items.add(item); break; } } break; } } // remove past players to give others a chance players.removeAll(pastPlayers); if(players.isEmpty()) { debug("SKIP! No new players in normal world(s)"); pastPlayers.clear(); return; } if(items.size() > 20) { debug("SKIP! Too many items already spawned"); return; } // select a random player Player player = players.get(random.nextInt(players.size())); debug("Player {0} selected", player); World world = player.getWorld(); Location loc = player.getLocation(); int x = loc.getBlockX(); int z = loc.getBlockZ(); // get all nearby long grass blocks List<Block> blocks = new ArrayList<Block>(); for(int dx = -15; dx <= 15; dx++) { // search within 15 x blocks of player if(dx >= -5 && dx <= 5) continue; // skip if within 5 x blocks from player for(int dz = -15; dz <= 15; dz++) { // search within 15 z blocks of player if(dz >= -5 && dz <= 5) continue; // skip if within 5 z blocks from player for(int y = 63; y <= 127; y++) { if(world.getBlockTypeIdAt(x + dx, y, z + dz) == LONG_GRASS) { blocks.add(world.getBlockAt(x + dx, y, z + dz)); } } } } if(blocks.isEmpty()) { debug("SKIP! No nearby long grass blocks found for player"); return; } // select a random long grass block Block block = blocks.get(random.nextInt(blocks.size())); debug("Block {0} selected at {1}", block, block.getLocation()); // drop a random egg-like item within the long grass Item item = block.getWorld().dropItem(block.getLocation(), eggChoices[random.nextInt(eggChoices.length)]); debug("Spawned item {0} at {1}", item, item.getLocation()); // notify server Bukkit.broadcastMessage(String.format("%sA colorful egg was hidden in the tall grass near %s%s.", ChatColor.GRAY, player.getDisplayName(), ChatColor.GRAY)); // update last egg spawn date lastEgg = new Date(); <MASK>pastPlayers.add(player);</MASK> }"
Inversion-Mutation
megadiff
"@Override public Fitness measure(Schedule schedule) { int violated = 0; for (Nurse nurse : schedule.toEntity()) { List<Shift> allShifts = nurse.getAllShifts(); int reducedIndex = -1; for (int i = 1; i < allShifts.size(); i++) { Shift today = allShifts.get(i - 1); Shift tommorow = allShifts.get(i); if (tommorow == Shift.NIGHT) { int restBetween = Shift.restBetween(today, tommorow); if (restBetween < 8) { violated++; } else if (restBetween < 14) { if (i - reducedIndex < 21) { violated++; } else { reducedIndex = i; } } } } } return new Fitness(violated); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "measure"
"@Override public Fitness measure(Schedule schedule) { int violated = 0; for (Nurse nurse : schedule.toEntity()) { List<Shift> allShifts = nurse.getAllShifts(); for (int i = 1; i < allShifts.size(); i++) { <MASK>int reducedIndex = -1;</MASK> Shift today = allShifts.get(i - 1); Shift tommorow = allShifts.get(i); if (tommorow == Shift.NIGHT) { int restBetween = Shift.restBetween(today, tommorow); if (restBetween < 8) { violated++; } else if (restBetween < 14) { if (i - reducedIndex < 21) { violated++; } else { reducedIndex = i; } } } } } return new Fitness(violated); }"
Inversion-Mutation
megadiff
"protected void transferOutputSettings(TransletOutputHandler output) { // It is an error if this method is called with anything else than // the translet post-processor (TextOutput) if (!(output instanceof TextOutput)) return; TextOutput handler = (TextOutput)output; // Transfer the output method setting if (_method != null) { // Transfer all settings relevant to XML output if (_method.equals("xml")) { if (_standalone != null) handler.setStandalone(_standalone); handler.setType(TextOutput.XML); handler.setCdataElements(_cdata); if (_version != null) handler.setVersion(_version); if (_omitHeader) handler.omitHeader(true); handler.setIndent(_indent); if (_doctypeSystem != null) handler.setDoctype(_doctypeSystem, _doctypePublic); } // Transfer all output settings relevant to HTML output else if (_method.equals("html")) { handler.setType(TextOutput.HTML); handler.setIndent(_indent); handler.setDoctype(_doctypeSystem, _doctypePublic); if (_mediaType != null) handler.setMediaType(_mediaType); } else if (_method.equals("text")) { handler.setType(TextOutput.TEXT); } else { handler.setType(TextOutput.QNAME); } } else { handler.setCdataElements(_cdata); if (_version != null) handler.setVersion(_version); if (_standalone != null) handler.setStandalone(_standalone); if (_omitHeader) handler.omitHeader(true); handler.setIndent(_indent); handler.setDoctype(_doctypeSystem, _doctypePublic); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "transferOutputSettings"
"protected void transferOutputSettings(TransletOutputHandler output) { // It is an error if this method is called with anything else than // the translet post-processor (TextOutput) if (!(output instanceof TextOutput)) return; TextOutput handler = (TextOutput)output; // Transfer the output method setting if (_method != null) { // Transfer all settings relevant to XML output if (_method.equals("xml")) { handler.setType(TextOutput.XML); handler.setCdataElements(_cdata); if (_version != null) handler.setVersion(_version); <MASK>if (_standalone != null) handler.setStandalone(_standalone);</MASK> if (_omitHeader) handler.omitHeader(true); handler.setIndent(_indent); if (_doctypeSystem != null) handler.setDoctype(_doctypeSystem, _doctypePublic); } // Transfer all output settings relevant to HTML output else if (_method.equals("html")) { handler.setType(TextOutput.HTML); handler.setIndent(_indent); handler.setDoctype(_doctypeSystem, _doctypePublic); if (_mediaType != null) handler.setMediaType(_mediaType); } else if (_method.equals("text")) { handler.setType(TextOutput.TEXT); } else { handler.setType(TextOutput.QNAME); } } else { handler.setCdataElements(_cdata); if (_version != null) handler.setVersion(_version); <MASK>if (_standalone != null) handler.setStandalone(_standalone);</MASK> if (_omitHeader) handler.omitHeader(true); handler.setIndent(_indent); handler.setDoctype(_doctypeSystem, _doctypePublic); } }"
Inversion-Mutation
megadiff
"public void updateManagementCenterUrl(String newUrl) { if (newUrl == null) { return; } if (newUrl.equals(managementCenterUrl)) { return; } managementCenterUrl = newUrl; if (!isRunning()) { start(); } urlChanged = true; logger.info("Management Center URL has changed. " + "Hazelcast will connect to Management Center on address: \n" + managementCenterUrl); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "updateManagementCenterUrl"
"public void updateManagementCenterUrl(String newUrl) { if (newUrl == null) { return; } <MASK>managementCenterUrl = newUrl;</MASK> if (newUrl.equals(managementCenterUrl)) { return; } if (!isRunning()) { start(); } urlChanged = true; logger.info("Management Center URL has changed. " + "Hazelcast will connect to Management Center on address: \n" + managementCenterUrl); }"
Inversion-Mutation
megadiff
"static void encodeForRuntime(final Declaration d, final GenerateJsVisitor gen, final RuntimeMetamodelAnnotationGenerator annGen) { gen.out("function(){return{mod:$$METAMODEL$$"); List<TypeParameter> tparms = null; List<ProducedType> satisfies = null; if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Class) { tparms = ((com.redhat.ceylon.compiler.typechecker.model.Class) d).getTypeParameters(); if (((com.redhat.ceylon.compiler.typechecker.model.Class) d).getExtendedType() != null) { gen.out(",'super':"); metamodelTypeNameOrList(d.getUnit().getPackage(), ((com.redhat.ceylon.compiler.typechecker.model.Class) d).getExtendedType(), gen); } satisfies = ((com.redhat.ceylon.compiler.typechecker.model.Class) d).getSatisfiedTypes(); } else if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) { tparms = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getTypeParameters(); satisfies = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getSatisfiedTypes(); } else if (d instanceof MethodOrValue) { gen.out(",", MetamodelGenerator.KEY_TYPE, ":"); //This needs a new setting to resolve types but not type parameters metamodelTypeNameOrList(d.getUnit().getPackage(), ((MethodOrValue)d).getType(), gen); if (d instanceof Method) { gen.out(",", MetamodelGenerator.KEY_PARAMS, ":"); //Parameter types of the first parameter list encodeParameterListForRuntime(((Method)d).getParameterLists().get(0), gen); tparms = ((Method) d).getTypeParameters(); } } if (d.isMember()) { gen.out(",$cont:", gen.getNames().name((Declaration)d.getContainer())); } if (tparms != null && !tparms.isEmpty()) { gen.out(",", MetamodelGenerator.KEY_TYPE_PARAMS, ":{"); boolean first = true; for(TypeParameter tp : tparms) { boolean comma = false; if (!first)gen.out(","); first=false; gen.out(tp.getName(), ":{"); if (tp.isCovariant()) { gen.out("'var':'out'"); comma = true; } else if (tp.isContravariant()) { gen.out("'var':'in'"); comma = true; } List<ProducedType> typelist = tp.getSatisfiedTypes(); if (typelist != null && !typelist.isEmpty()) { if (comma)gen.out(","); gen.out("'satisfies':["); boolean first2 = true; for (ProducedType st : typelist) { if (!first2)gen.out(","); first2=false; metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen); } gen.out("]"); comma = true; } typelist = tp.getCaseTypes(); if (typelist != null && !typelist.isEmpty()) { if (comma)gen.out(","); gen.out("'of':["); boolean first3 = true; for (ProducedType st : typelist) { if (!first3)gen.out(","); first3=false; metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen); } gen.out("]"); comma = true; } if (tp.getDefaultTypeArgument() != null) { if (comma)gen.out(","); gen.out("'def':"); metamodelTypeNameOrList(d.getUnit().getPackage(), tp.getDefaultTypeArgument(), gen); } gen.out("}"); } gen.out("}"); } if (satisfies != null) { gen.out(",satisfies:["); boolean first = true; for (ProducedType st : satisfies) { if (!first)gen.out(","); first=false; metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen); } gen.out("]"); } if (annGen != null) { annGen.generateAnnotations(); } gen.out(",pkg:'", d.getUnit().getPackage().getNameAsString(), "',d:$$METAMODEL$$['"); gen.out(d.getUnit().getPackage().getNameAsString(), "']"); if (d.isToplevel()) { gen.out("['", d.getName(), "']"); } else { ArrayList<String> path = new ArrayList<>(); Declaration p = d; while (p instanceof Declaration) { path.add(0, p.getName()); //Build the path in reverse if (!p.isToplevel()) { if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Class) { path.add(0, p.isAnonymous() ? "$o" : "$c"); } else if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) { path.add(0, "$i"); } else if (p instanceof Method) { path.add(0, "$m"); } else { path.add(0, "$at"); } } Scope s = p.getContainer(); while (s != null && s instanceof Declaration == false) { s = s.getContainer(); } p = (Declaration)s; } //Output path for (String part : path) { gen.out("['", part, "']"); } } gen.out("};}"); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "encodeForRuntime"
"static void encodeForRuntime(final Declaration d, final GenerateJsVisitor gen, final RuntimeMetamodelAnnotationGenerator annGen) { gen.out("function(){return{mod:$$METAMODEL$$"); List<TypeParameter> tparms = null; List<ProducedType> satisfies = null; if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Class) { tparms = ((com.redhat.ceylon.compiler.typechecker.model.Class) d).getTypeParameters(); if (((com.redhat.ceylon.compiler.typechecker.model.Class) d).getExtendedType() != null) { gen.out(",'super':"); metamodelTypeNameOrList(d.getUnit().getPackage(), ((com.redhat.ceylon.compiler.typechecker.model.Class) d).getExtendedType(), gen); } satisfies = ((com.redhat.ceylon.compiler.typechecker.model.Class) d).getSatisfiedTypes(); } else if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) { tparms = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getTypeParameters(); satisfies = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getSatisfiedTypes(); } else if (d instanceof MethodOrValue) { gen.out(",", MetamodelGenerator.KEY_TYPE, ":"); //This needs a new setting to resolve types but not type parameters metamodelTypeNameOrList(d.getUnit().getPackage(), ((MethodOrValue)d).getType(), gen); if (d instanceof Method) { gen.out(",", MetamodelGenerator.KEY_PARAMS, ":"); //Parameter types of the first parameter list encodeParameterListForRuntime(((Method)d).getParameterLists().get(0), gen); tparms = ((Method) d).getTypeParameters(); } } if (d.isMember()) { gen.out(",$cont:", gen.getNames().name((Declaration)d.getContainer())); } if (tparms != null && !tparms.isEmpty()) { gen.out(",", MetamodelGenerator.KEY_TYPE_PARAMS, ":{"); boolean first = true; <MASK>boolean comma = false;</MASK> for(TypeParameter tp : tparms) { if (!first)gen.out(","); first=false; gen.out(tp.getName(), ":{"); if (tp.isCovariant()) { gen.out("'var':'out'"); comma = true; } else if (tp.isContravariant()) { gen.out("'var':'in'"); comma = true; } List<ProducedType> typelist = tp.getSatisfiedTypes(); if (typelist != null && !typelist.isEmpty()) { if (comma)gen.out(","); gen.out("'satisfies':["); boolean first2 = true; for (ProducedType st : typelist) { if (!first2)gen.out(","); first2=false; metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen); } gen.out("]"); comma = true; } typelist = tp.getCaseTypes(); if (typelist != null && !typelist.isEmpty()) { if (comma)gen.out(","); gen.out("'of':["); boolean first3 = true; for (ProducedType st : typelist) { if (!first3)gen.out(","); first3=false; metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen); } gen.out("]"); comma = true; } if (tp.getDefaultTypeArgument() != null) { if (comma)gen.out(","); gen.out("'def':"); metamodelTypeNameOrList(d.getUnit().getPackage(), tp.getDefaultTypeArgument(), gen); } gen.out("}"); } gen.out("}"); } if (satisfies != null) { gen.out(",satisfies:["); boolean first = true; for (ProducedType st : satisfies) { if (!first)gen.out(","); first=false; metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen); } gen.out("]"); } if (annGen != null) { annGen.generateAnnotations(); } gen.out(",pkg:'", d.getUnit().getPackage().getNameAsString(), "',d:$$METAMODEL$$['"); gen.out(d.getUnit().getPackage().getNameAsString(), "']"); if (d.isToplevel()) { gen.out("['", d.getName(), "']"); } else { ArrayList<String> path = new ArrayList<>(); Declaration p = d; while (p instanceof Declaration) { path.add(0, p.getName()); //Build the path in reverse if (!p.isToplevel()) { if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Class) { path.add(0, p.isAnonymous() ? "$o" : "$c"); } else if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) { path.add(0, "$i"); } else if (p instanceof Method) { path.add(0, "$m"); } else { path.add(0, "$at"); } } Scope s = p.getContainer(); while (s != null && s instanceof Declaration == false) { s = s.getContainer(); } p = (Declaration)s; } //Output path for (String part : path) { gen.out("['", part, "']"); } } gen.out("};}"); }"
Inversion-Mutation
megadiff
"@Override public void doPost(HttpServletRequest request, HttpServletResponse response, Identity subject, Identity object) throws IOException { // Check whether the user is public if (subject.getUri().equals(getPublicUser())) { response.getWriter().println("The public user is not allowed to create new models. Please login first."); response.setStatus(403); return; } // Check whether the request contains at least the data and svg parameters if ((request.getParameter("data") != null) && (request.getParameter("svg") != null)) { response.setStatus(201); String title = request.getParameter("title"); if (title == null) title = "New Process"; String type = request.getParameter("type"); if (type == null) type = "/stencilsets/bpmn/bpmn.json"; String summary = request.getParameter("summary"); if (summary == null) summary = "This is a new process."; Identity identity = Identity.newModel(subject, title, type, summary, request.getParameter("svg"), request.getParameter("data")); response.setHeader("location", this.getServerPath(request) + identity.getUri() + "/self"); } else { response.setStatus(400); response.getWriter().println("Data and/or SVG missing"); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doPost"
"@Override public void doPost(HttpServletRequest request, HttpServletResponse response, Identity subject, Identity object) throws IOException { // Check whether the user is public if (subject.getUri().equals(getPublicUser())) { response.getWriter().println("The public user is not allowed to create new models. Please login first."); response.setStatus(403); return; } // Check whether the request contains at least the data and svg parameters if ((request.getParameter("data") != null) && (request.getParameter("svg") != null)) { String title = request.getParameter("title"); if (title == null) title = "New Process"; String type = request.getParameter("type"); if (type == null) type = "/stencilsets/bpmn/bpmn.json"; String summary = request.getParameter("summary"); if (summary == null) summary = "This is a new process."; Identity identity = Identity.newModel(subject, title, type, summary, request.getParameter("svg"), request.getParameter("data")); response.setHeader("location", this.getServerPath(request) + identity.getUri() + "/self"); <MASK>response.setStatus(201);</MASK> } else { response.setStatus(400); response.getWriter().println("Data and/or SVG missing"); } }"
Inversion-Mutation
megadiff
"public void initHStoreSite(HStoreSite hstore_site) { if (t) LOG.trace(String.format("Initializing HStoreSite components at partition %d", this.partitionId)); assert(this.hstore_site == null); this.hstore_site = hstore_site; this.hstore_coordinator = hstore_site.getCoordinator(); this.thresholds = hstore_site.getThresholds(); this.txnInitializer = hstore_site.getTransactionInitializer(); this.queueManager = hstore_site.getTransactionQueueManager(); if (hstore_conf.site.exec_deferrable_queries) { tmp_def_txn = new LocalTransaction(hstore_site); } if (hstore_conf.site.exec_profiling) { EventObservable<?> observable = this.hstore_site.getStartWorkloadObservable(); this.profiler.idle_queue_time.resetOnEventObservable(observable); this.profiler.exec_time.resetOnEventObservable(observable); } // ------------------------------- // SPECULATIVE EXECUTION INITIALIZATION // ------------------------------- if (hstore_conf.site.specexec_markov) { // The MarkovConflictChecker is thread-safe, so we all of the partitions // at this site can reuse the same one. this.specExecChecker = MarkovConflictChecker.singleton(this.catalogContext, this.thresholds); } else { this.specExecChecker = new TableConflictChecker(this.catalogContext); } SchedulerPolicy policy = SchedulerPolicy.get(hstore_conf.site.specexec_scheduler_policy); assert(policy != null) : String.format("Invalid %s '%s'", SchedulerPolicy.class.getSimpleName(), hstore_conf.site.specexec_scheduler_policy); this.specExecScheduler = new SpecExecScheduler(this.catalogContext, this.specExecChecker, this.partitionId, this.queueManager.getInitQueue(this.partitionId), policy, hstore_conf.site.specexec_scheduler_window); this.specExecChecker.setEstimationThresholds(this.thresholds); if (hstore_conf.site.specexec_ignore_all_local) { this.specExecScheduler.setIgnoreAllLocal(true); } // Initialize all of our VoltProcedures handles this.initializeVoltProcedures(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "initHStoreSite"
"public void initHStoreSite(HStoreSite hstore_site) { if (t) LOG.trace(String.format("Initializing HStoreSite components at partition %d", this.partitionId)); assert(this.hstore_site == null); this.hstore_site = hstore_site; this.hstore_coordinator = hstore_site.getCoordinator(); this.thresholds = hstore_site.getThresholds(); <MASK>this.specExecChecker.setEstimationThresholds(this.thresholds);</MASK> this.txnInitializer = hstore_site.getTransactionInitializer(); this.queueManager = hstore_site.getTransactionQueueManager(); if (hstore_conf.site.exec_deferrable_queries) { tmp_def_txn = new LocalTransaction(hstore_site); } if (hstore_conf.site.exec_profiling) { EventObservable<?> observable = this.hstore_site.getStartWorkloadObservable(); this.profiler.idle_queue_time.resetOnEventObservable(observable); this.profiler.exec_time.resetOnEventObservable(observable); } // ------------------------------- // SPECULATIVE EXECUTION INITIALIZATION // ------------------------------- if (hstore_conf.site.specexec_markov) { // The MarkovConflictChecker is thread-safe, so we all of the partitions // at this site can reuse the same one. this.specExecChecker = MarkovConflictChecker.singleton(this.catalogContext, this.thresholds); } else { this.specExecChecker = new TableConflictChecker(this.catalogContext); } SchedulerPolicy policy = SchedulerPolicy.get(hstore_conf.site.specexec_scheduler_policy); assert(policy != null) : String.format("Invalid %s '%s'", SchedulerPolicy.class.getSimpleName(), hstore_conf.site.specexec_scheduler_policy); this.specExecScheduler = new SpecExecScheduler(this.catalogContext, this.specExecChecker, this.partitionId, this.queueManager.getInitQueue(this.partitionId), policy, hstore_conf.site.specexec_scheduler_window); if (hstore_conf.site.specexec_ignore_all_local) { this.specExecScheduler.setIgnoreAllLocal(true); } // Initialize all of our VoltProcedures handles this.initializeVoltProcedures(); }"
Inversion-Mutation
megadiff
"public TestForUpload() { setCompositionRoot(main); main.addComponent(new Label( "This is a simple test for upload application. " + "Upload should work with big files and concurrent " + "requests should not be blocked. Button 'b' reads " + "current state into label below it. Memory receiver " + "streams upload contents into memory. You may track" + "consumption." + "tempfile receiver writes upload to file and " + "should have low memory consumption.")); main .addComponent(new Label( "Clicking on button b updates information about upload components status or same with garbage collector.")); textField = new TextField("Test field"); textFieldValue = new Label(); main.addComponent(textField); main.addComponent(textFieldValue); up = new Upload("Upload", buffer); up.setImmediate(true); up.addListener(new Listener() { private static final long serialVersionUID = -8319074730512324303L; public void componentEvent(Event event) { // print out all events fired by upload for debug purposes System.out.println("Upload fired event | " + event); } }); up.addListener(new StartedListener() { private static final long serialVersionUID = 5508883803861085154L; public void uploadStarted(StartedEvent event) { pi.setVisible(true); pi2.setVisible(true); l.setValue("Started uploading file " + event.getFilename()); textFieldValue .setValue(" TestFields value at the upload start is:" + textField.getValue()); } }); up.addListener(new Upload.FinishedListener() { private static final long serialVersionUID = -3773034195991947371L; public void uploadFinished(FinishedEvent event) { pi.setVisible(false); pi2.setVisible(false); if (event instanceof Upload.FailedEvent) { Exception reason = ((Upload.FailedEvent) event).getReason(); l.setValue("Finished with failure ( " + reason + " ), idle"); } else if (event instanceof Upload.SucceededEvent) { l.setValue("Finished with succes, idle"); } else { l.setValue("Finished with unknow event"); } status.removeAllComponents(); final InputStream stream = buffer.getStream(); if (stream == null) { status.addComponent(new Label( "Upload finished, but output buffer is null")); } else { status.addComponent(new Label("<b>Name:</b> " + event.getFilename(), Label.CONTENT_XHTML)); status.addComponent(new Label("<b>Mimetype:</b> " + event.getMIMEType(), Label.CONTENT_XHTML)); status.addComponent(new Label("<b>Size:</b> " + event.getLength() + " bytes.", Label.CONTENT_XHTML)); status.addComponent(new Link("Download " + buffer.getFileName(), new StreamResource(buffer, buffer.getFileName(), getApplication()))); status.setVisible(true); } setBuffer(); } }); up.addListener(new Upload.ProgressListener() { public void updateProgress(long readBytes, long contentLenght) { pi2.setValue(new Float(readBytes / (float) contentLenght)); refreshMemUsage(); } }); final Button b = new Button("Reed state from upload", this, "readState"); final Button c = new Button("Force GC", this, "gc"); main.addComponent(b); main.addComponent(c); main.addComponent(beSluggish); main.addComponent(throwExecption); main.addComponent(interrupt); interrupt.addListener(new Button.ClickListener() { public void buttonClick(ClickEvent event) { up.interruptUpload(); } }); uploadBufferSelector = new Select("Receiver type"); uploadBufferSelector.setImmediate(true); uploadBufferSelector.addItem("memory"); uploadBufferSelector.setValue("memory"); uploadBufferSelector.addItem("tempfile"); uploadBufferSelector .addListener(new AbstractField.ValueChangeListener() { public void valueChange(ValueChangeEvent event) { setBuffer(); } }); main.addComponent(uploadBufferSelector); main.addComponent(up); l = new Label("Idle"); main.addComponent(l); pi.setVisible(false); pi.setPollingInterval(1000); main.addComponent(pi); pi2.setVisible(false); pi2.setPollingInterval(1000); main.addComponent(pi2); memoryStatus = new Label(); main.addComponent(memoryStatus); status.setVisible(false); main.addComponent(status); final Button restart = new Button("R"); restart.addListener(new Button.ClickListener() { public void buttonClick(ClickEvent event) { getApplication().close(); } }); main.addComponent(restart); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "TestForUpload"
"public TestForUpload() { setCompositionRoot(main); main.addComponent(new Label( "This is a simple test for upload application. " + "Upload should work with big files and concurrent " + "requests should not be blocked. Button 'b' reads " + "current state into label below it. Memory receiver " + "streams upload contents into memory. You may track" + "consumption." + "tempfile receiver writes upload to file and " + "should have low memory consumption.")); main .addComponent(new Label( "Clicking on button b updates information about upload components status or same with garbage collector.")); textField = new TextField("Test field"); textFieldValue = new Label(); main.addComponent(textField); main.addComponent(textFieldValue); up = new Upload("Upload", buffer); up.setImmediate(true); up.addListener(new Listener() { private static final long serialVersionUID = -8319074730512324303L; public void componentEvent(Event event) { // print out all events fired by upload for debug purposes System.out.println("Upload fired event | " + event); } }); up.addListener(new StartedListener() { private static final long serialVersionUID = 5508883803861085154L; public void uploadStarted(StartedEvent event) { pi.setVisible(true); pi2.setVisible(true); l.setValue("Started uploading file " + event.getFilename()); textFieldValue .setValue(" TestFields value at the upload start is:" + textField.getValue()); } }); up.addListener(new Upload.FinishedListener() { private static final long serialVersionUID = -3773034195991947371L; public void uploadFinished(FinishedEvent event) { pi.setVisible(false); pi2.setVisible(false); if (event instanceof Upload.FailedEvent) { Exception reason = ((Upload.FailedEvent) event).getReason(); l.setValue("Finished with failure ( " + reason + " ), idle"); } else if (event instanceof Upload.SucceededEvent) { l.setValue("Finished with succes, idle"); } else { l.setValue("Finished with unknow event"); } <MASK>setBuffer();</MASK> status.removeAllComponents(); final InputStream stream = buffer.getStream(); if (stream == null) { status.addComponent(new Label( "Upload finished, but output buffer is null")); } else { status.addComponent(new Label("<b>Name:</b> " + event.getFilename(), Label.CONTENT_XHTML)); status.addComponent(new Label("<b>Mimetype:</b> " + event.getMIMEType(), Label.CONTENT_XHTML)); status.addComponent(new Label("<b>Size:</b> " + event.getLength() + " bytes.", Label.CONTENT_XHTML)); status.addComponent(new Link("Download " + buffer.getFileName(), new StreamResource(buffer, buffer.getFileName(), getApplication()))); status.setVisible(true); } } }); up.addListener(new Upload.ProgressListener() { public void updateProgress(long readBytes, long contentLenght) { pi2.setValue(new Float(readBytes / (float) contentLenght)); refreshMemUsage(); } }); final Button b = new Button("Reed state from upload", this, "readState"); final Button c = new Button("Force GC", this, "gc"); main.addComponent(b); main.addComponent(c); main.addComponent(beSluggish); main.addComponent(throwExecption); main.addComponent(interrupt); interrupt.addListener(new Button.ClickListener() { public void buttonClick(ClickEvent event) { up.interruptUpload(); } }); uploadBufferSelector = new Select("Receiver type"); uploadBufferSelector.setImmediate(true); uploadBufferSelector.addItem("memory"); uploadBufferSelector.setValue("memory"); uploadBufferSelector.addItem("tempfile"); uploadBufferSelector .addListener(new AbstractField.ValueChangeListener() { public void valueChange(ValueChangeEvent event) { <MASK>setBuffer();</MASK> } }); main.addComponent(uploadBufferSelector); main.addComponent(up); l = new Label("Idle"); main.addComponent(l); pi.setVisible(false); pi.setPollingInterval(1000); main.addComponent(pi); pi2.setVisible(false); pi2.setPollingInterval(1000); main.addComponent(pi2); memoryStatus = new Label(); main.addComponent(memoryStatus); status.setVisible(false); main.addComponent(status); final Button restart = new Button("R"); restart.addListener(new Button.ClickListener() { public void buttonClick(ClickEvent event) { getApplication().close(); } }); main.addComponent(restart); }"
Inversion-Mutation
megadiff
"public void uploadFinished(FinishedEvent event) { pi.setVisible(false); pi2.setVisible(false); if (event instanceof Upload.FailedEvent) { Exception reason = ((Upload.FailedEvent) event).getReason(); l.setValue("Finished with failure ( " + reason + " ), idle"); } else if (event instanceof Upload.SucceededEvent) { l.setValue("Finished with succes, idle"); } else { l.setValue("Finished with unknow event"); } status.removeAllComponents(); final InputStream stream = buffer.getStream(); if (stream == null) { status.addComponent(new Label( "Upload finished, but output buffer is null")); } else { status.addComponent(new Label("<b>Name:</b> " + event.getFilename(), Label.CONTENT_XHTML)); status.addComponent(new Label("<b>Mimetype:</b> " + event.getMIMEType(), Label.CONTENT_XHTML)); status.addComponent(new Label("<b>Size:</b> " + event.getLength() + " bytes.", Label.CONTENT_XHTML)); status.addComponent(new Link("Download " + buffer.getFileName(), new StreamResource(buffer, buffer.getFileName(), getApplication()))); status.setVisible(true); } setBuffer(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "uploadFinished"
"public void uploadFinished(FinishedEvent event) { pi.setVisible(false); pi2.setVisible(false); if (event instanceof Upload.FailedEvent) { Exception reason = ((Upload.FailedEvent) event).getReason(); l.setValue("Finished with failure ( " + reason + " ), idle"); } else if (event instanceof Upload.SucceededEvent) { l.setValue("Finished with succes, idle"); } else { l.setValue("Finished with unknow event"); } <MASK>setBuffer();</MASK> status.removeAllComponents(); final InputStream stream = buffer.getStream(); if (stream == null) { status.addComponent(new Label( "Upload finished, but output buffer is null")); } else { status.addComponent(new Label("<b>Name:</b> " + event.getFilename(), Label.CONTENT_XHTML)); status.addComponent(new Label("<b>Mimetype:</b> " + event.getMIMEType(), Label.CONTENT_XHTML)); status.addComponent(new Label("<b>Size:</b> " + event.getLength() + " bytes.", Label.CONTENT_XHTML)); status.addComponent(new Link("Download " + buffer.getFileName(), new StreamResource(buffer, buffer.getFileName(), getApplication()))); status.setVisible(true); } }"
Inversion-Mutation
megadiff
"public void removeNotify() { super.removeNotify(); if (_propsListener != null) { _session.getProperties().removePropertyChangeListener(_propsListener); _propsListener = null; } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "removeNotify"
"public void removeNotify() { if (_propsListener != null) { _session.getProperties().removePropertyChangeListener(_propsListener); _propsListener = null; } <MASK>super.removeNotify();</MASK> }"
Inversion-Mutation
megadiff
"@SuppressWarnings("unchecked") @Override public void onBrowserEvent(Event event) { int type = DOM.eventGetType(event); if (type == Event.ONCLICK) { if(selectRowOnClick && row.isEnabled()) { boolean status = row.isSelected(); grid.onSelectRow(!status, row, true); } if(fireEvents && row.isEnabled()) { grid.fireRowClickEvent(row); } } if (type == Event.ONDBLCLICK) { if(grid instanceof Grid && ((Grid)grid).isEditable()) { if(fireEvents && row.isEnabled()) { grid.fireBeforeRowEditEvent(row); ((Grid)grid).makeEditable((DataRow) row, this); } } if(fireEvents && row.isEnabled()) { grid.fireRowDoubleClickEvent(row); } return; } if(highlightRowOnMouseOver) { if (type == Event.ONMOUSEOVER) { if(row.isEnabled()) { row.addStyleDependentName("highlighted"); } return; } if (type == Event.ONMOUSEOUT) { if(row.isEnabled()) { row.removeStyleDependentName("highlighted"); } return; } } super.onBrowserEvent(event); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onBrowserEvent"
"@SuppressWarnings("unchecked") @Override public void onBrowserEvent(Event event) { int type = DOM.eventGetType(event); if (type == Event.ONCLICK) { if(selectRowOnClick && row.isEnabled()) { boolean status = row.isSelected(); grid.onSelectRow(!status, row, true); } if(fireEvents && row.isEnabled()) { grid.fireRowClickEvent(row); } } if (type == Event.ONDBLCLICK) { if(grid instanceof Grid && ((Grid)grid).isEditable()) { if(fireEvents && row.isEnabled()) { grid.fireBeforeRowEditEvent(row); } <MASK>((Grid)grid).makeEditable((DataRow) row, this);</MASK> } if(fireEvents && row.isEnabled()) { grid.fireRowDoubleClickEvent(row); } return; } if(highlightRowOnMouseOver) { if (type == Event.ONMOUSEOVER) { if(row.isEnabled()) { row.addStyleDependentName("highlighted"); } return; } if (type == Event.ONMOUSEOUT) { if(row.isEnabled()) { row.removeStyleDependentName("highlighted"); } return; } } super.onBrowserEvent(event); }"
Inversion-Mutation
megadiff
"public ResultGroup buildResultGroup( int parent ) { // Make a place for the result ResultGroup result = new ResultGroup(); // Record the value of the parent group. if( parent != 0 ) result.value = data.name( parent ); // Record the total number of doc hits for the parent group result.totalDocs = count[parent]; // Count the child groups int nSelected = 0; for( int kid = child(parent); kid >= 0; kid = sibling(kid) ) { if( !shouldInclude(kid) ) continue; ++result.totalSubGroups; if( selection[kid] != 0 ) ++nSelected; } // Build an array of the child groups. if( nSelected > 0 ) result.subGroups = new ResultGroup[nSelected]; int rank = 0; int n = 0; for( int kid = child(parent); kid >= 0; kid = sibling(kid) ) { if( !shouldInclude(kid) ) continue; if( selection[kid] != 0 ) { result.subGroups[n] = buildResultGroup( kid ); result.subGroups[n].rank = rank; n++; } ++rank; } assert n == nSelected : "miscount"; // If dochits were requested for this group, grab them. if( maxDocs[parent] != 0 && hitQueue[parent] != null ) buildDocHits( parent, result ); // All done! return result; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "buildResultGroup"
"public ResultGroup buildResultGroup( int parent ) { // Make a place for the result ResultGroup result = new ResultGroup(); // Record the value of the parent group. if( parent != 0 ) result.value = data.name( parent ); // Record the total number of doc hits for the parent group result.totalDocs = count[parent]; // Count the child groups int nSelected = 0; for( int kid = child(parent); kid >= 0; kid = sibling(kid) ) { if( !shouldInclude(kid) ) continue; ++result.totalSubGroups; if( selection[kid] != 0 ) ++nSelected; } // Build an array of the child groups. if( nSelected > 0 ) result.subGroups = new ResultGroup[nSelected]; int rank = 0; int n = 0; for( int kid = child(parent); kid >= 0; kid = sibling(kid) ) { if( !shouldInclude(kid) ) continue; <MASK>++rank;</MASK> if( selection[kid] != 0 ) { result.subGroups[n] = buildResultGroup( kid ); result.subGroups[n].rank = rank; n++; } } assert n == nSelected : "miscount"; // If dochits were requested for this group, grab them. if( maxDocs[parent] != 0 && hitQueue[parent] != null ) buildDocHits( parent, result ); // All done! return result; }"
Inversion-Mutation
megadiff
"private ContextGuard(PyObject manager) { __exit__method = manager.__getattr__("__exit__"); __enter__method = manager.__getattr__("__enter__"); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "ContextGuard"
"private ContextGuard(PyObject manager) { <MASK>__enter__method = manager.__getattr__("__enter__");</MASK> __exit__method = manager.__getattr__("__exit__"); }"
Inversion-Mutation
megadiff
"private Boolean _visitVariable(VariableTree node, Void p) { if (isSynthetic((JFXTree) node)) { return false; } int old = indent; Tree parent = getCurrentPath().getParentPath().getLeaf(); boolean insideFor = parent.getJavaFXKind() == JavaFXKind.FOR_EXPRESSION_FOR; ModifiersTree mods = node.getModifiers(); if (ReformatUtils.hasModifiers(mods, tokens.token().id())) { if (scan(mods, p)) { if (!insideFor) { indent += continuationIndentSize; if (cs.placeNewLineAfterModifiers()) { newline(); } else { space(); } } else { space(); } } } if (indent == old && !insideFor) { indent += continuationIndentSize; } JFXTokenId accepted = acceptAndRollback(ReformatUtils.VARIABLE_KEYWORDS); // put space if this VAR is not parameter if (ReformatUtils.VARIABLE_KEYWORDS.contains(accepted)) { accept(ReformatUtils.VARIABLE_KEYWORDS); space(); } final Name name = node.getName(); if (name != null && !ERROR.contentEquals(name)) { accept(JFXTokenId.IDENTIFIER); } final Tree type = node.getType(); if (type != null && type.getJavaFXKind() != JavaFXKind.TYPE_UNKNOWN) { // #180145 if (processColon()) { if (type instanceof TypeArrayTree) { if (acceptAndRollback(JFXTokenId.NATIVEARRAY) == JFXTokenId.NATIVEARRAY) { accept(JFXTokenId.NATIVEARRAY); space(); // accept(JFXTokenId.OF); accept(JFXTokenId.IDENTIFIER); // lexer bug? space(); } // } else if (type.getJavaFXKind() == JavaFXKind.TYPE_FUNCTIONAL) { // accept(JFXTokenId.FUNCTION); // spaces(cs.spaceBeforeMethodDeclParen() ? 1 : 0); } scan(type, p); } } ExpressionTree initTree = node.getInitializer(); if (initTree != null) { int alignIndent = -1; if (cs.alignMultilineAssignment()) { alignIndent = col; if (!ERROR.contentEquals(name)) { alignIndent -= name.length(); } } spaces(cs.spaceAroundAssignOps() ? 1 : 0); accept(JFXTokenId.EQ); final JavafxBindStatus bindStatus = node.getBindStatus(); if (bindStatus.isUnidiBind() || bindStatus.isBidiBind()) { spaces(cs.spaceAroundAssignOps() ? 1 : 0); accept(JFXTokenId.BIND); } wrapTree(cs.wrapAssignOps(), alignIndent, cs.spaceAroundAssignOps() ? 1 : 0, false, initTree); if (bindStatus.isBidiBind()) { space(); accept(JFXTokenId.WITH); space(); accept(JFXTokenId.INVERSE); } } OnReplaceTree onReplaceTree = node.getOnReplaceTree(); if (onReplaceTree != null) { spaces(1, true); scan(onReplaceTree, p); } processSemicolon(); indent = old; return true; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "_visitVariable"
"private Boolean _visitVariable(VariableTree node, Void p) { if (isSynthetic((JFXTree) node)) { return false; } int old = indent; Tree parent = getCurrentPath().getParentPath().getLeaf(); boolean insideFor = parent.getJavaFXKind() == JavaFXKind.FOR_EXPRESSION_FOR; ModifiersTree mods = node.getModifiers(); if (ReformatUtils.hasModifiers(mods, tokens.token().id())) { if (scan(mods, p)) { if (!insideFor) { indent += continuationIndentSize; if (cs.placeNewLineAfterModifiers()) { newline(); } else { space(); } } else { space(); } } } if (indent == old && !insideFor) { indent += continuationIndentSize; } JFXTokenId accepted = acceptAndRollback(ReformatUtils.VARIABLE_KEYWORDS); // put space if this VAR is not parameter if (ReformatUtils.VARIABLE_KEYWORDS.contains(accepted)) { accept(ReformatUtils.VARIABLE_KEYWORDS); space(); } final Name name = node.getName(); if (name != null && !ERROR.contentEquals(name)) { accept(JFXTokenId.IDENTIFIER); } final Tree type = node.getType(); if (type != null && type.getJavaFXKind() != JavaFXKind.TYPE_UNKNOWN) { // #180145 if (processColon()) { if (type instanceof TypeArrayTree) { if (acceptAndRollback(JFXTokenId.NATIVEARRAY) == JFXTokenId.NATIVEARRAY) { accept(JFXTokenId.NATIVEARRAY); space(); // accept(JFXTokenId.OF); accept(JFXTokenId.IDENTIFIER); // lexer bug? space(); } // } else if (type.getJavaFXKind() == JavaFXKind.TYPE_FUNCTIONAL) { // accept(JFXTokenId.FUNCTION); // spaces(cs.spaceBeforeMethodDeclParen() ? 1 : 0); } scan(type, p); } } ExpressionTree initTree = node.getInitializer(); if (initTree != null) { int alignIndent = -1; if (cs.alignMultilineAssignment()) { alignIndent = col; if (!ERROR.contentEquals(name)) { alignIndent -= name.length(); } } spaces(cs.spaceAroundAssignOps() ? 1 : 0); accept(JFXTokenId.EQ); final JavafxBindStatus bindStatus = node.getBindStatus(); if (bindStatus.isUnidiBind() || bindStatus.isBidiBind()) { spaces(cs.spaceAroundAssignOps() ? 1 : 0); accept(JFXTokenId.BIND); } wrapTree(cs.wrapAssignOps(), alignIndent, cs.spaceAroundAssignOps() ? 1 : 0, false, initTree); if (bindStatus.isBidiBind()) { space(); accept(JFXTokenId.WITH); space(); accept(JFXTokenId.INVERSE); } } <MASK>indent = old;</MASK> OnReplaceTree onReplaceTree = node.getOnReplaceTree(); if (onReplaceTree != null) { spaces(1, true); scan(onReplaceTree, p); } processSemicolon(); return true; }"
Inversion-Mutation
megadiff
"public static void main(String[] args) { Prop filterDirProp = Props.get("project", "filter.dir"); if (filterDirProp == null) { Output.print("^error^ Could not find project.filter.dir property."); System.exit(1); } Map<String, Prop> filterFiles = Props.getProps("filter-files"); if ((filterFiles == null) || filterFiles.isEmpty()) { Output.print("^dbug^ No filter sets specified, nothing to filter."); return; } File filterDir = new File(filterDirProp.value); List<FilterPattern> filterPatterns = new ArrayList<FilterPattern>(filterFiles.size()); for (String filterExp : filterFiles.keySet()) { Prop filterProp = filterFiles.get(filterExp); // if the filterExp is not prefixed with a directory, hard-code to be the filter.dir if (!filterExp.startsWith("**")) { filterExp = FileUtil.pathFromParts(filterDir.getPath(), filterExp); } Pattern filterPattern = AntStyleWildcardUtil.regex(filterExp); boolean include = false; if ((filterProp == null) || "include".equalsIgnoreCase(filterProp.value)) { include = true; } filterPatterns.add(new FilterPattern(filterPattern, include)); } Set<File> files = new HashSet<File>(); getApplicableFiles(filterPatterns, filterDir, files); if (files.isEmpty()) { Output.print("^dbug^ No files matched the filter set."); return; } for (File file : files) { Output.print("^info^ Filtering file %s.", file.getPath()); filter(file); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "main"
"public static void main(String[] args) { Prop filterDirProp = Props.get("project", "filter.dir"); if (filterDirProp == null) { Output.print("^error^ Could not find project.filter.dir property."); System.exit(1); } Map<String, Prop> filterFiles = Props.getProps("filter-files"); if ((filterFiles == null) || filterFiles.isEmpty()) { Output.print("^dbug^ No filter sets specified, nothing to filter."); return; } File filterDir = new File(filterDirProp.value); List<FilterPattern> filterPatterns = new ArrayList<FilterPattern>(filterFiles.size()); for (String filterExp : filterFiles.keySet()) { // if the filterExp is not prefixed with a directory, hard-code to be the filter.dir if (!filterExp.startsWith("**")) { filterExp = FileUtil.pathFromParts(filterDir.getPath(), filterExp); } Pattern filterPattern = AntStyleWildcardUtil.regex(filterExp); boolean include = false; <MASK>Prop filterProp = filterFiles.get(filterExp);</MASK> if ((filterProp == null) || "include".equalsIgnoreCase(filterProp.value)) { include = true; } filterPatterns.add(new FilterPattern(filterPattern, include)); } Set<File> files = new HashSet<File>(); getApplicableFiles(filterPatterns, filterDir, files); if (files.isEmpty()) { Output.print("^dbug^ No files matched the filter set."); return; } for (File file : files) { Output.print("^info^ Filtering file %s.", file.getPath()); filter(file); } }"
Inversion-Mutation
megadiff
"@After public void tearDown() throws Exception { TournamentDao.delete(t); ActorDao.delete(a); PermissionDao.delete(p); ResourceDao.delete(r); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "tearDown"
"@After public void tearDown() throws Exception { TournamentDao.delete(t); <MASK>ResourceDao.delete(r);</MASK> ActorDao.delete(a); PermissionDao.delete(p); }"
Inversion-Mutation
megadiff
"@Override protected RestResult doInBackground(String... args) { try { request = createRequest(); if (isCancelled()) throw new InterruptedException(); OAuthConsumer consumer = Session.getInstance().getOAuthConsumer(); if (consumer != null) { AccessToken accessToken = Session.getInstance().getAccessToken(); if (accessToken != null) { consumer.setTokenWithSecret(accessToken.getKey(), accessToken.getSecret()); } consumer.sign(request); } request.setHeader("Accept-Language", Locale.getDefault().getLanguage()); request.setHeader("API-Client", String.format("uservoice-android-%s", UserVoice.getVersion())); AndroidHttpClient client = AndroidHttpClient.newInstance(String.format("uservoice-android-%s", UserVoice.getVersion()), Session.getInstance().getContext()); if (isCancelled()) throw new InterruptedException(); // TODO it would be nice to find a way to abort the request on cancellation HttpResponse response = client.execute(request); if (isCancelled()) throw new InterruptedException(); HttpEntity responseEntity = response.getEntity(); StatusLine responseStatus = response.getStatusLine(); int statusCode = responseStatus != null ? responseStatus.getStatusCode() : 0; String body = responseEntity != null ? EntityUtils.toString(responseEntity) : null; client.close(); if (isCancelled()) throw new InterruptedException(); return new RestResult(statusCode, new JSONObject(body)); } catch (Exception e) { return new RestResult(e); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doInBackground"
"@Override protected RestResult doInBackground(String... args) { try { request = createRequest(); if (isCancelled()) throw new InterruptedException(); OAuthConsumer consumer = Session.getInstance().getOAuthConsumer(); if (consumer != null) { AccessToken accessToken = Session.getInstance().getAccessToken(); if (accessToken != null) { consumer.setTokenWithSecret(accessToken.getKey(), accessToken.getSecret()); } consumer.sign(request); } request.setHeader("Accept-Language", Locale.getDefault().getLanguage()); request.setHeader("API-Client", String.format("uservoice-android-%s", UserVoice.getVersion())); AndroidHttpClient client = AndroidHttpClient.newInstance(String.format("uservoice-android-%s", UserVoice.getVersion()), Session.getInstance().getContext()); if (isCancelled()) throw new InterruptedException(); // TODO it would be nice to find a way to abort the request on cancellation HttpResponse response = client.execute(request); if (isCancelled()) throw new InterruptedException(); HttpEntity responseEntity = response.getEntity(); StatusLine responseStatus = response.getStatusLine(); int statusCode = responseStatus != null ? responseStatus.getStatusCode() : 0; String body = responseEntity != null ? EntityUtils.toString(responseEntity) : null; if (isCancelled()) throw new InterruptedException(); <MASK>client.close();</MASK> return new RestResult(statusCode, new JSONObject(body)); } catch (Exception e) { return new RestResult(e); } }"
Inversion-Mutation
megadiff
"public void receiveUpdate() { byte[] data = receive(); InputBuffer in = new InputBuffer(data); int type = in.readInt(); if (type==RescueConstants.HEADER_NULL) return; int size = in.readInt(); if (type!=RescueConstants.UPDATE) { System.out.println("I don't know how to deal with "+type); in.skip(size); } else { int id = in.readInt(); int time = in.readInt(); if (id == simID) { WORLD.update(in,time); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "receiveUpdate"
"public void receiveUpdate() { byte[] data = receive(); InputBuffer in = new InputBuffer(data); int type = in.readInt(); if (type==RescueConstants.HEADER_NULL) return; int size = in.readInt(); if (type!=RescueConstants.UPDATE) { System.out.println("I don't know how to deal with "+type); in.skip(size); } else { <MASK>int time = in.readInt();</MASK> int id = in.readInt(); if (id == simID) { WORLD.update(in,time); } } }"
Inversion-Mutation
megadiff
"public void remove() { m_selectedItems.remove(this); removeValue(this); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "remove"
"public void remove() { <MASK>removeValue(this);</MASK> m_selectedItems.remove(this); }"
Inversion-Mutation
megadiff
"public boolean onOptionsItemSelected(MenuItem item) { Synodroid app = (Synodroid) getApplication(); DetailMain main = (DetailMain)mAdapter.getItem(MAIN_ITEM); if (item.getItemId() == R.id.menu_refresh) { try{ if (app.DEBUG) Log.v(Synodroid.DS_TAG,"DetailActivity: Menu refresh selected."); }catch (Exception ex){/*DO NOTHING*/} DetailFiles file = (DetailFiles)mAdapter.getItem(FILE_ITEM); app.forceRefresh(); if (task.isTorrent){ app.executeAsynchronousAction(file, new GetFilesAction(task), false); } return true; } else if (item.getItemId() == MENU_SHARE){ try{ if (app.DEBUG) Log.v(Synodroid.DS_TAG,"DetailActivity: Menu share selected."); }catch (Exception ex){/*DO NOTHING*/} Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT, task.originalLink); intent.putExtra(android.content.Intent.EXTRA_SUBJECT, task.fileName); startActivity(Intent.createChooser(intent, "Share url")); return true; } else if (item.getItemId() == MENU_PAUSE){ try{ if (app.DEBUG) Log.v(Synodroid.DS_TAG,"DetailActivity: Menu pause selected."); }catch (Exception ex){/*DO NOTHING*/} app.executeAction(main, new PauseTaskAction(task), true); return true; } else if (item.getItemId() == MENU_DELETE || item.getItemId() == MENU_CANCEL || item.getItemId() == MENU_CLEAR){ try{ if (app.DEBUG) Log.v(Synodroid.DS_TAG,"DetailActivity: Menu cancel/delete/clear selected."); }catch (Exception ex){/*DO NOTHING*/} app.executeAction(main, new DeleteTaskAction(task), true); return true; } else if (item.getItemId() == MENU_RESUME || item.getItemId() == MENU_RETRY){ try{ if (app.DEBUG) Log.v(Synodroid.DS_TAG,"DetailActivity: Menu resume/retry selected."); }catch (Exception ex){/*DO NOTHING*/} app.executeAction(main, new ResumeTaskAction(task), true); return true; } else if (item.getItemId() == MENU_PARAMETERS){ try{ if (app.DEBUG) Log.v(Synodroid.DS_TAG,"DetailActivity: Menu task properties selected."); }catch (Exception ex){/*DO NOTHING*/} try { if (app.getServer().getDsmVersion().greaterThen(DSMVersion.VERSION3_0)) { app.executeAsynchronousAction(main, new GetTaskPropertiesAction(task), false, false); } else { showDialog(TASK_PARAMETERS_DIALOG); } } catch (Exception e) { try{ if (app.DEBUG) Log.e(Synodroid.DS_TAG,"DetailActivity: Failed to execute action on task properties. Ignoring..."); }catch (Exception ex){/*DO NOTHING*/} } return true; } else if (item.getItemId() == MENU_DESTINATION){ try{ if (app.DEBUG) Log.v(Synodroid.DS_TAG,"DetailActivity: Menu destination selected."); }catch (Exception ex){/*DO NOTHING*/} try { if (app.getServer().getDsmVersion().greaterThen(DSMVersion.VERSION3_0)){ app.executeAsynchronousAction(main, new GetDirectoryListShares("remote/"+destination), false); } else{ app.executeAsynchronousAction(main, new EnumShareAction(), false); } } catch (NullPointerException e) { try{ if (app.DEBUG) Log.e(Synodroid.DS_TAG,"DetailActivity: Failed to execute action on task destination. Ignoring..."); }catch (Exception ex){/*DO NOTHING*/} } return true; } return super.onOptionsItemSelected(item); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onOptionsItemSelected"
"public boolean onOptionsItemSelected(MenuItem item) { Synodroid app = (Synodroid) getApplication(); DetailMain main = (DetailMain)mAdapter.getItem(MAIN_ITEM); if (item.getItemId() == R.id.menu_refresh) { try{ if (app.DEBUG) Log.v(Synodroid.DS_TAG,"DetailActivity: Menu refresh selected."); }catch (Exception ex){/*DO NOTHING*/} DetailFiles file = (DetailFiles)mAdapter.getItem(FILE_ITEM); if (task.isTorrent){ <MASK>app.forceRefresh();</MASK> app.executeAsynchronousAction(file, new GetFilesAction(task), false); } return true; } else if (item.getItemId() == MENU_SHARE){ try{ if (app.DEBUG) Log.v(Synodroid.DS_TAG,"DetailActivity: Menu share selected."); }catch (Exception ex){/*DO NOTHING*/} Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT, task.originalLink); intent.putExtra(android.content.Intent.EXTRA_SUBJECT, task.fileName); startActivity(Intent.createChooser(intent, "Share url")); return true; } else if (item.getItemId() == MENU_PAUSE){ try{ if (app.DEBUG) Log.v(Synodroid.DS_TAG,"DetailActivity: Menu pause selected."); }catch (Exception ex){/*DO NOTHING*/} app.executeAction(main, new PauseTaskAction(task), true); return true; } else if (item.getItemId() == MENU_DELETE || item.getItemId() == MENU_CANCEL || item.getItemId() == MENU_CLEAR){ try{ if (app.DEBUG) Log.v(Synodroid.DS_TAG,"DetailActivity: Menu cancel/delete/clear selected."); }catch (Exception ex){/*DO NOTHING*/} app.executeAction(main, new DeleteTaskAction(task), true); return true; } else if (item.getItemId() == MENU_RESUME || item.getItemId() == MENU_RETRY){ try{ if (app.DEBUG) Log.v(Synodroid.DS_TAG,"DetailActivity: Menu resume/retry selected."); }catch (Exception ex){/*DO NOTHING*/} app.executeAction(main, new ResumeTaskAction(task), true); return true; } else if (item.getItemId() == MENU_PARAMETERS){ try{ if (app.DEBUG) Log.v(Synodroid.DS_TAG,"DetailActivity: Menu task properties selected."); }catch (Exception ex){/*DO NOTHING*/} try { if (app.getServer().getDsmVersion().greaterThen(DSMVersion.VERSION3_0)) { app.executeAsynchronousAction(main, new GetTaskPropertiesAction(task), false, false); } else { showDialog(TASK_PARAMETERS_DIALOG); } } catch (Exception e) { try{ if (app.DEBUG) Log.e(Synodroid.DS_TAG,"DetailActivity: Failed to execute action on task properties. Ignoring..."); }catch (Exception ex){/*DO NOTHING*/} } return true; } else if (item.getItemId() == MENU_DESTINATION){ try{ if (app.DEBUG) Log.v(Synodroid.DS_TAG,"DetailActivity: Menu destination selected."); }catch (Exception ex){/*DO NOTHING*/} try { if (app.getServer().getDsmVersion().greaterThen(DSMVersion.VERSION3_0)){ app.executeAsynchronousAction(main, new GetDirectoryListShares("remote/"+destination), false); } else{ app.executeAsynchronousAction(main, new EnumShareAction(), false); } } catch (NullPointerException e) { try{ if (app.DEBUG) Log.e(Synodroid.DS_TAG,"DetailActivity: Failed to execute action on task destination. Ignoring..."); }catch (Exception ex){/*DO NOTHING*/} } return true; } return super.onOptionsItemSelected(item); }"
Inversion-Mutation
megadiff
"public static void main(String[] args) throws Exception { if( args.length != 2) { System.out.println("Usage SplitFasta fileToSplit numSequencesPerSplit"); System.exit(1); } FastaSequenceOneAtATime fsoat = new FastaSequenceOneAtATime(args[0]); int splitSize = Integer.parseInt(args[1]); int count=0; int file =1; long seqNum =0; BufferedWriter writer = new BufferedWriter(new FileWriter(new File(args[0] + "_FILE_" + file))); for( FastaSequence fs = fsoat.getNextSequence(); fs != null; fs = fsoat.getNextSequence() ) { count++; if( fs.getSequence().length() != 200 ) throw new Exception("Expecting a 200 basepair length"); if( count == splitSize) { writer.flush(); writer.close(); count =0; writer = new BufferedWriter(new FileWriter(new File(args[0] + "_FILE_" + file))); System.out.println("Finished " + args[0] + "_FILE_" + file); file++; } seqNum++; writer.write(">A" + seqNum + "\n"); writer.write(fs.getSequence().substring(0, 100) + "\n"); seqNum++; writer.write(">A" + seqNum + "\n"); writer.write(fs.getSequence().substring(100, fs.getSequence().length()) + "\n"); } System.out.println("Finished"); writer.flush(); writer.close(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "main"
"public static void main(String[] args) throws Exception { if( args.length != 2) { System.out.println("Usage SplitFasta fileToSplit numSequencesPerSplit"); System.exit(1); } FastaSequenceOneAtATime fsoat = new FastaSequenceOneAtATime(args[0]); int splitSize = Integer.parseInt(args[1]); int count=0; int file =1; long seqNum =0; BufferedWriter writer = new BufferedWriter(new FileWriter(new File(args[0] + "_FILE_" + file))); for( FastaSequence fs = fsoat.getNextSequence(); fs != null; fs = fsoat.getNextSequence() ) { count++; if( fs.getSequence().length() != 200 ) throw new Exception("Expecting a 200 basepair length"); if( count == splitSize) { writer.flush(); writer.close(); count =0; writer = new BufferedWriter(new FileWriter(new File(args[0] + "_FILE_" + file))); System.out.println("Finished " + args[0] + "_FILE_" + file); file++; } <MASK>writer.write(">A" + seqNum + "\n");</MASK> seqNum++; writer.write(fs.getSequence().substring(0, 100) + "\n"); seqNum++; <MASK>writer.write(">A" + seqNum + "\n");</MASK> writer.write(fs.getSequence().substring(100, fs.getSequence().length()) + "\n"); } System.out.println("Finished"); writer.flush(); writer.close(); }"
Inversion-Mutation
megadiff
"private static void callLoginListner(final UserView userView, final AuthenticationListner authenticationListner) { final TransactionalThread thread = new TransactionalThread() { final VirtualHost virtualHost = VirtualHost.getVirtualHostForThread(); @Override public void transactionalRun() { try { VirtualHost.setVirtualHostForThread(virtualHost); authenticationListner.afterLogin(userView); } finally { VirtualHost.releaseVirtualHostFromThread(); } } }; thread.start(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "callLoginListner"
"private static void callLoginListner(final UserView userView, final AuthenticationListner authenticationListner) { final TransactionalThread thread = new TransactionalThread() { final VirtualHost virtualHost = VirtualHost.getVirtualHostForThread(); @Override public void transactionalRun() { <MASK>authenticationListner.afterLogin(userView);</MASK> try { VirtualHost.setVirtualHostForThread(virtualHost); } finally { VirtualHost.releaseVirtualHostFromThread(); } } }; thread.start(); }"
Inversion-Mutation
megadiff
"@Override public void transactionalRun() { try { VirtualHost.setVirtualHostForThread(virtualHost); authenticationListner.afterLogin(userView); } finally { VirtualHost.releaseVirtualHostFromThread(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "transactionalRun"
"@Override public void transactionalRun() { <MASK>authenticationListner.afterLogin(userView);</MASK> try { VirtualHost.setVirtualHostForThread(virtualHost); } finally { VirtualHost.releaseVirtualHostFromThread(); } }"
Inversion-Mutation
megadiff
"@Override public void onPrepared(final MediaPlayer mp) { onMediaPlayerInfoNative(MEDIA_PLAYER_READY, 0, mID); onMediaPlayerInfoNative(MEDIA_PLAYER_DURATION, getDuration(), mID); mPreparing = false; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onPrepared"
"@Override public void onPrepared(final MediaPlayer mp) { <MASK>onMediaPlayerInfoNative(MEDIA_PLAYER_DURATION, getDuration(), mID);</MASK> onMediaPlayerInfoNative(MEDIA_PLAYER_READY, 0, mID); mPreparing = false; }"
Inversion-Mutation
megadiff
"public static byte[] encodeArtDmxPacket(final String univers, final String network, final int dmx[] ) throws IOException { final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // Prepare next trame artDmxCounter++; // ID. byteArrayOutputStream.write(ByteUtils.toByta(Constants.ID)); byteArrayOutputStream.write(MagicNumbers.MAGIC_NUMBER_ZERO); // OpOutput byteArrayOutputStream.write(ByteUtilsArt.in16toByte(20480)); // Version byteArrayOutputStream.write(MagicNumbers.MAGIC_NUMBER_ZERO); byteArrayOutputStream.write(new Integer(Constants.ART_NET_VERSION).byteValue()); // Sequence byteArrayOutputStream.write(ByteUtilsArt.in8toByte(artDmxCounter)); // Physical byteArrayOutputStream.write(MagicNumbers.MAGIC_NUMBER_ZERO); // Net Switch byteArrayOutputStream.write(Integer.parseInt(univers, MagicNumbers.MAGIC_NUMBER_16)); byteArrayOutputStream.write(Integer.parseInt(network, MagicNumbers.MAGIC_NUMBER_16)); // DMX data Length byteArrayOutputStream.write(ByteUtilsArt.in16toBit(dmx.length)); byte bdmx; for(int i=0; i!=Constants.DMX_512_SIZE; i++) { if(dmx.length>i) { bdmx = (byte) dmx[i]; byteArrayOutputStream.write(ByteUtilsArt.in8toByte(bdmx)); } else { byteArrayOutputStream.write(ByteUtilsArt.in8toByte(MagicNumbers.MAGIC_NUMBER_ZERO)); } } return byteArrayOutputStream.toByteArray(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "encodeArtDmxPacket"
"public static byte[] encodeArtDmxPacket(final String univers, final String network, final int dmx[] ) throws IOException { final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // Prepare next trame artDmxCounter++; // ID. byteArrayOutputStream.write(ByteUtils.toByta(Constants.ID)); byteArrayOutputStream.write(MagicNumbers.MAGIC_NUMBER_ZERO); // OpOutput byteArrayOutputStream.write(ByteUtilsArt.in16toByte(20480)); // Version <MASK>byteArrayOutputStream.write(new Integer(Constants.ART_NET_VERSION).byteValue());</MASK> byteArrayOutputStream.write(MagicNumbers.MAGIC_NUMBER_ZERO); // Sequence byteArrayOutputStream.write(ByteUtilsArt.in8toByte(artDmxCounter)); // Physical byteArrayOutputStream.write(MagicNumbers.MAGIC_NUMBER_ZERO); // Net Switch byteArrayOutputStream.write(Integer.parseInt(univers, MagicNumbers.MAGIC_NUMBER_16)); byteArrayOutputStream.write(Integer.parseInt(network, MagicNumbers.MAGIC_NUMBER_16)); // DMX data Length byteArrayOutputStream.write(ByteUtilsArt.in16toBit(dmx.length)); byte bdmx; for(int i=0; i!=Constants.DMX_512_SIZE; i++) { if(dmx.length>i) { bdmx = (byte) dmx[i]; byteArrayOutputStream.write(ByteUtilsArt.in8toByte(bdmx)); } else { byteArrayOutputStream.write(ByteUtilsArt.in8toByte(MagicNumbers.MAGIC_NUMBER_ZERO)); } } return byteArrayOutputStream.toByteArray(); }"
Inversion-Mutation
megadiff
"private void refreshStatus() { this.progressBar.getDisplay().syncExec(new Runnable() { @Override public void run() { if (connected) { if (EngineStatus.IDLE_XML_LOADED.equals(engineStatus)) { progressBar.setEnabled(true); currentPosition = 0; LOGGER.debug("new Scan -> enable ProgressBar"); } else if (EngineStatus.IDLE_NO_XML_LOADED.equals(engineStatus)) { progressBar.setEnabled(false); LOGGER.debug("no Scan -> disable ProgressBar"); } } else { progressBar.setEnabled(false); } } }); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "refreshStatus"
"private void refreshStatus() { this.progressBar.getDisplay().syncExec(new Runnable() { @Override public void run() { if (connected) { if (EngineStatus.IDLE_XML_LOADED.equals(engineStatus)) { progressBar.setEnabled(true); LOGGER.debug("new Scan -> enable ProgressBar"); } else if (EngineStatus.IDLE_NO_XML_LOADED.equals(engineStatus)) { progressBar.setEnabled(false); <MASK>currentPosition = 0;</MASK> LOGGER.debug("no Scan -> disable ProgressBar"); } } else { progressBar.setEnabled(false); } } }); }"
Inversion-Mutation
megadiff
"@Override public void run() { if (connected) { if (EngineStatus.IDLE_XML_LOADED.equals(engineStatus)) { progressBar.setEnabled(true); currentPosition = 0; LOGGER.debug("new Scan -> enable ProgressBar"); } else if (EngineStatus.IDLE_NO_XML_LOADED.equals(engineStatus)) { progressBar.setEnabled(false); LOGGER.debug("no Scan -> disable ProgressBar"); } } else { progressBar.setEnabled(false); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"@Override public void run() { if (connected) { if (EngineStatus.IDLE_XML_LOADED.equals(engineStatus)) { progressBar.setEnabled(true); LOGGER.debug("new Scan -> enable ProgressBar"); } else if (EngineStatus.IDLE_NO_XML_LOADED.equals(engineStatus)) { progressBar.setEnabled(false); <MASK>currentPosition = 0;</MASK> LOGGER.debug("no Scan -> disable ProgressBar"); } } else { progressBar.setEnabled(false); } }"
Inversion-Mutation
megadiff
"private int idForplaylist(String name) { Cursor c = MusicUtils.query(this, MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, new String[] { MediaStore.Audio.Playlists._ID }, MediaStore.Audio.Playlists.NAME + "=?", new String[] { name }, MediaStore.Audio.Playlists.NAME); int id = -1; if (c != null) { c.moveToFirst(); if (!c.isAfterLast()) { id = c.getInt(0); } c.close(); } return id; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "idForplaylist"
"private int idForplaylist(String name) { Cursor c = MusicUtils.query(this, MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, new String[] { MediaStore.Audio.Playlists._ID }, MediaStore.Audio.Playlists.NAME + "=?", new String[] { name }, MediaStore.Audio.Playlists.NAME); int id = -1; if (c != null) { c.moveToFirst(); if (!c.isAfterLast()) { id = c.getInt(0); } } <MASK>c.close();</MASK> return id; }"
Inversion-Mutation
megadiff
"protected final void scanElementDecl() throws IOException, XNIException { // spaces fReportEntity = false; if (!skipSeparator(true, !scanningInternalSubset())) { reportFatalError("MSG_SPACE_REQUIRED_BEFORE_ELEMENT_TYPE_IN_ELEMENTDECL", null); } // element name String name = fEntityScanner.scanName(); if (name == null) { reportFatalError("MSG_ELEMENT_TYPE_REQUIRED_IN_ELEMENTDECL", null); } // spaces if (!skipSeparator(true, !scanningInternalSubset())) { reportFatalError("MSG_SPACE_REQUIRED_BEFORE_CONTENTSPEC_IN_ELEMENTDECL", new Object[]{name}); } // content model if (fDTDContentModelHandler != null) { fDTDContentModelHandler.startContentModel(name); } String contentModel = null; fReportEntity = true; if (fEntityScanner.skipString("EMPTY")) { contentModel = "EMPTY"; // call handler if (fDTDContentModelHandler != null) { fDTDContentModelHandler.empty(); } } else if (fEntityScanner.skipString("ANY")) { contentModel = "ANY"; // call handler if (fDTDContentModelHandler != null) { fDTDContentModelHandler.any(); } } else { if (!fEntityScanner.skipChar('(')) { reportFatalError("MSG_OPEN_PAREN_OR_ELEMENT_TYPE_REQUIRED_IN_CHILDREN", new Object[]{name}); } if (fDTDContentModelHandler != null) { fDTDContentModelHandler.startGroup(); } fStringBuffer.clear(); fStringBuffer.append('('); fMarkUpDepth++; skipSeparator(false, !scanningInternalSubset()); // Mixed content model if (fEntityScanner.skipString("#PCDATA")) { scanMixed(name); } else { // children content scanChildren(name); } contentModel = fStringBuffer.toString(); } // call handler if (fDTDContentModelHandler != null) { fDTDContentModelHandler.endContentModel(); } fReportEntity = false; skipSeparator(false, !scanningInternalSubset()); fReportEntity = true; // end if (!fEntityScanner.skipChar('>')) { reportFatalError("ElementDeclUnterminated", new Object[]{name}); } fMarkUpDepth--; // call handler if (fDTDHandler != null) { fDTDHandler.elementDecl(name, contentModel); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "scanElementDecl"
"protected final void scanElementDecl() throws IOException, XNIException { // spaces fReportEntity = false; if (!skipSeparator(true, !scanningInternalSubset())) { reportFatalError("MSG_SPACE_REQUIRED_BEFORE_ELEMENT_TYPE_IN_ELEMENTDECL", null); } <MASK>fReportEntity = true;</MASK> // element name String name = fEntityScanner.scanName(); if (name == null) { reportFatalError("MSG_ELEMENT_TYPE_REQUIRED_IN_ELEMENTDECL", null); } // spaces if (!skipSeparator(true, !scanningInternalSubset())) { reportFatalError("MSG_SPACE_REQUIRED_BEFORE_CONTENTSPEC_IN_ELEMENTDECL", new Object[]{name}); } // content model if (fDTDContentModelHandler != null) { fDTDContentModelHandler.startContentModel(name); } String contentModel = null; if (fEntityScanner.skipString("EMPTY")) { contentModel = "EMPTY"; // call handler if (fDTDContentModelHandler != null) { fDTDContentModelHandler.empty(); } } else if (fEntityScanner.skipString("ANY")) { contentModel = "ANY"; // call handler if (fDTDContentModelHandler != null) { fDTDContentModelHandler.any(); } } else { if (!fEntityScanner.skipChar('(')) { reportFatalError("MSG_OPEN_PAREN_OR_ELEMENT_TYPE_REQUIRED_IN_CHILDREN", new Object[]{name}); } if (fDTDContentModelHandler != null) { fDTDContentModelHandler.startGroup(); } fStringBuffer.clear(); fStringBuffer.append('('); fMarkUpDepth++; skipSeparator(false, !scanningInternalSubset()); // Mixed content model if (fEntityScanner.skipString("#PCDATA")) { scanMixed(name); } else { // children content scanChildren(name); } contentModel = fStringBuffer.toString(); } // call handler if (fDTDContentModelHandler != null) { fDTDContentModelHandler.endContentModel(); } fReportEntity = false; skipSeparator(false, !scanningInternalSubset()); <MASK>fReportEntity = true;</MASK> // end if (!fEntityScanner.skipChar('>')) { reportFatalError("ElementDeclUnterminated", new Object[]{name}); } fMarkUpDepth--; // call handler if (fDTDHandler != null) { fDTDHandler.elementDecl(name, contentModel); } }"
Inversion-Mutation
megadiff
"private void init(){ this.setFocusable(true); this.addKeyListener(gc); this.addMouseMotionListener(new MoveCursor()); this.addMouseListener(gc); componentListener = new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { gameSupport.resize(getSize()); repaint();} @Override public void componentShown (ComponentEvent e) { gameSupport.resize(getSize()); repaint();} }; this.addComponentListener(componentListener); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "init"
"private void init(){ this.setFocusable(true); this.addKeyListener(gc); this.addMouseMotionListener(new MoveCursor()); this.addMouseListener(gc); <MASK>this.addComponentListener(componentListener);</MASK> componentListener = new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { gameSupport.resize(getSize()); repaint();} @Override public void componentShown (ComponentEvent e) { gameSupport.resize(getSize()); repaint();} }; }"
Inversion-Mutation
megadiff
"private void updateProviderListenersLocked(String provider, boolean enabled) { int listeners = 0; LocationProviderProxy p = mProvidersByName.get(provider); if (p == null) { return; } ArrayList<Receiver> deadReceivers = null; ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider); if (records != null) { final int N = records.size(); for (int i=0; i<N; i++) { UpdateRecord record = records.get(i); // Sends a notification message to the receiver if (!record.mReceiver.callProviderEnabledLocked(provider, enabled)) { if (deadReceivers == null) { deadReceivers = new ArrayList<Receiver>(); } deadReceivers.add(record.mReceiver); } listeners++; } } if (deadReceivers != null) { for (int i=deadReceivers.size()-1; i>=0; i--) { removeUpdatesLocked(deadReceivers.get(i)); } } if (enabled) { p.enable(); if (listeners > 0) { p.setMinTime(getMinTimeLocked(provider)); p.enableLocationTracking(true); } } else { p.enableLocationTracking(false); p.disable(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "updateProviderListenersLocked"
"private void updateProviderListenersLocked(String provider, boolean enabled) { int listeners = 0; LocationProviderProxy p = mProvidersByName.get(provider); if (p == null) { return; } ArrayList<Receiver> deadReceivers = null; ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider); if (records != null) { final int N = records.size(); for (int i=0; i<N; i++) { UpdateRecord record = records.get(i); // Sends a notification message to the receiver if (!record.mReceiver.callProviderEnabledLocked(provider, enabled)) { if (deadReceivers == null) { deadReceivers = new ArrayList<Receiver>(); <MASK>deadReceivers.add(record.mReceiver);</MASK> } } listeners++; } } if (deadReceivers != null) { for (int i=deadReceivers.size()-1; i>=0; i--) { removeUpdatesLocked(deadReceivers.get(i)); } } if (enabled) { p.enable(); if (listeners > 0) { p.setMinTime(getMinTimeLocked(provider)); p.enableLocationTracking(true); } } else { p.enableLocationTracking(false); p.disable(); } }"
Inversion-Mutation
megadiff
"public void destroy() { mContent.destroy(); disableRemoteDebugging(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "destroy"
"public void destroy() { <MASK>disableRemoteDebugging();</MASK> mContent.destroy(); }"
Inversion-Mutation
megadiff
"public TalkingLine() { condPar = new ArrayList<ConditionParser>(); consPar = new ArrayList<ConsequenceParser>(); condPar.add(new illarion.easynpc.parser.talk.conditions.State()); condPar.add(new illarion.easynpc.parser.talk.conditions.Skill()); condPar.add(new illarion.easynpc.parser.talk.conditions.Attribute()); condPar.add(new illarion.easynpc.parser.talk.conditions.MagicType()); condPar.add(new illarion.easynpc.parser.talk.conditions.Money()); condPar.add(new illarion.easynpc.parser.talk.conditions.Race()); condPar.add(new illarion.easynpc.parser.talk.conditions.Queststatus()); condPar.add(new illarion.easynpc.parser.talk.conditions.Item()); condPar.add(new illarion.easynpc.parser.talk.conditions.Language()); condPar.add(new illarion.easynpc.parser.talk.conditions.Chance()); condPar.add(new illarion.easynpc.parser.talk.conditions.Town()); condPar.add(new illarion.easynpc.parser.talk.conditions.Number()); condPar.add(new illarion.easynpc.parser.talk.conditions.Talkstate()); condPar.add(new illarion.easynpc.parser.talk.conditions.Sex()); condPar.add(new illarion.easynpc.parser.talk.conditions.Admin()); condPar.add(new illarion.easynpc.parser.talk.conditions.Trigger()); consPar.add(new illarion.easynpc.parser.talk.consequences.Inform()); consPar.add(new illarion.easynpc.parser.talk.consequences.Answer()); consPar.add(new illarion.easynpc.parser.talk.consequences.State()); consPar.add(new illarion.easynpc.parser.talk.consequences.Skill()); consPar.add(new illarion.easynpc.parser.talk.consequences.Attribute()); consPar.add(new illarion.easynpc.parser.talk.consequences.Rune()); consPar.add(new illarion.easynpc.parser.talk.consequences.Money()); consPar.add(new illarion.easynpc.parser.talk.consequences.DeleteItem()); consPar.add(new illarion.easynpc.parser.talk.consequences.Item()); consPar.add(new illarion.easynpc.parser.talk.consequences.Queststatus()); consPar.add(new illarion.easynpc.parser.talk.consequences.Rankpoints()); consPar.add(new illarion.easynpc.parser.talk.consequences.Talkstate()); consPar.add(new illarion.easynpc.parser.talk.consequences.Trade()); consPar.add(new illarion.easynpc.parser.talk.consequences.Treasure()); consPar.add(new illarion.easynpc.parser.talk.consequences.Introduce()); consPar.add(new illarion.easynpc.parser.talk.consequences.Warp()); final List<ConditionParser> conditionsList = condPar; final List<ConsequenceParser> consequenceList = consPar; conditionDocu = new DocuEntry() { @SuppressWarnings("nls") @Override public DocuEntry getChild(final int index) { if ((index < 0) || (index >= conditionsList.size())) { throw new IllegalArgumentException("Index out of range"); } return conditionsList.get(index); } @Override public int getChildCount() { return conditionsList.size(); } @SuppressWarnings("nls") @Override public String getDescription() { return Lang.getMsg(TalkingLine.class, "Conditions.Docu.description"); } @Override public String getExample() { return null; } @Override public String getSyntax() { return null; } @Override @SuppressWarnings("nls") public String getTitle() { return Lang.getMsg(TalkingLine.class, "Conditions.Docu.title"); } }; consequenceDocu = new DocuEntry() { @SuppressWarnings("nls") @Override public DocuEntry getChild(final int index) { if ((index < 0) || (index >= consequenceList.size())) { throw new IllegalArgumentException("Index out of range"); } return consequenceList.get(index); } @Override public int getChildCount() { return consequenceList.size(); } @SuppressWarnings("nls") @Override public String getDescription() { return Lang.getMsg(TalkingLine.class, "Consequence.Docu.description"); } @Override public String getExample() { return null; } @Override public String getSyntax() { return null; } @Override @SuppressWarnings("nls") public String getTitle() { return Lang .getMsg(TalkingLine.class, "Consequence.Docu.title"); } }; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "TalkingLine"
"public TalkingLine() { condPar = new ArrayList<ConditionParser>(); consPar = new ArrayList<ConsequenceParser>(); condPar.add(new illarion.easynpc.parser.talk.conditions.State()); condPar.add(new illarion.easynpc.parser.talk.conditions.Skill()); condPar.add(new illarion.easynpc.parser.talk.conditions.Attribute()); condPar.add(new illarion.easynpc.parser.talk.conditions.MagicType()); condPar.add(new illarion.easynpc.parser.talk.conditions.Money()); condPar.add(new illarion.easynpc.parser.talk.conditions.Race()); condPar.add(new illarion.easynpc.parser.talk.conditions.Queststatus()); condPar.add(new illarion.easynpc.parser.talk.conditions.Item()); condPar.add(new illarion.easynpc.parser.talk.conditions.Language()); condPar.add(new illarion.easynpc.parser.talk.conditions.Chance()); condPar.add(new illarion.easynpc.parser.talk.conditions.Town()); condPar.add(new illarion.easynpc.parser.talk.conditions.Number()); condPar.add(new illarion.easynpc.parser.talk.conditions.Talkstate()); condPar.add(new illarion.easynpc.parser.talk.conditions.Sex()); condPar.add(new illarion.easynpc.parser.talk.conditions.Admin()); condPar.add(new illarion.easynpc.parser.talk.conditions.Trigger()); consPar.add(new illarion.easynpc.parser.talk.consequences.Inform()); consPar.add(new illarion.easynpc.parser.talk.consequences.State()); consPar.add(new illarion.easynpc.parser.talk.consequences.Skill()); consPar.add(new illarion.easynpc.parser.talk.consequences.Attribute()); consPar.add(new illarion.easynpc.parser.talk.consequences.Rune()); consPar.add(new illarion.easynpc.parser.talk.consequences.Money()); consPar.add(new illarion.easynpc.parser.talk.consequences.DeleteItem()); consPar.add(new illarion.easynpc.parser.talk.consequences.Item()); consPar.add(new illarion.easynpc.parser.talk.consequences.Queststatus()); consPar.add(new illarion.easynpc.parser.talk.consequences.Rankpoints()); consPar.add(new illarion.easynpc.parser.talk.consequences.Talkstate()); consPar.add(new illarion.easynpc.parser.talk.consequences.Trade()); consPar.add(new illarion.easynpc.parser.talk.consequences.Treasure()); consPar.add(new illarion.easynpc.parser.talk.consequences.Introduce()); consPar.add(new illarion.easynpc.parser.talk.consequences.Warp()); <MASK>consPar.add(new illarion.easynpc.parser.talk.consequences.Answer());</MASK> final List<ConditionParser> conditionsList = condPar; final List<ConsequenceParser> consequenceList = consPar; conditionDocu = new DocuEntry() { @SuppressWarnings("nls") @Override public DocuEntry getChild(final int index) { if ((index < 0) || (index >= conditionsList.size())) { throw new IllegalArgumentException("Index out of range"); } return conditionsList.get(index); } @Override public int getChildCount() { return conditionsList.size(); } @SuppressWarnings("nls") @Override public String getDescription() { return Lang.getMsg(TalkingLine.class, "Conditions.Docu.description"); } @Override public String getExample() { return null; } @Override public String getSyntax() { return null; } @Override @SuppressWarnings("nls") public String getTitle() { return Lang.getMsg(TalkingLine.class, "Conditions.Docu.title"); } }; consequenceDocu = new DocuEntry() { @SuppressWarnings("nls") @Override public DocuEntry getChild(final int index) { if ((index < 0) || (index >= consequenceList.size())) { throw new IllegalArgumentException("Index out of range"); } return consequenceList.get(index); } @Override public int getChildCount() { return consequenceList.size(); } @SuppressWarnings("nls") @Override public String getDescription() { return Lang.getMsg(TalkingLine.class, "Consequence.Docu.description"); } @Override public String getExample() { return null; } @Override public String getSyntax() { return null; } @Override @SuppressWarnings("nls") public String getTitle() { return Lang .getMsg(TalkingLine.class, "Consequence.Docu.title"); } }; }"
Inversion-Mutation
megadiff
"@Test public void queryBudget(){ try{ budget.setDescription("I'M A BUDGET!!!!!!!!"); budget.setTotal(1337); budget.commit(); id = budget.getId(); }catch(Exception e){ fail("cannot sync budget" + e); } try{ Budget queriedBudget = Budget.find(id); assertEquals(queriedBudget.getDescription(), "I'M A BUDGET!!!!!!!!"); System.out.println(queriedBudget.getDescription()); }catch(Exception e){ fail("Could not fetch the budget"+e); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "queryBudget"
"@Test public void queryBudget(){ try{ budget.setDescription("I'M A BUDGET!!!!!!!!"); budget.setTotal(1337); <MASK>id = budget.getId();</MASK> budget.commit(); }catch(Exception e){ fail("cannot sync budget" + e); } try{ Budget queriedBudget = Budget.find(id); assertEquals(queriedBudget.getDescription(), "I'M A BUDGET!!!!!!!!"); System.out.println(queriedBudget.getDescription()); }catch(Exception e){ fail("Could not fetch the budget"+e); } }"
Inversion-Mutation
megadiff
"private Object createBean(final PerRequestInfo pri, final String beanname) { CreationMarker marker = (CreationMarker) pri.beans.locateBean(beanname); boolean success = false; if (marker == null) { marker = BEAN_IN_CREATION_OBJECT; pri.beans.set(beanname, marker); } try { RSACBeanInfo rbi = (RSACBeanInfo) rbimap.get(beanname); if (rbi == null) { throw new NoSuchBeanDefinitionException(beanname, "Bean definition not found"); } // implement fetch wrappers in such a way that doesn't slow normal // creation. if (rbi.fetchwrappers != null && marker.wrapperindex < rbi.fetchwrappers.length) { Object wrappero = rbi.fetchwrappers[marker.wrapperindex]; if (marker.wrapperindex == 0) { pri.beans.set(beanname, new CreationMarker(1)); } else { ++marker.wrapperindex; } RunnableWrapper wrapper = (RunnableWrapper) (wrappero instanceof RunnableWrapper ? wrappero : getBean(pri, (String) wrappero, true)); final Object[] togo = new Object[1]; wrapper.wrapRunnable(new Runnable() { public void run() { togo[0] = createBean(pri, beanname); } }).run(); return togo[0]; } ++pri.cbeans; Object newbean; // NB - isn't this odd, and in fact generally undocumented - properties // defined for factory-method beans are set on the PRODUCT, whereas those // set on FactoryBeans are set on the FACTORY!! if (rbi.factorybean != null) { Object factorybean = getBean(pri, rbi.factorybean, false); newbean = reflectivecache.invokeMethod(factorybean, rbi.factorymethod); if (newbean == null) { throw new IllegalArgumentException( "Error: null returned from factory method " + rbi.factorymethod + " of bean " + rbi.factorybean); } // rbi.beanclass = newbean.getClass(); } else { // Locate the "dead" bean from the genuine Spring context, and clone it // as quick as we can - bytecodes might do faster but in the meantime // observe that a clone typically costs 1.6 reflective calls so in // general this method will win over a reflective solution. // NB - all Copiables simply copy dependencies manually for now, no // cost. // Copiable deadbean = (Copiable) livecontext.getBean(rbi.isfactorybean? // "&" +beanname : beanname); // All the same, the following line will cost us close to 1us - unless // it invokes manual code! newbean = reflectivecache.construct(rbi.beanclass); } if (rbi.hasDependencies()) { // guard this block since if it is a factory-method bean it may be // something // extremely undesirable (like an inner class) that we should not even // dream of reflecting over. If on the other hand the user has specified // some dependencies they doubtless know what they are doing. MethodAnalyser ma = smc.getAnalyser(newbean.getClass()); // Object clonebean = deadbean.copy(); // iterate over each LOCAL dependency of the bean with given name. for (Iterator depit = rbi.dependencies(); depit.hasNext();) { String propertyname = (String) depit.next(); try { AccessMethod setter = ma.getAccessMethod(propertyname); Object depbean = null; Object beanref = rbi.beannames(propertyname); if (beanref instanceof String) { depbean = getBean(pri, (String) beanref, false); } else if (beanref instanceof ValueHolder) { Class accezzz = setter.getAccessedType(); String value = ((ValueHolder) beanref).value; if (smc.saxleafparser.isLeafType(accezzz)) { depbean = smc.saxleafparser.parse(accezzz, value); } else { // exception def copied from the beast BeanWrapperImpl! throw new TypeMismatchException(new PropertyChangeEvent( newbean, propertyname, null, value), accezzz, null); } } else { // Really need generalised conversion of vector values here. // The code to do this is actually WITHIN the grotty // BeanWrapperImpl // itself in a protected method with 5 arguments!! // This is a sort of 50% solution. It will deal with all 1-d array // types and collections, and values of parseable types. depbean = assembleVectorProperty(pri, (StringList) beanref, setter.getDeclaredType()); } // Lose another 500ns here, until we bring on FastClass. setter.setChildObject(newbean, depbean); } catch (Exception e) { throw UniversalRuntimeException.accumulate(e, "Error setting dependency " + propertyname + " of bean " + beanname); } } } if (rbi.dependson != null) { for (int i = 0; i < rbi.dependson.length; ++i) { getBean(pri, rbi.dependson[i], false); } } // process it FIRST since it will be the factory that is expecting the // dependencies set! processNewBean(pri, beanname, newbean); // now the bean is initialised, attempt to call any init-method or // InitBean. if (rbi.initmethod != null) { reflectivecache.invokeMethod(newbean, rbi.initmethod); } if (newbean instanceof InitializingBean) { try { ((InitializingBean) newbean).afterPropertiesSet(); } catch (Exception e) { // Evil Rod! Bad Juergen! throw UniversalRuntimeException.accumulate(e); } } if (rbi.destroymethod != null) { pri.todestroy.add(beanname); } if (newbean instanceof FactoryBean) { FactoryBean factorybean = (FactoryBean) newbean; try { newbean = factorybean.getObject(); } catch (Exception e) { throw UniversalRuntimeException.accumulate(e); } } // enter the bean into the req-specific map. pri.beans.set(beanname, newbean); success = true; return newbean; } finally { if (marker == BEAN_IN_CREATION_OBJECT && !success) { pri.beans.remove(beanname); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createBean"
"private Object createBean(final PerRequestInfo pri, final String beanname) { CreationMarker marker = (CreationMarker) pri.beans.locateBean(beanname); boolean success = false; if (marker == null) { marker = BEAN_IN_CREATION_OBJECT; pri.beans.set(beanname, marker); } try { RSACBeanInfo rbi = (RSACBeanInfo) rbimap.get(beanname); if (rbi == null) { throw new NoSuchBeanDefinitionException(beanname, "Bean definition not found"); } // implement fetch wrappers in such a way that doesn't slow normal // creation. if (rbi.fetchwrappers != null && marker.wrapperindex < rbi.fetchwrappers.length) { if (marker.wrapperindex == 0) { pri.beans.set(beanname, new CreationMarker(1)); } else { ++marker.wrapperindex; } <MASK>Object wrappero = rbi.fetchwrappers[marker.wrapperindex];</MASK> RunnableWrapper wrapper = (RunnableWrapper) (wrappero instanceof RunnableWrapper ? wrappero : getBean(pri, (String) wrappero, true)); final Object[] togo = new Object[1]; wrapper.wrapRunnable(new Runnable() { public void run() { togo[0] = createBean(pri, beanname); } }).run(); return togo[0]; } ++pri.cbeans; Object newbean; // NB - isn't this odd, and in fact generally undocumented - properties // defined for factory-method beans are set on the PRODUCT, whereas those // set on FactoryBeans are set on the FACTORY!! if (rbi.factorybean != null) { Object factorybean = getBean(pri, rbi.factorybean, false); newbean = reflectivecache.invokeMethod(factorybean, rbi.factorymethod); if (newbean == null) { throw new IllegalArgumentException( "Error: null returned from factory method " + rbi.factorymethod + " of bean " + rbi.factorybean); } // rbi.beanclass = newbean.getClass(); } else { // Locate the "dead" bean from the genuine Spring context, and clone it // as quick as we can - bytecodes might do faster but in the meantime // observe that a clone typically costs 1.6 reflective calls so in // general this method will win over a reflective solution. // NB - all Copiables simply copy dependencies manually for now, no // cost. // Copiable deadbean = (Copiable) livecontext.getBean(rbi.isfactorybean? // "&" +beanname : beanname); // All the same, the following line will cost us close to 1us - unless // it invokes manual code! newbean = reflectivecache.construct(rbi.beanclass); } if (rbi.hasDependencies()) { // guard this block since if it is a factory-method bean it may be // something // extremely undesirable (like an inner class) that we should not even // dream of reflecting over. If on the other hand the user has specified // some dependencies they doubtless know what they are doing. MethodAnalyser ma = smc.getAnalyser(newbean.getClass()); // Object clonebean = deadbean.copy(); // iterate over each LOCAL dependency of the bean with given name. for (Iterator depit = rbi.dependencies(); depit.hasNext();) { String propertyname = (String) depit.next(); try { AccessMethod setter = ma.getAccessMethod(propertyname); Object depbean = null; Object beanref = rbi.beannames(propertyname); if (beanref instanceof String) { depbean = getBean(pri, (String) beanref, false); } else if (beanref instanceof ValueHolder) { Class accezzz = setter.getAccessedType(); String value = ((ValueHolder) beanref).value; if (smc.saxleafparser.isLeafType(accezzz)) { depbean = smc.saxleafparser.parse(accezzz, value); } else { // exception def copied from the beast BeanWrapperImpl! throw new TypeMismatchException(new PropertyChangeEvent( newbean, propertyname, null, value), accezzz, null); } } else { // Really need generalised conversion of vector values here. // The code to do this is actually WITHIN the grotty // BeanWrapperImpl // itself in a protected method with 5 arguments!! // This is a sort of 50% solution. It will deal with all 1-d array // types and collections, and values of parseable types. depbean = assembleVectorProperty(pri, (StringList) beanref, setter.getDeclaredType()); } // Lose another 500ns here, until we bring on FastClass. setter.setChildObject(newbean, depbean); } catch (Exception e) { throw UniversalRuntimeException.accumulate(e, "Error setting dependency " + propertyname + " of bean " + beanname); } } } if (rbi.dependson != null) { for (int i = 0; i < rbi.dependson.length; ++i) { getBean(pri, rbi.dependson[i], false); } } // process it FIRST since it will be the factory that is expecting the // dependencies set! processNewBean(pri, beanname, newbean); // now the bean is initialised, attempt to call any init-method or // InitBean. if (rbi.initmethod != null) { reflectivecache.invokeMethod(newbean, rbi.initmethod); } if (newbean instanceof InitializingBean) { try { ((InitializingBean) newbean).afterPropertiesSet(); } catch (Exception e) { // Evil Rod! Bad Juergen! throw UniversalRuntimeException.accumulate(e); } } if (rbi.destroymethod != null) { pri.todestroy.add(beanname); } if (newbean instanceof FactoryBean) { FactoryBean factorybean = (FactoryBean) newbean; try { newbean = factorybean.getObject(); } catch (Exception e) { throw UniversalRuntimeException.accumulate(e); } } // enter the bean into the req-specific map. pri.beans.set(beanname, newbean); success = true; return newbean; } finally { if (marker == BEAN_IN_CREATION_OBJECT && !success) { pri.beans.remove(beanname); } } }"
Inversion-Mutation
megadiff
"public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); this.getListView().setOnScrollListener(new EndlessScrollListener()); if(!recreated) { refreshAds(); recreated = true; // TODO: Restore position } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onViewCreated"
"public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); if(!recreated) { refreshAds(); <MASK>this.getListView().setOnScrollListener(new EndlessScrollListener());</MASK> recreated = true; // TODO: Restore position } }"
Inversion-Mutation
megadiff
"public <S extends Number> NumberValueDialog(final Component parent, final VisualProperty<S> vizProp, final S initialValue) { super(JOptionPane.getFrameForComponent(parent), vizProp.getDisplayName(), true); super.setLayout(new GridBagLayout()); final GridBagConstraints c = new GridBagConstraints(); final ContinuousRange<S> range = (ContinuousRange<S>) vizProp.getRange(); final JLabel titleLabel = new JLabel(String.format("Enter %s:", readableRange(range))); final JLabel errorLabel = new JLabel("<html><font color=\"red\" size=\"-1\">Not a valid number</font></html>"); errorLabel.setVisible(false); final JTextField field = new JTextField(6); if (initialValue != null) field.setText(initialValue.toString()); final JButton okBtn = new JButton(" OK "); final JButton cancelBtn = new JButton("Cancel"); cancelBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { value = null; dispose(); } }); final ActionListener okAction = new ActionListener() { public void actionPerformed(ActionEvent e) { value = parseNumber(field.getText(), range.getType()); if (value != null) { if (!range.inRange(range.getType().cast(value))) value = null; } if (value == null) { errorLabel.setVisible(true); pack(); } else { dispose(); } } }; okBtn.addActionListener(okAction); field.addActionListener(okAction); field.getDocument().addDocumentListener(new DocumentListener() { public void changedUpdate(DocumentEvent e) { clear(); } public void removeUpdate(DocumentEvent e) { clear(); } public void insertUpdate(DocumentEvent e) { clear(); } void clear() { errorLabel.setVisible(false); pack(); } }); c.gridx = 0; c.gridy = 0; c.gridwidth = 1; c.gridheight = 1; c.weightx = 0.0; c.weighty = 0.0; c.fill = GridBagConstraints.NONE; c.insets = new Insets(10, 10, 5, 5); super.add(titleLabel, c); c.gridx = 1; c.gridy = 0; c.anchor = GridBagConstraints.WEST; c.insets = new Insets(10, 0, 5, 10); super.add(field, c); c.gridx = 1; c.gridy = 1; c.insets = new Insets(0, 0, 10, 10); super.add(errorLabel, c); c.gridx = 0; c.gridy = 2; c.gridwidth = 2; c.gridheight = 1; c.weightx = 1.0; c.weighty = 0.0; c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(0, 10, 10, 10); final JPanel btnPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); btnPanel.add(cancelBtn); btnPanel.add(okBtn); super.add(btnPanel, c); super.pack(); super.setLocationRelativeTo(parent); super.setVisible(true); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "NumberValueDialog"
"public <S extends Number> NumberValueDialog(final Component parent, final VisualProperty<S> vizProp, final S initialValue) { super(JOptionPane.getFrameForComponent(parent), vizProp.getDisplayName(), true); super.setLayout(new GridBagLayout()); final GridBagConstraints c = new GridBagConstraints(); final ContinuousRange<S> range = (ContinuousRange<S>) vizProp.getRange(); final JLabel titleLabel = new JLabel(String.format("Enter %s:", readableRange(range))); final JLabel errorLabel = new JLabel("<html><font color=\"red\" size=\"-1\">Not a valid number</font></html>"); errorLabel.setVisible(false); final JTextField field = new JTextField(6); if (initialValue != null) field.setText(initialValue.toString()); final JButton okBtn = new JButton(" OK "); final JButton cancelBtn = new JButton("Cancel"); cancelBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { value = null; dispose(); } }); final ActionListener okAction = new ActionListener() { public void actionPerformed(ActionEvent e) { value = parseNumber(field.getText(), range.getType()); if (value != null) { if (!range.inRange(range.getType().cast(value))) value = null; } if (value == null) { errorLabel.setVisible(true); pack(); } else { dispose(); } } }; okBtn.addActionListener(okAction); field.addActionListener(okAction); field.getDocument().addDocumentListener(new DocumentListener() { public void changedUpdate(DocumentEvent e) { clear(); } public void removeUpdate(DocumentEvent e) { clear(); } public void insertUpdate(DocumentEvent e) { clear(); } void clear() { errorLabel.setVisible(false); pack(); } }); c.gridx = 0; c.gridy = 0; c.gridwidth = 1; c.gridheight = 1; c.weightx = 0.0; c.weighty = 0.0; c.fill = GridBagConstraints.NONE; c.insets = new Insets(10, 10, 5, 5); super.add(titleLabel, c); c.gridx = 1; c.gridy = 0; c.anchor = GridBagConstraints.WEST; c.insets = new Insets(10, 0, 5, 10); super.add(field, c); c.gridx = 1; c.gridy = 1; c.insets = new Insets(0, 0, 10, 10); super.add(errorLabel, c); c.gridx = 0; c.gridy = 2; c.gridwidth = 2; c.gridheight = 1; c.weightx = 1.0; c.weighty = 0.0; c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(0, 10, 10, 10); final JPanel btnPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); btnPanel.add(cancelBtn); btnPanel.add(okBtn); super.add(btnPanel, c); super.pack(); <MASK>super.setVisible(true);</MASK> super.setLocationRelativeTo(parent); }"
Inversion-Mutation
megadiff
"public void writeToFile(RandomOutputStream output) throws Exception { BintexWriter bw = new BintexWriter(output); int section_count = sections.size(); ////////// HEADERS ////////// alog(output.getFilePointer(), "write yes header"); bw.writeRaw(YES_HEADER); ///////// SECTION INDEX /////////// long savedpos_sectionIndexSize = -1; long savedpos_startOfSectionIndex = -1; long[] savedpos_sectionIndexSizeEntries = new long[section_count]; long savedpos_startOfSections = -1; int[] saved_sectionOffset = new int[section_count]; int[] savedsizes_sectionAttributes = new int[section_count]; int[] savedsizes_sectionContent = new int[section_count]; { // section index size is not known, just save position and reserve bytes savedpos_sectionIndexSize = output.getFilePointer(); bw.writeInt(-1); // for sectionIndex size } alog(output.getFilePointer(), "write sectionIndexVersion: 1"); bw.writeUint8(1); alog(output.getFilePointer(), "write section_count: " + section_count); bw.writeInt(section_count); savedpos_startOfSectionIndex = output.getFilePointer(); for (int i = 0; i < section_count; i++) { SectionContent section = sections.get(i); { // section name String name = section.getName(); byte[] name_bytes = section.getNameAsBytesWithLength(); alog(output.getFilePointer(), "write sectionName: " + name); bw.writeRaw(name_bytes); } { // sizes are not known, just save position and reserve bytes savedpos_sectionIndexSizeEntries[i] = output.getFilePointer(); bw.writeInt(-1); // for offset bw.writeInt(-1); // for attributes_size bw.writeInt(-1); // for content_size bw.writeInt(0); // for reserved } } { // now we know the size of the section index, write it into the placeholder long lastPos = output.getFilePointer(); output.seek(savedpos_sectionIndexSize); int size = (int) (lastPos - savedpos_startOfSectionIndex); alog(output.getFilePointer(), "write section index size: " + size); bw.writeInt(size); output.seek(lastPos); } //////////////// SECTION ATTRIBUTES AND CONTENT ///////////////// savedpos_startOfSections = output.getFilePointer(); for (int i = 0; i < section_count; i++) { SectionContent section = sections.get(i); String section_name = section.getName(); saved_sectionOffset[i] = (int) (output.getFilePointer() - savedpos_startOfSections); { // attributes int posBeforeAttributes = (int) output.getFilePointer(); alog(output.getFilePointer(), "write section attributes: " + section_name); ValueMap attributes = section.getAttributes(); bw.writeValueSimpleMap(attributes == null? new ValueMap(): attributes); savedsizes_sectionAttributes[i] = (int) output.getFilePointer() - posBeforeAttributes; } { // contents int posBeforeContent = (int) output.getFilePointer(); alog(output.getFilePointer(), "write section content: " + section_name); ((SectionContent.Writer) section).write(output); savedsizes_sectionContent[i] = (int) output.getFilePointer() - posBeforeContent; } } //////////// WRITE INTO PLACEHOLDERS //////////////// long lastPos = output.getFilePointer(); { // offsets and sizes in the section index for (int i = 0; i < section_count; i++) { SectionContent section = sections.get(i); String section_name = section.getName(); int offset = saved_sectionOffset[i]; int attributes_size = savedsizes_sectionAttributes[i]; int content_size = savedsizes_sectionContent[i]; output.seek(savedpos_sectionIndexSizeEntries[i]); alog(output.getFilePointer(), "write offset, attributes_size, content_size of section " + section_name + ": " + offset + ", " + attributes_size + ", " + content_size); bw.writeInt(offset); bw.writeInt(attributes_size); bw.writeInt(content_size); } } output.seek(lastPos); alog(output.getFilePointer(), "write footer"); bw.writeUint8(0); alog(output.getFilePointer(), "done"); bw.close(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "writeToFile"
"public void writeToFile(RandomOutputStream output) throws Exception { BintexWriter bw = new BintexWriter(output); int section_count = sections.size(); ////////// HEADERS ////////// alog(output.getFilePointer(), "write yes header"); bw.writeRaw(YES_HEADER); ///////// SECTION INDEX /////////// long savedpos_sectionIndexSize = -1; long savedpos_startOfSectionIndex = -1; long[] savedpos_sectionIndexSizeEntries = new long[section_count]; long savedpos_startOfSections = -1; int[] saved_sectionOffset = new int[section_count]; int[] savedsizes_sectionAttributes = new int[section_count]; int[] savedsizes_sectionContent = new int[section_count]; { // section index size is not known, just save position and reserve bytes savedpos_sectionIndexSize = output.getFilePointer(); bw.writeInt(-1); // for sectionIndex size } alog(output.getFilePointer(), "write sectionIndexVersion: 1"); bw.writeUint8(1); alog(output.getFilePointer(), "write section_count: " + section_count); bw.writeInt(section_count); savedpos_startOfSectionIndex = output.getFilePointer(); for (int i = 0; i < section_count; i++) { SectionContent section = sections.get(i); { // section name String name = section.getName(); byte[] name_bytes = section.getNameAsBytesWithLength(); alog(output.getFilePointer(), "write sectionName: " + name); bw.writeRaw(name_bytes); } { // sizes are not known, just save position and reserve bytes savedpos_sectionIndexSizeEntries[i] = output.getFilePointer(); bw.writeInt(-1); // for offset bw.writeInt(-1); // for attributes_size bw.writeInt(-1); // for content_size bw.writeInt(0); // for reserved } } { // now we know the size of the section index, write it into the placeholder long lastPos = output.getFilePointer(); output.seek(savedpos_sectionIndexSize); int size = (int) (lastPos - savedpos_startOfSectionIndex); alog(output.getFilePointer(), "write section index size: " + size); bw.writeInt(size); output.seek(lastPos); } //////////////// SECTION ATTRIBUTES AND CONTENT ///////////////// savedpos_startOfSections = output.getFilePointer(); for (int i = 0; i < section_count; i++) { SectionContent section = sections.get(i); String section_name = section.getName(); saved_sectionOffset[i] = (int) (output.getFilePointer() - savedpos_startOfSections); { // attributes int posBeforeAttributes = (int) output.getFilePointer(); alog(output.getFilePointer(), "write section attributes: " + section_name); ValueMap attributes = section.getAttributes(); bw.writeValueSimpleMap(attributes == null? new ValueMap(): attributes); savedsizes_sectionAttributes[i] = (int) output.getFilePointer() - posBeforeAttributes; } { // contents int posBeforeContent = (int) output.getFilePointer(); alog(output.getFilePointer(), "write section content: " + section_name); ((SectionContent.Writer) section).write(output); savedsizes_sectionContent[i] = (int) output.getFilePointer() - posBeforeContent; } } //////////// WRITE INTO PLACEHOLDERS //////////////// long lastPos = output.getFilePointer(); { // offsets and sizes in the section index for (int i = 0; i < section_count; i++) { SectionContent section = sections.get(i); String section_name = section.getName(); int offset = saved_sectionOffset[i]; int attributes_size = savedsizes_sectionAttributes[i]; int content_size = savedsizes_sectionContent[i]; output.seek(savedpos_sectionIndexSizeEntries[i]); alog(output.getFilePointer(), "write offset, attributes_size, content_size of section " + section_name + ": " + offset + ", " + attributes_size + ", " + content_size); bw.writeInt(offset); bw.writeInt(attributes_size); bw.writeInt(content_size); } } output.seek(lastPos); alog(output.getFilePointer(), "write footer"); bw.writeUint8(0); <MASK>bw.close();</MASK> alog(output.getFilePointer(), "done"); }"
Inversion-Mutation
megadiff
"private void updateRecent(int index) { String label = m_commands.get(index).getLabel(); insertComboBoxItem(label, 0); m_comboBoxHistory.setSelectedIndex(0); for (int i = 1; i < getComboBoxItemCount(); ++i) if (getComboBoxItem(i).equals(label)) m_comboBoxHistory.removeItemAt(i); m_firstIsTemp = false; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "updateRecent"
"private void updateRecent(int index) { String label = m_commands.get(index).getLabel(); insertComboBoxItem(label, 0); for (int i = 1; i < getComboBoxItemCount(); ++i) if (getComboBoxItem(i).equals(label)) m_comboBoxHistory.removeItemAt(i); <MASK>m_comboBoxHistory.setSelectedIndex(0);</MASK> m_firstIsTemp = false; }"
Inversion-Mutation
megadiff
"@Override protected void onResume() { super.onResume(); mWifiEnabler.resume(); mBtEnabler.resume(); mAirplaneModeEnabler.resume(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onResume"
"@Override protected void onResume() { super.onResume(); mWifiEnabler.resume(); <MASK>mAirplaneModeEnabler.resume();</MASK> mBtEnabler.resume(); }"
Inversion-Mutation
megadiff
"@Override public void run() { if (requestRequired()) { /* final SearchResult search = */GCMap.searchByGeocodes(Collections.singleton(cache.getGeocode())); } CGeoMap.markCacheAsDirty(cache.getGeocode()); CachePopup.startActivity(context, cache.getGeocode()); progress.dismiss(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"@Override public void run() { if (requestRequired()) { /* final SearchResult search = */GCMap.searchByGeocodes(Collections.singleton(cache.getGeocode())); <MASK>CGeoMap.markCacheAsDirty(cache.getGeocode());</MASK> } CachePopup.startActivity(context, cache.getGeocode()); progress.dismiss(); }"
Inversion-Mutation
megadiff
"private void createMultiFieldCombo(Composite composite, GridData gd) { toolkit.createLabel(composite, "Multiple field constraint"); final Combo combo = new Combo(composite, SWT.READ_ONLY); combo.setLayoutData(gd); combo.add("..."); combo.add("All of (And)"); combo.add("Any of (Or)"); combo.setData("All of (And)", CompositeFieldConstraint.COMPOSITE_TYPE_AND); combo.setData("Any of (Or)", CompositeFieldConstraint.COMPOSITE_TYPE_OR); combo.select(0); combo.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { if (combo.getSelectionIndex() == 0) { return; } CompositeFieldConstraint comp = new CompositeFieldConstraint(); comp.compositeJunctionType = combo.getText(); constraint.addConstraint( comp ); modeller.reloadLhs(); modeller.setDirty(true); close(); } }); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createMultiFieldCombo"
"private void createMultiFieldCombo(Composite composite, GridData gd) { toolkit.createLabel(composite, "Multiple field constraint"); final Combo combo = new Combo(composite, SWT.READ_ONLY); combo.setLayoutData(gd); combo.add("..."); combo.add("All of (And)"); combo.add("Any of (Or)"); combo.setData("All of (And)", CompositeFieldConstraint.COMPOSITE_TYPE_AND); combo.setData("Any of (Or)", CompositeFieldConstraint.COMPOSITE_TYPE_OR); combo.select(0); combo.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { if (combo.getSelectionIndex() == 0) { return; } CompositeFieldConstraint comp = new CompositeFieldConstraint(); comp.compositeJunctionType = combo.getText(); constraint.addConstraint( comp ); <MASK>modeller.setDirty(true);</MASK> modeller.reloadLhs(); close(); } }); }"
Inversion-Mutation
megadiff
"public void handleEvent(Event event) { if (combo.getSelectionIndex() == 0) { return; } CompositeFieldConstraint comp = new CompositeFieldConstraint(); comp.compositeJunctionType = combo.getText(); constraint.addConstraint( comp ); modeller.reloadLhs(); modeller.setDirty(true); close(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handleEvent"
"public void handleEvent(Event event) { if (combo.getSelectionIndex() == 0) { return; } CompositeFieldConstraint comp = new CompositeFieldConstraint(); comp.compositeJunctionType = combo.getText(); constraint.addConstraint( comp ); <MASK>modeller.setDirty(true);</MASK> modeller.reloadLhs(); close(); }"
Inversion-Mutation
megadiff
"public PlanarImage createColoredBandImage(final RasterDataNode[] rasterDataNodes, final int level, int levelCount) { Assert.notNull(rasterDataNodes, "rasterDataNodes"); Assert.state(rasterDataNodes.length == 1 || rasterDataNodes.length == 3 || rasterDataNodes.length == 4, "invalid number of bands"); PlanarImage image; PlanarImage[] bandImages = getBandImages(rasterDataNodes, level); PlanarImage[] validMaskImages = getValidMaskImages(rasterDataNodes, level); prepareImageInfos(rasterDataNodes, bandImages, validMaskImages, levelCount, ProgressMonitor.NULL); PlanarImage[] sourceImages = new PlanarImage[rasterDataNodes.length]; for (int i = 0; i < rasterDataNodes.length; i++) { final RasterDataNode raster = rasterDataNodes[i]; PlanarImage planarImage = bandImages[i]; ImageInfo imageInfo = raster.getImageInfo(); Assert.state(imageInfo != null, "imageInfo != null"); final double minSample = imageInfo.getColorPaletteDef().getMinDisplaySample(); final double maxSample = imageInfo.getColorPaletteDef().getMaxDisplaySample(); Assert.notNull(imageInfo, "imageInfo"); final IndexCoding indexCoding = (raster instanceof Band) ? ((Band) raster).getIndexCoding() : null; if (indexCoding != null) { final IntMap sampleColorIndexMap = new IntMap((int) minSample - 1, 4098); final ColorPaletteDef.Point[] points = imageInfo.getColorPaletteDef().getPoints(); for (int colorIndex = 0; colorIndex < points.length; colorIndex++) { sampleColorIndexMap.putValue((int) points[colorIndex].getSample(), colorIndex); } planarImage = JAIUtils.createIndexedImage(planarImage, sampleColorIndexMap, raster.getImageInfo().getColorPaletteDef().getNumPoints() - 1); } else { final double newMin = raster.scaleInverse(minSample); final double newMax = raster.scaleInverse(maxSample); planarImage = JAIUtils.createRescaleOp(planarImage, 255.0 / (newMax - newMin), 255.0 * newMin / (newMin - newMax)); planarImage = JAIUtils.createFormatOp(planarImage, DataBuffer.TYPE_BYTE); } sourceImages[i] = planarImage; } image = performIndexToRgbConversion(rasterDataNodes, sourceImages, validMaskImages); return image; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createColoredBandImage"
"public PlanarImage createColoredBandImage(final RasterDataNode[] rasterDataNodes, final int level, int levelCount) { Assert.notNull(rasterDataNodes, "rasterDataNodes"); Assert.state(rasterDataNodes.length == 1 || rasterDataNodes.length == 3 || rasterDataNodes.length == 4, "invalid number of bands"); PlanarImage image; PlanarImage[] bandImages = getBandImages(rasterDataNodes, level); PlanarImage[] validMaskImages = getValidMaskImages(rasterDataNodes, level); prepareImageInfos(rasterDataNodes, bandImages, validMaskImages, levelCount, ProgressMonitor.NULL); PlanarImage[] sourceImages = new PlanarImage[rasterDataNodes.length]; for (int i = 0; i < rasterDataNodes.length; i++) { final RasterDataNode raster = rasterDataNodes[i]; PlanarImage planarImage = bandImages[i]; ImageInfo imageInfo = raster.getImageInfo(); Assert.state(imageInfo != null, "imageInfo != null"); <MASK>final IndexCoding indexCoding = (raster instanceof Band) ? ((Band) raster).getIndexCoding() : null;</MASK> final double minSample = imageInfo.getColorPaletteDef().getMinDisplaySample(); final double maxSample = imageInfo.getColorPaletteDef().getMaxDisplaySample(); Assert.notNull(imageInfo, "imageInfo"); if (indexCoding != null) { final IntMap sampleColorIndexMap = new IntMap((int) minSample - 1, 4098); final ColorPaletteDef.Point[] points = imageInfo.getColorPaletteDef().getPoints(); for (int colorIndex = 0; colorIndex < points.length; colorIndex++) { sampleColorIndexMap.putValue((int) points[colorIndex].getSample(), colorIndex); } planarImage = JAIUtils.createIndexedImage(planarImage, sampleColorIndexMap, raster.getImageInfo().getColorPaletteDef().getNumPoints() - 1); } else { final double newMin = raster.scaleInverse(minSample); final double newMax = raster.scaleInverse(maxSample); planarImage = JAIUtils.createRescaleOp(planarImage, 255.0 / (newMax - newMin), 255.0 * newMin / (newMin - newMax)); planarImage = JAIUtils.createFormatOp(planarImage, DataBuffer.TYPE_BYTE); } sourceImages[i] = planarImage; } image = performIndexToRgbConversion(rasterDataNodes, sourceImages, validMaskImages); return image; }"
Inversion-Mutation
megadiff
"private void removeOldSSTablesSize(Iterable<SSTableReader> oldSSTables) { for (SSTableReader sstable : oldSSTables) { if (logger.isDebugEnabled()) logger.debug(String.format("removing %s from list of files tracked for %s.%s", sstable.descriptor, cfstore.table.name, cfstore.getColumnFamilyName())); liveSize.addAndGet(-sstable.bytesOnDisk()); sstable.markCompacted(); sstable.releaseReference(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "removeOldSSTablesSize"
"private void removeOldSSTablesSize(Iterable<SSTableReader> oldSSTables) { for (SSTableReader sstable : oldSSTables) { if (logger.isDebugEnabled()) logger.debug(String.format("removing %s from list of files tracked for %s.%s", sstable.descriptor, cfstore.table.name, cfstore.getColumnFamilyName())); sstable.markCompacted(); sstable.releaseReference(); <MASK>liveSize.addAndGet(-sstable.bytesOnDisk());</MASK> } }"
Inversion-Mutation
megadiff
"public final void createWindow() { setTitle("Fanorona"); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(600, 600); setLocationRelativeTo(null); rec = new Rectangle(); if (getParent() instanceof JViewport) { JViewport vp = (JViewport) getParent(); rec = vp.getViewRect(); } else { rec = new Rectangle(0, 0, getWidth(), getHeight()); } maxX = (int) rec.getMaxX(); maxY = (int) rec.getMaxY(); ActionListener timerListener = new ActionListener() { public void actionPerformed(ActionEvent e) { clearTime(); updateScreen(false); } }; Timer timer = new Timer(1000, timerListener); timer.start(); addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent event) { if (event.getButton() == MouseEvent.BUTTON1) { clicked = true; xClick = event.getX(); yClick = event.getY(); updateScreen(true); //processClick(event.getX(), event.getY()); } if (event.getButton() == MouseEvent.BUTTON3) { } } }); setVisible(true); graphics = this.getGraphics(); /* To clear the window initially, a pause is needed * otherwise the graphics objects are not usable */ try { Thread.sleep(1000); clearWindow(); drawGrid(); } catch (InterruptedException e1) { e1.printStackTrace(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createWindow"
"public final void createWindow() { setTitle("Fanorona"); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(600, 600); setLocationRelativeTo(null); rec = new Rectangle(); if (getParent() instanceof JViewport) { JViewport vp = (JViewport) getParent(); rec = vp.getViewRect(); } else { rec = new Rectangle(0, 0, getWidth(), getHeight()); } maxX = (int) rec.getMaxX(); maxY = (int) rec.getMaxY(); ActionListener timerListener = new ActionListener() { public void actionPerformed(ActionEvent e) { clearTime(); updateScreen(false); } }; Timer timer = new Timer(1000, timerListener); timer.start(); addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent event) { if (event.getButton() == MouseEvent.BUTTON1) { <MASK>updateScreen(true);</MASK> clicked = true; xClick = event.getX(); yClick = event.getY(); //processClick(event.getX(), event.getY()); } if (event.getButton() == MouseEvent.BUTTON3) { } } }); setVisible(true); graphics = this.getGraphics(); /* To clear the window initially, a pause is needed * otherwise the graphics objects are not usable */ try { Thread.sleep(1000); clearWindow(); drawGrid(); } catch (InterruptedException e1) { e1.printStackTrace(); } }"
Inversion-Mutation
megadiff
"@Override public void mousePressed(MouseEvent event) { if (event.getButton() == MouseEvent.BUTTON1) { clicked = true; xClick = event.getX(); yClick = event.getY(); updateScreen(true); //processClick(event.getX(), event.getY()); } if (event.getButton() == MouseEvent.BUTTON3) { } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "mousePressed"
"@Override public void mousePressed(MouseEvent event) { if (event.getButton() == MouseEvent.BUTTON1) { <MASK>updateScreen(true);</MASK> clicked = true; xClick = event.getX(); yClick = event.getY(); //processClick(event.getX(), event.getY()); } if (event.getButton() == MouseEvent.BUTTON3) { } }"
Inversion-Mutation
megadiff
"@Override public void run() { Thread.currentThread().setName("JobRunner-" + this.jobId + "-" + executionId); // If the job is cancelled, disabled, killed. No log is created in this case if (handleNonReadyStatus()) { return; } createAttachmentFile(); createLogger(); boolean errorFound = false; // Delay execution if necessary. Will return a true if something went wrong. errorFound |= delayExecution(); // For pipelining of jobs. Will watch other jobs. Will return true if // something went wrong. errorFound |= blockOnPipeLine(); // Start the node. node.setStartTime(System.currentTimeMillis()); if (!errorFound && !isKilled()) { fireEvent(Event.create(this, Type.JOB_STARTED, null, false)); try { loader.uploadExecutableNode(node, props); } catch (ExecutorManagerException e1) { logger.error("Error writing initial node properties"); } if (prepareJob()) { // Writes status to the db writeStatus(); fireEvent(Event.create(this, Type.JOB_STATUS_CHANGED), false); runJob(); } else { changeStatus(Status.FAILED); logError("Job run failed preparing the job."); } } node.setEndTime(System.currentTimeMillis()); if (isKilled()) { changeStatus(Status.KILLED); } logInfo("Finishing job " + this.jobId + " at " + node.getEndTime() + " with status " + node.getStatus()); fireEvent(Event.create(this, Type.JOB_FINISHED), false); finalizeLogFile(); finalizeAttachmentFile(); writeStatus(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"@Override public void run() { Thread.currentThread().setName("JobRunner-" + this.jobId + "-" + executionId); // If the job is cancelled, disabled, killed. No log is created in this case if (handleNonReadyStatus()) { return; } createAttachmentFile(); createLogger(); boolean errorFound = false; // Delay execution if necessary. Will return a true if something went wrong. errorFound |= delayExecution(); // For pipelining of jobs. Will watch other jobs. Will return true if // something went wrong. errorFound |= blockOnPipeLine(); // Start the node. node.setStartTime(System.currentTimeMillis()); if (!errorFound && !isKilled()) { fireEvent(Event.create(this, Type.JOB_STARTED, null, false)); try { loader.uploadExecutableNode(node, props); } catch (ExecutorManagerException e1) { logger.error("Error writing initial node properties"); } if (prepareJob()) { // Writes status to the db <MASK>writeStatus();</MASK> fireEvent(Event.create(this, Type.JOB_STATUS_CHANGED), false); runJob(); <MASK>writeStatus();</MASK> } else { changeStatus(Status.FAILED); logError("Job run failed preparing the job."); } } node.setEndTime(System.currentTimeMillis()); if (isKilled()) { changeStatus(Status.KILLED); } logInfo("Finishing job " + this.jobId + " at " + node.getEndTime() + " with status " + node.getStatus()); fireEvent(Event.create(this, Type.JOB_FINISHED), false); finalizeLogFile(); finalizeAttachmentFile(); }"
Inversion-Mutation
megadiff
"public Session(int boardWidth, int boardHeight, int growthFrequency, long thinkingTime) { snakes = new HashMap<Integer, Snake>(); score = new HashMap<Snake, Integer>(); objects = new HashMap<String, GameObjectType>(); initGameObjects(); board = createStandardBoard(boardWidth, boardHeight); this.growthFrequency = growthFrequency; this.thinkingTime = thinkingTime; turnsUntilGrowth = growthFrequency; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "Session"
"public Session(int boardWidth, int boardHeight, int growthFrequency, long thinkingTime) { <MASK>board = createStandardBoard(boardWidth, boardHeight);</MASK> snakes = new HashMap<Integer, Snake>(); score = new HashMap<Snake, Integer>(); objects = new HashMap<String, GameObjectType>(); initGameObjects(); this.growthFrequency = growthFrequency; this.thinkingTime = thinkingTime; turnsUntilGrowth = growthFrequency; }"
Inversion-Mutation
megadiff
"private static void updateSchemas(final PrintWriter writer, final PgDiffArguments arguments, final PgDatabase oldDatabase, final PgDatabase newDatabase) { final boolean setSearchPath = newDatabase.getSchemas().size() > 1 || !newDatabase.getSchemas().get(0).getName().equals("public"); for (final PgSchema newSchema : newDatabase.getSchemas()) { if (setSearchPath) { writer.println(); writer.println("SET search_path = " + PgDiffUtils.getQuotedName(newSchema.getName()) + ", pg_catalog;"); } final PgSchema oldSchema = oldDatabase.getSchema(newSchema.getName()); PgDiffTriggers.dropTriggers(writer, oldSchema, newSchema); PgDiffFunctions.dropFunctions( writer, arguments, oldSchema, newSchema); PgDiffFunctions.createFunctions( writer, arguments, oldSchema, newSchema); PgDiffViews.dropViews(writer, oldSchema, newSchema); PgDiffConstraints.dropConstraints( writer, oldSchema, newSchema, true); PgDiffConstraints.dropConstraints( writer, oldSchema, newSchema, false); PgDiffIndexes.dropIndexes(writer, oldSchema, newSchema); PgDiffTables.dropClusters(writer, oldSchema, newSchema); PgDiffTables.dropTables(writer, oldSchema, newSchema); PgDiffSequences.dropSequences(writer, oldSchema, newSchema); PgDiffSequences.createSequences(writer, oldSchema, newSchema); PgDiffSequences.alterSequences( writer, arguments, oldSchema, newSchema); PgDiffTables.createTables(writer, oldSchema, newSchema); PgDiffTables.alterTables(writer, arguments, oldSchema, newSchema); PgDiffConstraints.createConstraints( writer, oldSchema, newSchema, true); PgDiffConstraints.createConstraints( writer, oldSchema, newSchema, false); PgDiffIndexes.createIndexes(writer, oldSchema, newSchema); PgDiffTables.createClusters(writer, oldSchema, newSchema); PgDiffTriggers.createTriggers(writer, oldSchema, newSchema); PgDiffViews.createViews(writer, oldSchema, newSchema); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "updateSchemas"
"private static void updateSchemas(final PrintWriter writer, final PgDiffArguments arguments, final PgDatabase oldDatabase, final PgDatabase newDatabase) { final boolean setSearchPath = newDatabase.getSchemas().size() > 1 || !newDatabase.getSchemas().get(0).getName().equals("public"); for (final PgSchema newSchema : newDatabase.getSchemas()) { if (setSearchPath) { writer.println(); writer.println("SET search_path = " + PgDiffUtils.getQuotedName(newSchema.getName()) + ", pg_catalog;"); } final PgSchema oldSchema = oldDatabase.getSchema(newSchema.getName()); PgDiffFunctions.dropFunctions( writer, arguments, oldSchema, newSchema); <MASK>PgDiffTriggers.dropTriggers(writer, oldSchema, newSchema);</MASK> PgDiffFunctions.createFunctions( writer, arguments, oldSchema, newSchema); PgDiffViews.dropViews(writer, oldSchema, newSchema); PgDiffConstraints.dropConstraints( writer, oldSchema, newSchema, true); PgDiffConstraints.dropConstraints( writer, oldSchema, newSchema, false); PgDiffIndexes.dropIndexes(writer, oldSchema, newSchema); PgDiffTables.dropClusters(writer, oldSchema, newSchema); PgDiffTables.dropTables(writer, oldSchema, newSchema); PgDiffSequences.dropSequences(writer, oldSchema, newSchema); PgDiffSequences.createSequences(writer, oldSchema, newSchema); PgDiffSequences.alterSequences( writer, arguments, oldSchema, newSchema); PgDiffTables.createTables(writer, oldSchema, newSchema); PgDiffTables.alterTables(writer, arguments, oldSchema, newSchema); PgDiffConstraints.createConstraints( writer, oldSchema, newSchema, true); PgDiffConstraints.createConstraints( writer, oldSchema, newSchema, false); PgDiffIndexes.createIndexes(writer, oldSchema, newSchema); PgDiffTables.createClusters(writer, oldSchema, newSchema); PgDiffTriggers.createTriggers(writer, oldSchema, newSchema); PgDiffViews.createViews(writer, oldSchema, newSchema); } }"
Inversion-Mutation
megadiff
"public MapViewLocation setLocation(double latitude, double longitude) { MyLocationOverlay myOverlay = LayerUtils.getMyLocationOverlay(mapView, latitude, longitude); if(lastMyOverlay != null) { mapView.getOverlays().remove(lastMyOverlay); } lastMyOverlay = myOverlay; mapView.getOverlays().add(myOverlay); return this; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setLocation"
"public MapViewLocation setLocation(double latitude, double longitude) { MyLocationOverlay myOverlay = LayerUtils.getMyLocationOverlay(mapView, latitude, longitude); if(lastMyOverlay != null) { mapView.getOverlays().remove(lastMyOverlay); <MASK>lastMyOverlay = myOverlay;</MASK> } mapView.getOverlays().add(myOverlay); return this; }"
Inversion-Mutation
megadiff
"static void markAndCopy() { int i, ref; if (!concurrentGc) { getStackRoots(); } getStaticRoots(); for (;;) { // pop one object from the gray list synchronized (mutex) { ref = greyList; if (ref==GREY_END) { break; } greyList = Native.rdMem(ref+OFF_GREY); Native.wrMem(0, ref+OFF_GREY); // mark as not in list } // allready moved // can this happen? - yes, as we do not check it in mark // TODO: no, it's checked in push() // What happens when the actuall scanning object is // again pushed on the grey stack by the mutator? if (Native.rdMem(ref+OFF_SPACE)==toSpace) { // it happens // log("mark/copy allready in toSpace"); continue; } // there should be no null pointers on the mark stack // if (Native.rdMem(ref+OFF_PTR)==0) { // log("mark/copy OFF_PTR=0!!!"); // continue; // } // push all childs // get pointer to object int addr = Native.rdMem(ref); int flags = Native.rdMem(ref+OFF_TYPE); if (flags==IS_REFARR) { // is an array of references int size = Native.rdMem(ref+OFF_MTAB_ALEN); for (i=0; i<size; ++i) { push(Native.rdMem(addr+i)); } // However, multianewarray does probably NOT work } else if (flags==IS_OBJ){ // it's a plain object // get pointer to method table flags = Native.rdMem(ref+OFF_MTAB_ALEN); // get real flags flags = Native.rdMem(flags+Const.MTAB2GC_INFO); for (i=0; flags!=0; ++i) { if ((flags&1)!=0) { push(Native.rdMem(addr+i)); } flags >>>= 1; } } // now copy it - color it BLACK int size; int dest; synchronized(mutex) { size = Native.rdMem(ref+OFF_SIZE); dest = copyPtr; copyPtr += size; // set it BLACK Native.wrMem(toSpace, ref+OFF_SPACE); } if (size>0) { // copy it for (i=0; i<size; i++) { // Native.wrMem(Native.rdMem(addr+i), dest+i); Native.memCopy(dest, addr, i); } } // update object pointer to the new location Native.wrMem(dest, ref+OFF_PTR); // wait until everybody uses the new location for (i = 0; i < 10; i++); // turn off address translation Native.memCopy(dest, dest, -1); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "markAndCopy"
"static void markAndCopy() { int i, ref; <MASK>getStaticRoots();</MASK> if (!concurrentGc) { getStackRoots(); } for (;;) { // pop one object from the gray list synchronized (mutex) { ref = greyList; if (ref==GREY_END) { break; } greyList = Native.rdMem(ref+OFF_GREY); Native.wrMem(0, ref+OFF_GREY); // mark as not in list } // allready moved // can this happen? - yes, as we do not check it in mark // TODO: no, it's checked in push() // What happens when the actuall scanning object is // again pushed on the grey stack by the mutator? if (Native.rdMem(ref+OFF_SPACE)==toSpace) { // it happens // log("mark/copy allready in toSpace"); continue; } // there should be no null pointers on the mark stack // if (Native.rdMem(ref+OFF_PTR)==0) { // log("mark/copy OFF_PTR=0!!!"); // continue; // } // push all childs // get pointer to object int addr = Native.rdMem(ref); int flags = Native.rdMem(ref+OFF_TYPE); if (flags==IS_REFARR) { // is an array of references int size = Native.rdMem(ref+OFF_MTAB_ALEN); for (i=0; i<size; ++i) { push(Native.rdMem(addr+i)); } // However, multianewarray does probably NOT work } else if (flags==IS_OBJ){ // it's a plain object // get pointer to method table flags = Native.rdMem(ref+OFF_MTAB_ALEN); // get real flags flags = Native.rdMem(flags+Const.MTAB2GC_INFO); for (i=0; flags!=0; ++i) { if ((flags&1)!=0) { push(Native.rdMem(addr+i)); } flags >>>= 1; } } // now copy it - color it BLACK int size; int dest; synchronized(mutex) { size = Native.rdMem(ref+OFF_SIZE); dest = copyPtr; copyPtr += size; // set it BLACK Native.wrMem(toSpace, ref+OFF_SPACE); } if (size>0) { // copy it for (i=0; i<size; i++) { // Native.wrMem(Native.rdMem(addr+i), dest+i); Native.memCopy(dest, addr, i); } } // update object pointer to the new location Native.wrMem(dest, ref+OFF_PTR); // wait until everybody uses the new location for (i = 0; i < 10; i++); // turn off address translation Native.memCopy(dest, dest, -1); } }"
Inversion-Mutation
megadiff
"@Override public void onCreate() { log = Logger.getDefaultLogger(); pm = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "KlaxonService"); wakeLock.acquire(); // Listen for incoming calls to kill the alarm. mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); volume = new Volume(log, mTelephonyManager); mTelephonyManager.listen(volume, PhoneStateListener.LISTEN_CALL_STATE); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); sp.registerOnSharedPreferenceChangeListener(volume); volume.onSharedPreferenceChanged(sp, Intents.KEY_PREALARM_VOLUME); volume.onSharedPreferenceChanged(sp, Intents.KEY_ALARM_VOLUME); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCreate"
"@Override public void onCreate() { log = Logger.getDefaultLogger(); pm = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "KlaxonService"); wakeLock.acquire(); // Listen for incoming calls to kill the alarm. mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); <MASK>mTelephonyManager.listen(volume, PhoneStateListener.LISTEN_CALL_STATE);</MASK> volume = new Volume(log, mTelephonyManager); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); sp.registerOnSharedPreferenceChangeListener(volume); volume.onSharedPreferenceChanged(sp, Intents.KEY_PREALARM_VOLUME); volume.onSharedPreferenceChanged(sp, Intents.KEY_ALARM_VOLUME); }"
Inversion-Mutation
megadiff
"public void createTopBarElements() { // 1. Create view groups and controls statusBar = createStatusBar(); statusBar.setBackgroundDrawable(view.getResources().getDrawable(R.drawable.box_top)); rightStack = new MapStackControl(view.getContext()); rightStack.addStackView(createAltitudeControl()); rightStack.addStackView(createDistanceControl()); rightStack.addCollapsedView(createSpeedControl()); rightStack.addCollapsedView(createTimeControl()); leftStack = new MapStackControl(view.getContext()); leftStack.addStackView(createNextInfoControl()); leftStack.addStackView(createMiniMapControl()); // 2. Preparations Rect topRectPadding = new Rect(); view.getResources().getDrawable(R.drawable.box_top).getPadding(topRectPadding); STATUS_BAR_MARGIN_X = (int) (STATUS_BAR_MARGIN_X * scaleCoefficient); statusBar.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED); Rect statusBarPadding = new Rect(); statusBar.getBackground().getPadding(statusBarPadding); // 3. put into frame parent layout controls FrameLayout parent = (FrameLayout) view.getParent(); // status bar hides own top part int topMargin = statusBar.getMeasuredHeight() - statusBarPadding.top - statusBarPadding.bottom; // we want that status bar lays over map stack controls topMargin -= topRectPadding.top; FrameLayout.LayoutParams flp = new FrameLayout.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.RIGHT); flp.rightMargin = STATUS_BAR_MARGIN_X; flp.topMargin = topMargin; rightStack.setLayoutParams(flp); flp = new FrameLayout.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.LEFT); flp.leftMargin = STATUS_BAR_MARGIN_X; flp.topMargin = topMargin; leftStack.setLayoutParams(flp); flp = new FrameLayout.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.TOP); flp.leftMargin = STATUS_BAR_MARGIN_X; flp.rightMargin = STATUS_BAR_MARGIN_X; flp.topMargin = -topRectPadding.top; statusBar.setLayoutParams(flp); parent.addView(rightStack); parent.addView(leftStack); parent.addView(statusBar); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createTopBarElements"
"public void createTopBarElements() { // 1. Create view groups and controls statusBar = createStatusBar(); statusBar.setBackgroundDrawable(view.getResources().getDrawable(R.drawable.box_top)); rightStack = new MapStackControl(view.getContext()); <MASK>rightStack.addStackView(createDistanceControl());</MASK> rightStack.addStackView(createAltitudeControl()); rightStack.addCollapsedView(createSpeedControl()); rightStack.addCollapsedView(createTimeControl()); leftStack = new MapStackControl(view.getContext()); leftStack.addStackView(createNextInfoControl()); leftStack.addStackView(createMiniMapControl()); // 2. Preparations Rect topRectPadding = new Rect(); view.getResources().getDrawable(R.drawable.box_top).getPadding(topRectPadding); STATUS_BAR_MARGIN_X = (int) (STATUS_BAR_MARGIN_X * scaleCoefficient); statusBar.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED); Rect statusBarPadding = new Rect(); statusBar.getBackground().getPadding(statusBarPadding); // 3. put into frame parent layout controls FrameLayout parent = (FrameLayout) view.getParent(); // status bar hides own top part int topMargin = statusBar.getMeasuredHeight() - statusBarPadding.top - statusBarPadding.bottom; // we want that status bar lays over map stack controls topMargin -= topRectPadding.top; FrameLayout.LayoutParams flp = new FrameLayout.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.RIGHT); flp.rightMargin = STATUS_BAR_MARGIN_X; flp.topMargin = topMargin; rightStack.setLayoutParams(flp); flp = new FrameLayout.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.LEFT); flp.leftMargin = STATUS_BAR_MARGIN_X; flp.topMargin = topMargin; leftStack.setLayoutParams(flp); flp = new FrameLayout.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.TOP); flp.leftMargin = STATUS_BAR_MARGIN_X; flp.rightMargin = STATUS_BAR_MARGIN_X; flp.topMargin = -topRectPadding.top; statusBar.setLayoutParams(flp); parent.addView(rightStack); parent.addView(leftStack); parent.addView(statusBar); }"
Inversion-Mutation
megadiff
"private void sendMail(MailOutTransportInfo outInfo, MessageContext msgContext) throws AxisFault, MessagingException, IOException { OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext); MessageFormatter messageFormatter = BaseUtils.getMessageFormatter(msgContext); WSMimeMessage message = new WSMimeMessage(session); Map trpHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS); // set From address - first check if this is a reply, then use from address from the // transport out, else if any custom transport headers set on this message, or default // to the transport senders default From address if (outInfo.getTargetAddresses() != null && outInfo.getFromAddress() != null) { message.setFrom(outInfo.getFromAddress()); message.setReplyTo((new Address []{outInfo.getFromAddress()})); } else if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_FROM)) { message.setFrom( new InternetAddress((String) trpHeaders.get(MailConstants.MAIL_HEADER_FROM))); message.setReplyTo(InternetAddress.parse( (String) trpHeaders.get(MailConstants.MAIL_HEADER_FROM))); } else { if (smtpFromAddress != null) { message.setFrom(smtpFromAddress); message.setReplyTo(new Address[] {smtpFromAddress}); } else { handleException("From address for outgoing message cannot be determined"); } } // set To address/es to any custom transport header set on the message, else use the reply // address from the out transport information if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_TO)) { message.setRecipients(Message.RecipientType.TO, InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_TO))); } else if (outInfo.getTargetAddresses() != null) { message.setRecipients(Message.RecipientType.TO, outInfo.getTargetAddresses()); } else { handleException("To address for outgoing message cannot be determined"); } // set Cc address/es to any custom transport header set on the message, else use the // Cc list from original request message if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_CC)) { message.setRecipients(Message.RecipientType.CC, InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_CC))); } else if (outInfo.getTargetAddresses() != null) { message.setRecipients(Message.RecipientType.CC, outInfo.getCcAddresses()); } // set Bcc address/es to any custom addresses set at the transport sender level + any // custom transport header InternetAddress[] trpBccArr = null; if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_BCC)) { trpBccArr = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_BCC)); } InternetAddress[] mergedBcc = new InternetAddress[ (trpBccArr != null ? trpBccArr.length : 0) + (smtpBccAddresses != null ? smtpBccAddresses.length : 0)]; if (trpBccArr != null) { System.arraycopy(trpBccArr, 0, mergedBcc, 0, trpBccArr.length); } if (smtpBccAddresses != null) { System.arraycopy(smtpBccAddresses, 0, mergedBcc, mergedBcc.length, smtpBccAddresses.length); } if (mergedBcc != null) { message.setRecipients(Message.RecipientType.BCC, mergedBcc); } // set subject if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_SUBJECT)) { message.setSubject((String) trpHeaders.get(MailConstants.MAIL_HEADER_SUBJECT)); } else if (outInfo.getSubject() != null) { message.setSubject(outInfo.getSubject()); } else { message.setSubject(BaseConstants.SOAPACTION + ": " + msgContext.getSoapAction()); } // if a custom message id is set, use it if (msgContext.getMessageID() != null) { message.setHeader(MailConstants.MAIL_HEADER_MESSAGE_ID, msgContext.getMessageID()); message.setHeader(MailConstants.MAIL_HEADER_X_MESSAGE_ID, msgContext.getMessageID()); } // if this is a reply, set reference to original message if (outInfo.getRequestMessageID() != null) { message.setHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO, outInfo.getRequestMessageID()); message.setHeader(MailConstants.MAIL_HEADER_REFERENCES, outInfo.getRequestMessageID()); } else { if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_IN_REPLY_TO)) { message.setHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO, (String) trpHeaders.get(MailConstants.MAIL_HEADER_IN_REPLY_TO)); } if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_REFERENCES)) { message.setHeader(MailConstants.MAIL_HEADER_REFERENCES, (String) trpHeaders.get(MailConstants.MAIL_HEADER_REFERENCES)); } } // set Date message.setSentDate(new Date()); // set SOAPAction header message.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction()); // write body MessageFormatterEx messageFormatterEx; if (messageFormatter instanceof MessageFormatterEx) { messageFormatterEx = (MessageFormatterEx)messageFormatter; } else { messageFormatterEx = new MessageFormatterExAdapter(messageFormatter); } DataHandler dataHandler = new DataHandler(messageFormatterEx.getDataSource(msgContext, format, msgContext.getSoapAction())); MimeMultipart mimeMultiPart = null; String mFormat = (String) msgContext.getProperty(MailConstants.TRANSPORT_MAIL_FORMAT); if (mFormat == null) { mFormat = defaultMailFormat; } if (MailConstants.TRANSPORT_FORMAT_MP.equals(mFormat)) { mimeMultiPart = new MimeMultipart(); MimeBodyPart mimeBodyPart1 = new MimeBodyPart(); mimeBodyPart1.setContent("Web Service Message Attached","text/plain"); MimeBodyPart mimeBodyPart2 = new MimeBodyPart(); mimeBodyPart2.setDataHandler(dataHandler); mimeBodyPart2.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction()); mimeMultiPart.addBodyPart(mimeBodyPart1); mimeMultiPart.addBodyPart(mimeBodyPart2); } else { message.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction()); } try { if (mimeMultiPart == null) { message.setDataHandler(dataHandler); } else { message.setContent(mimeMultiPart); } Transport.send(message); // update metrics metrics.incrementMessagesSent(); if (mimeMultiPart != null) { for (int i=0; i<mimeMultiPart.getCount(); i++) { MimeBodyPart mbp = (MimeBodyPart) mimeMultiPart.getBodyPart(i); int size = mbp.getSize(); if (size != -1) { metrics.incrementBytesSent(size); } } } else { int size = message.getSize(); if (size != -1) { metrics.incrementBytesSent(size); } } } catch (MessagingException e) { metrics.incrementFaultsSending(); handleException("Error creating mail message or sending it to the configured server", e); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "sendMail"
"private void sendMail(MailOutTransportInfo outInfo, MessageContext msgContext) throws AxisFault, MessagingException, IOException { OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext); MessageFormatter messageFormatter = BaseUtils.getMessageFormatter(msgContext); WSMimeMessage message = new WSMimeMessage(session); Map trpHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS); // set From address - first check if this is a reply, then use from address from the // transport out, else if any custom transport headers set on this message, or default // to the transport senders default From address if (outInfo.getTargetAddresses() != null && outInfo.getFromAddress() != null) { message.setFrom(outInfo.getFromAddress()); message.setReplyTo((new Address []{outInfo.getFromAddress()})); } else if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_FROM)) { message.setFrom( new InternetAddress((String) trpHeaders.get(MailConstants.MAIL_HEADER_FROM))); message.setReplyTo(InternetAddress.parse( (String) trpHeaders.get(MailConstants.MAIL_HEADER_FROM))); } else { if (smtpFromAddress != null) { message.setFrom(smtpFromAddress); message.setReplyTo(new Address[] {smtpFromAddress}); } else { handleException("From address for outgoing message cannot be determined"); } } // set To address/es to any custom transport header set on the message, else use the reply // address from the out transport information if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_TO)) { message.setRecipients(Message.RecipientType.TO, InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_TO))); } else if (outInfo.getTargetAddresses() != null) { message.setRecipients(Message.RecipientType.TO, outInfo.getTargetAddresses()); } else { handleException("To address for outgoing message cannot be determined"); } // set Cc address/es to any custom transport header set on the message, else use the // Cc list from original request message if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_CC)) { message.setRecipients(Message.RecipientType.CC, InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_CC))); } else if (outInfo.getTargetAddresses() != null) { message.setRecipients(Message.RecipientType.CC, outInfo.getCcAddresses()); } // set Bcc address/es to any custom addresses set at the transport sender level + any // custom transport header InternetAddress[] trpBccArr = null; if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_BCC)) { trpBccArr = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_BCC)); } InternetAddress[] mergedBcc = new InternetAddress[ (trpBccArr != null ? trpBccArr.length : 0) + (smtpBccAddresses != null ? smtpBccAddresses.length : 0)]; if (trpBccArr != null) { System.arraycopy(trpBccArr, 0, mergedBcc, 0, trpBccArr.length); } if (smtpBccAddresses != null) { System.arraycopy(smtpBccAddresses, 0, mergedBcc, mergedBcc.length, smtpBccAddresses.length); } if (mergedBcc != null) { message.setRecipients(Message.RecipientType.BCC, mergedBcc); } // set subject if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_SUBJECT)) { message.setSubject((String) trpHeaders.get(MailConstants.MAIL_HEADER_SUBJECT)); } else if (outInfo.getSubject() != null) { message.setSubject(outInfo.getSubject()); } else { message.setSubject(BaseConstants.SOAPACTION + ": " + msgContext.getSoapAction()); } // if a custom message id is set, use it if (msgContext.getMessageID() != null) { message.setHeader(MailConstants.MAIL_HEADER_MESSAGE_ID, msgContext.getMessageID()); message.setHeader(MailConstants.MAIL_HEADER_X_MESSAGE_ID, msgContext.getMessageID()); } // if this is a reply, set reference to original message if (outInfo.getRequestMessageID() != null) { message.setHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO, outInfo.getRequestMessageID()); message.setHeader(MailConstants.MAIL_HEADER_REFERENCES, outInfo.getRequestMessageID()); } else { if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_IN_REPLY_TO)) { message.setHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO, (String) trpHeaders.get(MailConstants.MAIL_HEADER_IN_REPLY_TO)); } if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_REFERENCES)) { message.setHeader(MailConstants.MAIL_HEADER_REFERENCES, (String) trpHeaders.get(MailConstants.MAIL_HEADER_REFERENCES)); } } // set Date message.setSentDate(new Date()); // set SOAPAction header message.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction()); // write body MessageFormatterEx messageFormatterEx; if (messageFormatter instanceof MessageFormatterEx) { messageFormatterEx = (MessageFormatterEx)messageFormatter; } else { messageFormatterEx = new MessageFormatterExAdapter(messageFormatter); } DataHandler dataHandler = new DataHandler(messageFormatterEx.getDataSource(msgContext, format, msgContext.getSoapAction())); MimeMultipart mimeMultiPart = null; String mFormat = (String) msgContext.getProperty(MailConstants.TRANSPORT_MAIL_FORMAT); if (mFormat == null) { mFormat = defaultMailFormat; } if (MailConstants.TRANSPORT_FORMAT_MP.equals(mFormat)) { mimeMultiPart = new MimeMultipart(); MimeBodyPart mimeBodyPart1 = new MimeBodyPart(); mimeBodyPart1.setContent("Web Service Message Attached","text/plain"); MimeBodyPart mimeBodyPart2 = new MimeBodyPart(); mimeBodyPart2.setDataHandler(dataHandler); mimeBodyPart2.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction()); mimeMultiPart.addBodyPart(mimeBodyPart1); mimeMultiPart.addBodyPart(mimeBodyPart2); } else { message.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction()); } try { if (mimeMultiPart == null) { message.setDataHandler(dataHandler); } else { message.setContent(mimeMultiPart); } Transport.send(message); // update metrics metrics.incrementMessagesSent(); if (mimeMultiPart != null) { for (int i=0; i<mimeMultiPart.getCount(); i++) { MimeBodyPart mbp = (MimeBodyPart) mimeMultiPart.getBodyPart(i); int size = mbp.getSize(); if (size != -1) { metrics.incrementBytesSent(size); } } } else { int size = message.getSize(); if (size != -1) { metrics.incrementBytesSent(size); } } } catch (MessagingException e) { <MASK>handleException("Error creating mail message or sending it to the configured server", e);</MASK> metrics.incrementFaultsSending(); } }"
Inversion-Mutation
megadiff
"public void shutdownMinecraftApplet() { // Spout Start if (shutdown) { return; } SpoutClient.getInstance().disableAddons(); shutdown = true; SpoutClient.disableSandbox(); // Spout End try { this.statFileWriter.func_27175_b(); this.statFileWriter.syncStats(); if (this.mcApplet != null) { this.mcApplet.clearApplet(); } try { if (this.downloadResourcesThread != null) { this.downloadResourcesThread.closeMinecraft(); } } catch (Exception var9) { ; } System.out.println("Stopping!"); try { this.changeWorld1((World) null); } catch (Throwable var8) { ; } try { GLAllocation.deleteTexturesAndDisplayLists(); } catch (Throwable var7) { ; } this.sndManager.closeMinecraft(); Mouse.destroy(); Keyboard.destroy(); } finally { Display.destroy(); if (!this.hasCrashed) { System.exit(0); } } System.gc(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "shutdownMinecraftApplet"
"public void shutdownMinecraftApplet() { // Spout Start if (shutdown) { return; } shutdown = true; SpoutClient.disableSandbox(); <MASK>SpoutClient.getInstance().disableAddons();</MASK> // Spout End try { this.statFileWriter.func_27175_b(); this.statFileWriter.syncStats(); if (this.mcApplet != null) { this.mcApplet.clearApplet(); } try { if (this.downloadResourcesThread != null) { this.downloadResourcesThread.closeMinecraft(); } } catch (Exception var9) { ; } System.out.println("Stopping!"); try { this.changeWorld1((World) null); } catch (Throwable var8) { ; } try { GLAllocation.deleteTexturesAndDisplayLists(); } catch (Throwable var7) { ; } this.sndManager.closeMinecraft(); Mouse.destroy(); Keyboard.destroy(); } finally { Display.destroy(); if (!this.hasCrashed) { System.exit(0); } } System.gc(); }"
Inversion-Mutation
megadiff
"@EventHandler public static void handleChat(ChatEvent event) { if(!event.isCancelled()) AuthChatListener.handleChat(event); if(!event.isCancelled()) TicketChatHandler.handleChat(event); if(!event.isCancelled()) MuteChatListener.handleChat(event); if(!event.isCancelled() && event.isCommand()) for(ServerInfo server : Main.instance.getProxy().getServers().values()) if(server.getAddress().equals(event.getReceiver().getAddress())) for(ProxiedPlayer player : server.getPlayers()) if(player.getAddress().equals(event.getSender().getAddress())) ConsoleGateway.dispatchLog(server.getName(), player.getName() + ": " + ((event.getMessage().startsWith("/login ")) ? "/login ***" : event.getMessage())); if(!event.isCancelled()) SharedChatHandler.handleChat(event); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handleChat"
"@EventHandler public static void handleChat(ChatEvent event) { if(!event.isCancelled()) AuthChatListener.handleChat(event); if(!event.isCancelled()) TicketChatHandler.handleChat(event); if(!event.isCancelled()) MuteChatListener.handleChat(event); <MASK>if(!event.isCancelled()) SharedChatHandler.handleChat(event);</MASK> if(!event.isCancelled() && event.isCommand()) for(ServerInfo server : Main.instance.getProxy().getServers().values()) if(server.getAddress().equals(event.getReceiver().getAddress())) for(ProxiedPlayer player : server.getPlayers()) if(player.getAddress().equals(event.getSender().getAddress())) ConsoleGateway.dispatchLog(server.getName(), player.getName() + ": " + ((event.getMessage().startsWith("/login ")) ? "/login ***" : event.getMessage())); }"
Inversion-Mutation
megadiff
"@Override public MediaService<Call> getMediaService(final boolean reinvite) throws IllegalStateException, MediaException { if (getSIPCallState() != SIPCall.State.ANSWERED && getSIPCallState() != SIPCall.State.RINGING && getSIPCallState() != SIPCall.State.PROGRESSED) { throw new IllegalStateException("The call has not been answered or there was no progress in the call"); } mediaServiceLock.lock(); try { if (_network == null) { if (reinvite) { try { this.join(Direction.DUPLEX).get(); } catch (final Exception e) { throw new MediaException(e); } } else { throw new IllegalStateException("the call is Direct mode but reinvite is false"); } } try { if (_service == null) { Parameters params = null; if (getSipSession() != null) { if (LOG.isDebugEnabled()) { LOG.debug("Set mg id with call id :" + getSipSession().getCallId()); } params = _media.createParameters(); params.put(MediaObject.MEDIAOBJECT_ID, "MG-" + getSipSession().getCallId()); _media.setParameters(params); } _service = _context.getMediaServiceFactory().create((Call) this, _media, params); JoinDelegate.bridgeJoin(this, _service.getMediaGroup()); } } catch (final Exception e) { throw new MediaException(e); } return _service; } finally { mediaServiceLock.unlock(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getMediaService"
"@Override public MediaService<Call> getMediaService(final boolean reinvite) throws IllegalStateException, MediaException { if (getSIPCallState() != SIPCall.State.ANSWERED && getSIPCallState() != SIPCall.State.RINGING && getSIPCallState() != SIPCall.State.PROGRESSED) { throw new IllegalStateException("The call has not been answered or there was no progress in the call"); } mediaServiceLock.lock(); try { if (_network == null) { if (reinvite) { try { this.join(Direction.DUPLEX).get(); } catch (final Exception e) { throw new MediaException(e); } } else { throw new IllegalStateException("the call is Direct mode but reinvite is false"); } } try { if (_service == null) { Parameters params = null; if (getSipSession() != null) { if (LOG.isDebugEnabled()) { LOG.debug("Set mg id with call id :" + getSipSession().getCallId()); } params = _media.createParameters(); params.put(MediaObject.MEDIAOBJECT_ID, "MG-" + getSipSession().getCallId()); _media.setParameters(params); } _service = _context.getMediaServiceFactory().create((Call) this, _media, params); } <MASK>JoinDelegate.bridgeJoin(this, _service.getMediaGroup());</MASK> } catch (final Exception e) { throw new MediaException(e); } return _service; } finally { mediaServiceLock.unlock(); } }"
Inversion-Mutation
megadiff
"public boolean addUser(String name, String password) { String query = "INSERT INTO Users (name, password) VALUES ('" + name + "','" + password + "')"; if(execute(query)) { int userId = getUserId(name); for(int i = 0; i < 10; i++) { query = "INSERT INTO Progresses (userId, slotId, progress) VALUES ('" + userId + "','" + i + "','(empty)')"; execute(query); } return true; } return false; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addUser"
"public boolean addUser(String name, String password) { String query = "INSERT INTO Users (name, password) VALUES ('" + name + "','" + password + "')"; <MASK>int userId = getUserId(name);</MASK> if(execute(query)) { for(int i = 0; i < 10; i++) { query = "INSERT INTO Progresses (userId, slotId, progress) VALUES ('" + userId + "','" + i + "','(empty)')"; execute(query); } return true; } return false; }"
Inversion-Mutation
megadiff
"@Override public void run() { try { while(true) { byte[] header = new byte[4]; if ((dis.read(header)) == -1) { break; } else if (header[0] == ActionType.SYNCSTORE) { int setlen = header[1]; int md5len = header[2]; int contentlen = dis.readInt(); //一次把所有的都读出来,减少读取次数 byte[] setmd5content = readBytes(setlen + md5len + contentlen, dis); String set = new String(setmd5content, 0, setlen); String md5 = new String(setmd5content, setlen, md5len); String result = sp.storePhoto(set, md5, setmd5content, setlen + md5len, contentlen); if (result == null) dos.writeInt(-1); else { dos.writeInt(result.length()); dos.write(result.getBytes()); } dos.flush(); } else if(header[0] == ActionType.ASYNCSTORE){ int setlen = header[1]; int md5len = header[2]; int contentlen = dis.readInt(); //一次把所有的都读出来,减少读取次数 byte[] setmd5content = readBytes(setlen + md5len + contentlen, dis); String set = new String(setmd5content, 0, setlen); String md5 = new String(setmd5content, setlen, md5len); WriteTask t = new WriteTask(set, md5, setmd5content, setlen + md5len, contentlen); BlockingQueue<WriteTask> bq = sq.get(set); if (bq != null) { //存在这个键,表明该写线程已经存在,直接把任务加到任务队列里即可 bq.add(t); } else { //如果不存在这个键,则需要新开启一个写线程 BlockingQueue<WriteTask> tasks = new LinkedBlockingQueue<WriteTask>(); tasks.add(t); sq.put(set, tasks); WriteThread wt = new WriteThread(conf,set, sq); new Thread(wt).start(); } } else if(header[0] == ActionType.MPUT){ int setlen = header[1]; int n = dis.readInt(); String set = new String(readBytes(setlen, dis)); String[] md5s = new String[n]; int[] conlen = new int[n]; byte[][] content = new byte[n][]; for(int i = 0; i<n;i++) { md5s[i] = new String(readBytes(dis.readInt(), dis)); } for(int i = 0;i<n;i++) conlen[i] = dis.readInt(); for(int i = 0;i<n;i++) { content[i] = readBytes(conlen[i], dis); // System.out.println("in handler"+content[i].length); } String[] r = sp.mstorePhoto(set,md5s,content); if(r == null) dos.writeInt(-1); else { for(int i = 0;i<n;i++) { dos.writeInt(r[i].getBytes().length); dos.write(r[i].getBytes()); } } dos.flush(); } else if (header[0] == ActionType.SEARCH) { //这样能把byte当成无符号的用,拼接的元信息长度最大可以255 int infolen = header[1]&0xff; if (infolen > 0) { String info = new String(readBytes(infolen, dis)); // boolean succ = false; // 解析拼接的元信息,返回其中一个读取成功的内容 // for(String info : infos.split("#")) // { byte[] content = sp.searchPhoto(info); // FIXME: ?? 有可能刚刚写进redis的时候,还无法马上读出来,这时候会无法找到图片,返回null if (content != null) { dos.writeInt(content.length); dos.write(content); // succ = true; // break; } else { // continue; dos.writeInt(-1); } // } // if(!succ) // dos.writeInt(-1); } else { dos.writeInt(-1); } dos.flush(); } else if(header[0] == ActionType.IGET){ int infolen = header[1]&0xff; long id = dis.readLong(); if(infolen > 0) { String info = new String( readBytes(infolen, dis)); byte[] content = sp.searchPhoto(info); if (content != null) { dos.writeLong(id); dos.writeInt(content.length); dos.write(content); } else { dos.writeInt(-1); } } else { dos.writeInt(-1); } } else if (header[0] == ActionType.DELSET) { String set = new String(readBytes(header[1], dis)); BlockingQueue<WriteTask> bq = sq.get(set); if(bq != null) { // 要删除这个集合,把在这个集合上进行写的线程停掉, null作为标志 bq.add(new WriteTask(null, null, null, 0, 0)); } sp.delSet(set); dos.write(1); //返回一个字节1,代表删除成功 dos.flush(); } else if(header[0] == ActionType.SERVERINFO) { ServerInfo si = new ServerInfo(); String str = ""; try { str += si.getCpuTotalInfo() + System.getProperty("line.separator"); str += si.getMemInfo()+ System.getProperty("line.separator"); for(String s : si.getDiskInfo()) str += s+ System.getProperty("line.separator"); } catch (SigarException e) { str = "#FAIL:" + e.getMessage(); e.printStackTrace(); } dos.writeInt(str.length()); dos.write(str.getBytes()); dos.flush(); } } if(sp != null) sp.close(); } catch (IOException e) { e.printStackTrace(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"@Override public void run() { try { while(true) { byte[] header = new byte[4]; if ((dis.read(header)) == -1) { break; } else if (header[0] == ActionType.SYNCSTORE) { int setlen = header[1]; int md5len = header[2]; int contentlen = dis.readInt(); //一次把所有的都读出来,减少读取次数 byte[] setmd5content = readBytes(setlen + md5len + contentlen, dis); String set = new String(setmd5content, 0, setlen); String md5 = new String(setmd5content, setlen, md5len); String result = sp.storePhoto(set, md5, setmd5content, setlen + md5len, contentlen); if (result == null) dos.writeInt(-1); else { dos.writeInt(result.length()); dos.write(result.getBytes()); } dos.flush(); } else if(header[0] == ActionType.ASYNCSTORE){ int setlen = header[1]; int md5len = header[2]; int contentlen = dis.readInt(); //一次把所有的都读出来,减少读取次数 byte[] setmd5content = readBytes(setlen + md5len + contentlen, dis); String set = new String(setmd5content, 0, setlen); String md5 = new String(setmd5content, setlen, md5len); WriteTask t = new WriteTask(set, md5, setmd5content, setlen + md5len, contentlen); BlockingQueue<WriteTask> bq = sq.get(set); if (bq != null) { //存在这个键,表明该写线程已经存在,直接把任务加到任务队列里即可 bq.add(t); } else { //如果不存在这个键,则需要新开启一个写线程 BlockingQueue<WriteTask> tasks = new LinkedBlockingQueue<WriteTask>(); tasks.add(t); sq.put(set, tasks); WriteThread wt = new WriteThread(conf,set, sq); new Thread(wt).start(); } } else if(header[0] == ActionType.MPUT){ int setlen = header[1]; int n = dis.readInt(); String set = new String(readBytes(setlen, dis)); String[] md5s = new String[n]; int[] conlen = new int[n]; byte[][] content = new byte[n][]; for(int i = 0; i<n;i++) { md5s[i] = new String(readBytes(dis.readInt(), dis)); } for(int i = 0;i<n;i++) conlen[i] = dis.readInt(); for(int i = 0;i<n;i++) { content[i] = readBytes(conlen[i], dis); // System.out.println("in handler"+content[i].length); } String[] r = sp.mstorePhoto(set,md5s,content); if(r == null) dos.writeInt(-1); else { for(int i = 0;i<n;i++) { dos.writeInt(r[i].getBytes().length); dos.write(r[i].getBytes()); } } dos.flush(); } else if (header[0] == ActionType.SEARCH) { //这样能把byte当成无符号的用,拼接的元信息长度最大可以255 int infolen = header[1]&0xff; if (infolen > 0) { String info = new String(readBytes(infolen, dis)); // boolean succ = false; // 解析拼接的元信息,返回其中一个读取成功的内容 // for(String info : infos.split("#")) // { byte[] content = sp.searchPhoto(info); // FIXME: ?? 有可能刚刚写进redis的时候,还无法马上读出来,这时候会无法找到图片,返回null if (content != null) { <MASK>dos.writeInt(content.length);</MASK> dos.write(content); // succ = true; // break; } else { // continue; dos.writeInt(-1); } // } // if(!succ) // dos.writeInt(-1); } else { dos.writeInt(-1); } dos.flush(); } else if(header[0] == ActionType.IGET){ int infolen = header[1]&0xff; long id = dis.readLong(); if(infolen > 0) { String info = new String( readBytes(infolen, dis)); byte[] content = sp.searchPhoto(info); if (content != null) { <MASK>dos.writeInt(content.length);</MASK> dos.writeLong(id); dos.write(content); } else { dos.writeInt(-1); } } else { dos.writeInt(-1); } } else if (header[0] == ActionType.DELSET) { String set = new String(readBytes(header[1], dis)); BlockingQueue<WriteTask> bq = sq.get(set); if(bq != null) { // 要删除这个集合,把在这个集合上进行写的线程停掉, null作为标志 bq.add(new WriteTask(null, null, null, 0, 0)); } sp.delSet(set); dos.write(1); //返回一个字节1,代表删除成功 dos.flush(); } else if(header[0] == ActionType.SERVERINFO) { ServerInfo si = new ServerInfo(); String str = ""; try { str += si.getCpuTotalInfo() + System.getProperty("line.separator"); str += si.getMemInfo()+ System.getProperty("line.separator"); for(String s : si.getDiskInfo()) str += s+ System.getProperty("line.separator"); } catch (SigarException e) { str = "#FAIL:" + e.getMessage(); e.printStackTrace(); } dos.writeInt(str.length()); dos.write(str.getBytes()); dos.flush(); } } if(sp != null) sp.close(); } catch (IOException e) { e.printStackTrace(); } }"
Inversion-Mutation
megadiff
"@Override protected void notifyFinished(final JobEvent rescheduleInfo) { this.jobEvent = rescheduleInfo; this.logger.debug("Notifying job queue {} to continue processing.", this.queueName); synchronized ( this.syncLock ) { this.isWaiting = false; this.syncLock.notify(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "notifyFinished"
"@Override protected void notifyFinished(final JobEvent rescheduleInfo) { this.jobEvent = rescheduleInfo; this.logger.debug("Notifying job queue {} to continue processing.", this.queueName); <MASK>this.isWaiting = false;</MASK> synchronized ( this.syncLock ) { this.syncLock.notify(); } }"
Inversion-Mutation
megadiff
"public void cleanUp() { try { runCode(new Runnable() { public void run() { try { resumeAWT(); TestHelper.cleanUp(StepPlayer.this); for (Window window : WindowMonitor.getWindows()) { window.setVisible(false); window.dispose(); } flushAWT(); } catch (Throwable e) { setError(e); } } }); } catch (Throwable throwable) { LOG.warn("cleanup has failed", throwable); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "cleanUp"
"public void cleanUp() { try { runCode(new Runnable() { public void run() { try { resumeAWT(); for (Window window : WindowMonitor.getWindows()) { window.setVisible(false); window.dispose(); } <MASK>TestHelper.cleanUp(StepPlayer.this);</MASK> flushAWT(); } catch (Throwable e) { setError(e); } } }); } catch (Throwable throwable) { LOG.warn("cleanup has failed", throwable); } }"
Inversion-Mutation
megadiff
"public void run() { try { resumeAWT(); TestHelper.cleanUp(StepPlayer.this); for (Window window : WindowMonitor.getWindows()) { window.setVisible(false); window.dispose(); } flushAWT(); } catch (Throwable e) { setError(e); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"public void run() { try { resumeAWT(); for (Window window : WindowMonitor.getWindows()) { window.setVisible(false); window.dispose(); } <MASK>TestHelper.cleanUp(StepPlayer.this);</MASK> flushAWT(); } catch (Throwable e) { setError(e); } }"
Inversion-Mutation
megadiff
"public SlotLabels(int rows, int cols, CurrentSlot currentSlot) { super(rows + 1, cols); labelList = new ArrayList<SlotLabel>(rows * cols); this.currentSlot=currentSlot; addColumnIdentifiers(cols); addEmptySlots(rows, cols); SlotLabel firstLabel = labelList.get(0); firstLabel.setBackground(Color.YELLOW); currentSlot.set(firstLabel); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "SlotLabels"
"public SlotLabels(int rows, int cols, CurrentSlot currentSlot) { super(rows + 1, cols); labelList = new ArrayList<SlotLabel>(rows * cols); addColumnIdentifiers(cols); addEmptySlots(rows, cols); SlotLabel firstLabel = labelList.get(0); firstLabel.setBackground(Color.YELLOW); <MASK>this.currentSlot=currentSlot;</MASK> currentSlot.set(firstLabel); }"
Inversion-Mutation
megadiff
"public void opponentDisconnected() { gameInProgress = false; lobbyManager.resetOpponentConnection(); if (lobbyManager.getHostedGame() != null) { hostWaitScreen.setPotentialOpponent(null); } if (gameInProgress) { JOptionPane.showMessageDialog(gameMain, "Your opponent disconnected unexpectedly (they're probably scared of you)", "Disconnection", JOptionPane.ERROR_MESSAGE); quitNetworkGame(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "opponentDisconnected"
"public void opponentDisconnected() { gameInProgress = false; if (lobbyManager.getHostedGame() != null) { <MASK>lobbyManager.resetOpponentConnection();</MASK> hostWaitScreen.setPotentialOpponent(null); } if (gameInProgress) { JOptionPane.showMessageDialog(gameMain, "Your opponent disconnected unexpectedly (they're probably scared of you)", "Disconnection", JOptionPane.ERROR_MESSAGE); quitNetworkGame(); } }"
Inversion-Mutation
megadiff
"@EventHandler(priority = EventPriority.NORMAL) public void applyInventory(InventoryEvent event) { if (event.getMessage().equalsIgnoreCase(name)) { final BattlePlayer p = event.getPlayer(); Inventory i = p.getInventory(); clearInv(p); ItemStack WOODEN_SWORD = new ItemStack(Material.WOOD_SWORD, 1, (short) -16373); ItemStack BOW = new ItemStack(Material.BOW, 1); ItemStack IRON_PICKAXE = new ItemStack(Material.IRON_PICKAXE, 1, (short) -1400); ItemStack PUMPKIN_PIE = new ItemStack(Material.PUMPKIN_PIE, 5); ItemStack APPLE = new ItemStack(Material.GOLDEN_APPLE, 2); ItemStack BLUE_STAINED_CLAY = new ItemStack(Material.STAINED_CLAY, 48, (short) 11); ItemStack RED_STAINED_CLAY = new ItemStack(Material.STAINED_CLAY, 48, (short) 14); ItemStack LEATHER_CHESTPLATE = new ItemStack(Material.LEATHER_CHESTPLATE, 1); LEATHER_CHESTPLATE.addEnchantment(Enchantment.PROTECTION_PROJECTILE, 2); ItemStack DIAMOND_HELMET = new ItemStack(Material.DIAMOND_HELMET, 1); ItemStack TORCH = new ItemStack(Material.TORCH, 16); ItemStack ARROW = new ItemStack(Material.ARROW, 1); p.getInventory().setHelmet(DIAMOND_HELMET); BOW.addEnchantment(Enchantment.ARROW_INFINITE, 1); InvUtils.colourArmourAccordingToTeam(p, new ItemStack[]{LEATHER_CHESTPLATE}); p.getInventory().setChestplate(LEATHER_CHESTPLATE); i.setItem(0, WOODEN_SWORD); i.setItem(1, BOW); i.setItem(2, IRON_PICKAXE); i.setItem(3, PUMPKIN_PIE); i.setItem(4, APPLE); if (TDM.isRed(p.getName())) { i.setItem(5, RED_STAINED_CLAY); } if (TDM.isBlue(p.getName())) { i.setItem(5, BLUE_STAINED_CLAY); } i.setItem(6, TORCH); i.setItem(27, ARROW); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "applyInventory"
"@EventHandler(priority = EventPriority.NORMAL) public void applyInventory(InventoryEvent event) { if (event.getMessage().equalsIgnoreCase(name)) { final BattlePlayer p = event.getPlayer(); Inventory i = p.getInventory(); clearInv(p); ItemStack WOODEN_SWORD = new ItemStack(Material.WOOD_SWORD, 1, (short) -16373); ItemStack BOW = new ItemStack(Material.BOW, 1); ItemStack IRON_PICKAXE = new ItemStack(Material.IRON_PICKAXE, 1, (short) -1400); ItemStack PUMPKIN_PIE = new ItemStack(Material.PUMPKIN_PIE, 5); ItemStack APPLE = new ItemStack(Material.GOLDEN_APPLE, 2); ItemStack BLUE_STAINED_CLAY = new ItemStack(Material.STAINED_CLAY, 48, (short) 11); ItemStack RED_STAINED_CLAY = new ItemStack(Material.STAINED_CLAY, 48, (short) 14); ItemStack LEATHER_CHESTPLATE = new ItemStack(Material.LEATHER_CHESTPLATE, 1); LEATHER_CHESTPLATE.addEnchantment(Enchantment.PROTECTION_PROJECTILE, 2); ItemStack DIAMOND_HELMET = new ItemStack(Material.DIAMOND_HELMET, 1); ItemStack TORCH = new ItemStack(Material.TORCH, 16); ItemStack ARROW = new ItemStack(Material.ARROW, 1); <MASK>p.getInventory().setChestplate(LEATHER_CHESTPLATE);</MASK> p.getInventory().setHelmet(DIAMOND_HELMET); BOW.addEnchantment(Enchantment.ARROW_INFINITE, 1); InvUtils.colourArmourAccordingToTeam(p, new ItemStack[]{LEATHER_CHESTPLATE}); i.setItem(0, WOODEN_SWORD); i.setItem(1, BOW); i.setItem(2, IRON_PICKAXE); i.setItem(3, PUMPKIN_PIE); i.setItem(4, APPLE); if (TDM.isRed(p.getName())) { i.setItem(5, RED_STAINED_CLAY); } if (TDM.isBlue(p.getName())) { i.setItem(5, BLUE_STAINED_CLAY); } i.setItem(6, TORCH); i.setItem(27, ARROW); } }"
Inversion-Mutation
megadiff
"public boolean match(IFileInfo fileInfo) throws CoreException { if (provider == null) { IFilterMatcherDescriptor filterDescriptor = project.getWorkspace().getFilterMatcherDescriptor(getId()); if (filterDescriptor != null) provider = ((FilterDescriptor) filterDescriptor).createFilter(); if (provider == null) { String message = NLS.bind(Messages.filters_missingFilterType, getId()); throw new CoreException(new Status(IStatus.ERROR, ResourcesPlugin.PI_RESOURCES, Platform.PLUGIN_ERROR, message, new Error())); } provider.initialize(project, description.getFileInfoMatcherDescription().getArguments()); } if (provider != null) return provider.matches(fileInfo); return false; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "match"
"public boolean match(IFileInfo fileInfo) throws CoreException { if (provider == null) { IFilterMatcherDescriptor filterDescriptor = project.getWorkspace().getFilterMatcherDescriptor(getId()); if (filterDescriptor != null) provider = ((FilterDescriptor) filterDescriptor).createFilter(); <MASK>provider.initialize(project, description.getFileInfoMatcherDescription().getArguments());</MASK> if (provider == null) { String message = NLS.bind(Messages.filters_missingFilterType, getId()); throw new CoreException(new Status(IStatus.ERROR, ResourcesPlugin.PI_RESOURCES, Platform.PLUGIN_ERROR, message, new Error())); } } if (provider != null) return provider.matches(fileInfo); return false; }"
Inversion-Mutation
megadiff
"protected synchronized void intialize() throws Exception { if (isStarted()) { if (this.initialized == false) { if (this.directory == null) { this.directory = new File(IOHelper.getDefaultDataDirectory() + File.pathSeparator + "delayedDB"); } IOHelper.mkdirs(this.directory); lock(); this.journal = new Journal(); this.journal.setDirectory(directory); this.journal.setMaxFileLength(getJournalMaxFileLength()); this.journal.setWriteBatchSize(getJournalMaxWriteBatchSize()); this.journal.start(); this.pageFile = new PageFile(directory, "tmpDB"); this.pageFile.setEnablePageCaching(getIndexEnablePageCaching()); this.pageFile.setPageSize(getIndexPageSize()); this.pageFile.setWriteBatchSize(getIndexWriteBatchSize()); this.pageFile.setPageCacheSize(getIndexCacheSize()); this.pageFile.load(); this.pageFile.tx().execute(new Transaction.Closure<IOException>() { public void execute(Transaction tx) throws IOException { if (pageFile.getPageCount() == 0) { Page<MetaData> page = tx.allocate(); assert page.getPageId() == 0; page.set(metaData); metaData.page = page; metaData.createIndexes(tx); tx.store(metaData.page, metaDataMarshaller, true); } else { Page<MetaData> page = tx.load(0, metaDataMarshaller); metaData = page.get(); metaData.page = page; } metaData.load(tx); metaData.loadLists(tx, persistentLists); } }); this.pageFile.flush(); if (cleanupInterval > 0) { if (scheduler == null) { scheduler = new Scheduler(PListStore.class.getSimpleName()); scheduler.start(); } scheduler.executePeriodically(this, cleanupInterval); } this.initialized = true; LOG.info(this + " initialized"); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "intialize"
"protected synchronized void intialize() throws Exception { if (isStarted()) { if (this.initialized == false) { <MASK>this.initialized = true;</MASK> if (this.directory == null) { this.directory = new File(IOHelper.getDefaultDataDirectory() + File.pathSeparator + "delayedDB"); } IOHelper.mkdirs(this.directory); lock(); this.journal = new Journal(); this.journal.setDirectory(directory); this.journal.setMaxFileLength(getJournalMaxFileLength()); this.journal.setWriteBatchSize(getJournalMaxWriteBatchSize()); this.journal.start(); this.pageFile = new PageFile(directory, "tmpDB"); this.pageFile.setEnablePageCaching(getIndexEnablePageCaching()); this.pageFile.setPageSize(getIndexPageSize()); this.pageFile.setWriteBatchSize(getIndexWriteBatchSize()); this.pageFile.setPageCacheSize(getIndexCacheSize()); this.pageFile.load(); this.pageFile.tx().execute(new Transaction.Closure<IOException>() { public void execute(Transaction tx) throws IOException { if (pageFile.getPageCount() == 0) { Page<MetaData> page = tx.allocate(); assert page.getPageId() == 0; page.set(metaData); metaData.page = page; metaData.createIndexes(tx); tx.store(metaData.page, metaDataMarshaller, true); } else { Page<MetaData> page = tx.load(0, metaDataMarshaller); metaData = page.get(); metaData.page = page; } metaData.load(tx); metaData.loadLists(tx, persistentLists); } }); this.pageFile.flush(); if (cleanupInterval > 0) { if (scheduler == null) { scheduler = new Scheduler(PListStore.class.getSimpleName()); scheduler.start(); } scheduler.executePeriodically(this, cleanupInterval); } LOG.info(this + " initialized"); } } }"
Inversion-Mutation
megadiff
"public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.message_compose); mAddressAdapter = new EmailAddressAdapter(this); mAddressValidator = new EmailAddressValidator(); mToView = (MultiAutoCompleteTextView)findViewById(R.id.to); mCcView = (MultiAutoCompleteTextView)findViewById(R.id.cc); mBccView = (MultiAutoCompleteTextView)findViewById(R.id.bcc); mSubjectView = (EditText)findViewById(R.id.subject); mMessageContentView = (EditText)findViewById(R.id.message_content); mAttachments = (LinearLayout)findViewById(R.id.attachments); mQuotedTextBar = findViewById(R.id.quoted_text_bar); mQuotedTextDelete = (ImageButton)findViewById(R.id.quoted_text_delete); mQuotedText = (WebView)findViewById(R.id.quoted_text); TextWatcher watcher = new TextWatcher() { public void beforeTextChanged(CharSequence s, int start, int before, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { mDraftNeedsSaving = true; } public void afterTextChanged(android.text.Editable s) { } }; mToView.addTextChangedListener(watcher); mCcView.addTextChangedListener(watcher); mBccView.addTextChangedListener(watcher); mSubjectView.addTextChangedListener(watcher); mMessageContentView.addTextChangedListener(watcher); /* * We set this to invisible by default. Other methods will turn it back on if it's * needed. */ mQuotedTextBar.setVisibility(View.GONE); mQuotedText.setVisibility(View.GONE); mQuotedTextDelete.setOnClickListener(this); mToView.setAdapter(mAddressAdapter); mToView.setTokenizer(new Rfc822Tokenizer()); mToView.setValidator(mAddressValidator); mCcView.setAdapter(mAddressAdapter); mCcView.setTokenizer(new Rfc822Tokenizer()); mCcView.setValidator(mAddressValidator); mBccView.setAdapter(mAddressAdapter); mBccView.setTokenizer(new Rfc822Tokenizer()); mBccView.setValidator(mAddressValidator); mSubjectView.setOnFocusChangeListener(this); if (savedInstanceState != null) { /* * This data gets used in onCreate, so grab it here instead of onRestoreIntstanceState */ mSourceMessageProcessed = savedInstanceState.getBoolean(STATE_KEY_SOURCE_MESSAGE_PROCED, false); } Intent intent = getIntent(); String action = intent.getAction(); if (Intent.ACTION_VIEW.equals(action) || Intent.ACTION_SENDTO.equals(action)) { /* * Someone has clicked a mailto: link. The address is in the URI. */ mAccount = Preferences.getPreferences(this).getDefaultAccount(); if (mAccount == null) { /* * There are no accounts set up. This should not have happened. Prompt the * user to set up an account as an acceptable bailout. */ startActivity(new Intent(this, Accounts.class)); mDraftNeedsSaving = false; finish(); return; } if (intent.getData() != null) { Uri uri = intent.getData(); try { if (uri.getScheme().equalsIgnoreCase("mailto")) { Address[] addresses = Address.parse(uri.getSchemeSpecificPart()); addAddresses(mToView, addresses); } } catch (Exception e) { /* * If we can't extract any information from the URI it's okay. They can * still compose a message. */ } } } else if (Intent.ACTION_SEND.equals(action)) { /* * Someone is trying to compose an email with an attachment, probably Pictures. * The Intent should contain an EXTRA_STREAM with the data to attach. */ mAccount = Preferences.getPreferences(this).getDefaultAccount(); if (mAccount == null) { /* * There are no accounts set up. This should not have happened. Prompt the * user to set up an account as an acceptable bailout. */ startActivity(new Intent(this, Accounts.class)); mDraftNeedsSaving = false; finish(); return; } String text = intent.getStringExtra(Intent.EXTRA_TEXT); if (text != null) { mMessageContentView.setText(text); } String subject = intent.getStringExtra(Intent.EXTRA_SUBJECT); if (subject != null) { mSubjectView.setText(subject); } String type = intent.getType(); Uri stream = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM); if (stream != null && type != null) { if (MimeUtility.mimeTypeMatches(type, Email.ACCEPTABLE_ATTACHMENT_SEND_TYPES)) { addAttachment(stream); } } /* * There might be an EXTRA_SUBJECT, EXTRA_TEXT, EXTRA_EMAIL, EXTRA_BCC or EXTRA_CC */ String extraSubject = intent.getStringExtra(Intent.EXTRA_SUBJECT); String extraText = intent.getStringExtra(Intent.EXTRA_TEXT); String[] extraEmail = intent.getStringArrayExtra(Intent.EXTRA_EMAIL); String[] extraBcc = intent.getStringArrayExtra(Intent.EXTRA_BCC); String[] extraCc = intent.getStringArrayExtra(Intent.EXTRA_CC); String addressList = new String(); // Cache array size, as per Google's recommendations. int arraySize; int i; mSubjectView.setText(extraSubject); mMessageContentView.setText(extraText); if (extraEmail != null){ arraySize = extraEmail.length; if (arraySize > 1){ for (i=0; i < (arraySize-1); i++) { addressList += extraEmail[i]+", "; } addressList += extraEmail[arraySize-1]; } } mToView.setText(addressList); addressList = ""; if (extraBcc != null){ arraySize = extraBcc.length; if (arraySize > 1){ for (i=0; i < (arraySize-1); i++) { addressList += extraBcc[i]+", "; } addressList += extraBcc[arraySize-1]; } } mBccView.setText(addressList); addressList = ""; if (extraCc != null){ arraySize = extraCc.length; if (arraySize > 1){ for (i=0; i < (arraySize-1); i++) { addressList += extraCc[i]+", "; } addressList += extraCc[arraySize-1]; } } mCcView.setText(addressList); addressList = ""; } else { mAccount = (Account) intent.getSerializableExtra(EXTRA_ACCOUNT); mFolder = (String) intent.getStringExtra(EXTRA_FOLDER); mSourceMessageUid = (String) intent.getStringExtra(EXTRA_MESSAGE); } Log.d(Email.LOG_TAG, "action = " + action + ", mAccount = " + mAccount + ", mFolder = " + mFolder + ", mSourceMessageUid = " + mSourceMessageUid); if ((ACTION_REPLY.equals(action) || ACTION_REPLY_ALL.equals(action)) && mAccount != null && mFolder != null && mSourceMessageUid != null) { Log.d(Email.LOG_TAG, "Setting message ANSWERED flag to true"); // TODO: Really, we should wait until we send the message, but that would require saving the original // message info along with a Draft copy, in case it is left in Drafts for a while before being sent MessagingController.getInstance(getApplication()).setMessageFlag(mAccount, mFolder, mSourceMessageUid, Flag.ANSWERED, true); } if (ACTION_REPLY.equals(action) || ACTION_REPLY_ALL.equals(action) || ACTION_FORWARD.equals(action) || ACTION_EDIT_DRAFT.equals(action)) { /* * If we need to load the message we add ourself as a message listener here * so we can kick it off. Normally we add in onResume but we don't * want to reload the message every time the activity is resumed. * There is no harm in adding twice. */ MessagingController.getInstance(getApplication()).addListener(mListener); MessagingController.getInstance(getApplication()).loadMessageForView( mAccount, mFolder, mSourceMessageUid, null); } if (ACTION_REPLY.equals(action) || ACTION_REPLY_ALL.equals(action) || ACTION_EDIT_DRAFT.equals(action)) { //change focus to message body. mMessageContentView.requestFocus(); } if (!ACTION_EDIT_DRAFT.equals(action)) { String signature = getSignature(); if (signature!=null) { mMessageContentView.setText(signature); } addAddress(mBccView, new Address(mAccount.getAlwaysBcc(), "")); } updateTitle(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCreate"
"public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.message_compose); mAddressAdapter = new EmailAddressAdapter(this); mAddressValidator = new EmailAddressValidator(); mToView = (MultiAutoCompleteTextView)findViewById(R.id.to); mCcView = (MultiAutoCompleteTextView)findViewById(R.id.cc); mBccView = (MultiAutoCompleteTextView)findViewById(R.id.bcc); mSubjectView = (EditText)findViewById(R.id.subject); mMessageContentView = (EditText)findViewById(R.id.message_content); mAttachments = (LinearLayout)findViewById(R.id.attachments); mQuotedTextBar = findViewById(R.id.quoted_text_bar); mQuotedTextDelete = (ImageButton)findViewById(R.id.quoted_text_delete); mQuotedText = (WebView)findViewById(R.id.quoted_text); TextWatcher watcher = new TextWatcher() { public void beforeTextChanged(CharSequence s, int start, int before, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { mDraftNeedsSaving = true; } public void afterTextChanged(android.text.Editable s) { } }; mToView.addTextChangedListener(watcher); mCcView.addTextChangedListener(watcher); mBccView.addTextChangedListener(watcher); mSubjectView.addTextChangedListener(watcher); mMessageContentView.addTextChangedListener(watcher); /* * We set this to invisible by default. Other methods will turn it back on if it's * needed. */ mQuotedTextBar.setVisibility(View.GONE); mQuotedText.setVisibility(View.GONE); mQuotedTextDelete.setOnClickListener(this); mToView.setAdapter(mAddressAdapter); mToView.setTokenizer(new Rfc822Tokenizer()); mToView.setValidator(mAddressValidator); mCcView.setAdapter(mAddressAdapter); mCcView.setTokenizer(new Rfc822Tokenizer()); mCcView.setValidator(mAddressValidator); mBccView.setAdapter(mAddressAdapter); mBccView.setTokenizer(new Rfc822Tokenizer()); mBccView.setValidator(mAddressValidator); mSubjectView.setOnFocusChangeListener(this); if (savedInstanceState != null) { /* * This data gets used in onCreate, so grab it here instead of onRestoreIntstanceState */ mSourceMessageProcessed = savedInstanceState.getBoolean(STATE_KEY_SOURCE_MESSAGE_PROCED, false); } Intent intent = getIntent(); String action = intent.getAction(); if (Intent.ACTION_VIEW.equals(action) || Intent.ACTION_SENDTO.equals(action)) { /* * Someone has clicked a mailto: link. The address is in the URI. */ mAccount = Preferences.getPreferences(this).getDefaultAccount(); if (mAccount == null) { /* * There are no accounts set up. This should not have happened. Prompt the * user to set up an account as an acceptable bailout. */ startActivity(new Intent(this, Accounts.class)); mDraftNeedsSaving = false; finish(); return; } if (intent.getData() != null) { Uri uri = intent.getData(); try { if (uri.getScheme().equalsIgnoreCase("mailto")) { Address[] addresses = Address.parse(uri.getSchemeSpecificPart()); addAddresses(mToView, addresses); } } catch (Exception e) { /* * If we can't extract any information from the URI it's okay. They can * still compose a message. */ } } } else if (Intent.ACTION_SEND.equals(action)) { /* * Someone is trying to compose an email with an attachment, probably Pictures. * The Intent should contain an EXTRA_STREAM with the data to attach. */ mAccount = Preferences.getPreferences(this).getDefaultAccount(); if (mAccount == null) { /* * There are no accounts set up. This should not have happened. Prompt the * user to set up an account as an acceptable bailout. */ startActivity(new Intent(this, Accounts.class)); mDraftNeedsSaving = false; finish(); return; } String text = intent.getStringExtra(Intent.EXTRA_TEXT); if (text != null) { mMessageContentView.setText(text); } String subject = intent.getStringExtra(Intent.EXTRA_SUBJECT); if (subject != null) { mSubjectView.setText(subject); } String type = intent.getType(); Uri stream = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM); if (stream != null && type != null) { if (MimeUtility.mimeTypeMatches(type, Email.ACCEPTABLE_ATTACHMENT_SEND_TYPES)) { addAttachment(stream); } } /* * There might be an EXTRA_SUBJECT, EXTRA_TEXT, EXTRA_EMAIL, EXTRA_BCC or EXTRA_CC */ String extraSubject = intent.getStringExtra(Intent.EXTRA_SUBJECT); String extraText = intent.getStringExtra(Intent.EXTRA_TEXT); String[] extraEmail = intent.getStringArrayExtra(Intent.EXTRA_EMAIL); String[] extraBcc = intent.getStringArrayExtra(Intent.EXTRA_BCC); String[] extraCc = intent.getStringArrayExtra(Intent.EXTRA_CC); String addressList = new String(); // Cache array size, as per Google's recommendations. int arraySize; int i; mSubjectView.setText(extraSubject); mMessageContentView.setText(extraText); if (extraEmail != null){ arraySize = extraEmail.length; if (arraySize > 1){ for (i=0; i < (arraySize-1); i++) { addressList += extraEmail[i]+", "; } addressList += extraEmail[arraySize-1]; } } mToView.setText(addressList); addressList = ""; if (extraBcc != null){ arraySize = extraBcc.length; if (arraySize > 1){ for (i=0; i < (arraySize-1); i++) { addressList += extraBcc[i]+", "; } addressList += extraBcc[arraySize-1]; } } mBccView.setText(addressList); addressList = ""; if (extraCc != null){ arraySize = extraCc.length; if (arraySize > 1){ for (i=0; i < (arraySize-1); i++) { addressList += extraCc[i]+", "; } addressList += extraCc[arraySize-1]; } } mCcView.setText(addressList); addressList = ""; } else { mAccount = (Account) intent.getSerializableExtra(EXTRA_ACCOUNT); mFolder = (String) intent.getStringExtra(EXTRA_FOLDER); mSourceMessageUid = (String) intent.getStringExtra(EXTRA_MESSAGE); } Log.d(Email.LOG_TAG, "action = " + action + ", mAccount = " + mAccount + ", mFolder = " + mFolder + ", mSourceMessageUid = " + mSourceMessageUid); if ((ACTION_REPLY.equals(action) || ACTION_REPLY_ALL.equals(action)) && mAccount != null && mFolder != null && mSourceMessageUid != null) { Log.d(Email.LOG_TAG, "Setting message ANSWERED flag to true"); // TODO: Really, we should wait until we send the message, but that would require saving the original // message info along with a Draft copy, in case it is left in Drafts for a while before being sent MessagingController.getInstance(getApplication()).setMessageFlag(mAccount, mFolder, mSourceMessageUid, Flag.ANSWERED, true); } if (ACTION_REPLY.equals(action) || ACTION_REPLY_ALL.equals(action) || ACTION_FORWARD.equals(action) || ACTION_EDIT_DRAFT.equals(action)) { /* * If we need to load the message we add ourself as a message listener here * so we can kick it off. Normally we add in onResume but we don't * want to reload the message every time the activity is resumed. * There is no harm in adding twice. */ MessagingController.getInstance(getApplication()).addListener(mListener); MessagingController.getInstance(getApplication()).loadMessageForView( mAccount, mFolder, mSourceMessageUid, null); } if (ACTION_REPLY.equals(action) || ACTION_REPLY_ALL.equals(action) || ACTION_EDIT_DRAFT.equals(action)) { //change focus to message body. mMessageContentView.requestFocus(); } if (!ACTION_EDIT_DRAFT.equals(action)) { String signature = getSignature(); if (signature!=null) { mMessageContentView.setText(signature); } } <MASK>addAddress(mBccView, new Address(mAccount.getAlwaysBcc(), ""));</MASK> updateTitle(); }"
Inversion-Mutation
megadiff
"public PresentableProcessState getPresentableAcquisitionProcessState() { if (isCanceledOrRejected()) return WorkingCapitalProcessState.CANCELED; if (isPendingAcceptResponsability()) return WorkingCapitalProcessState.PENDING_ACCEPT_RESPONSIBILITY; if (isPendingAproval()) return WorkingCapitalProcessState.PENDING_APPROVAL; if (isPendingVerification()) return WorkingCapitalProcessState.PENDING_VERIFICATION; if (isPendingFundAllocation()) return WorkingCapitalProcessState.PENDING_FUND_ALLOCATION; if (isPendingAuthorization()) return WorkingCapitalProcessState.PENDING_AUTHORIZATION; if (isPendingPayment()) return WorkingCapitalProcessState.PENDING_PAYMENT; if (isPendingRefund()) return WorkingCapitalProcessState.SENT_FOR_FUND_REFUND; if (isRefunded()) return WorkingCapitalProcessState.TERMINATED; if (isTerminated()) return WorkingCapitalProcessState.SENT_FOR_TERMINATION; return WorkingCapitalProcessState.WORKING_CAPITAL_AVAILABLE; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getPresentableAcquisitionProcessState"
"public PresentableProcessState getPresentableAcquisitionProcessState() { if (isCanceledOrRejected()) return WorkingCapitalProcessState.CANCELED; if (isPendingAcceptResponsability()) return WorkingCapitalProcessState.PENDING_ACCEPT_RESPONSIBILITY; if (isPendingAproval()) return WorkingCapitalProcessState.PENDING_APPROVAL; if (isPendingVerification()) return WorkingCapitalProcessState.PENDING_VERIFICATION; if (isPendingFundAllocation()) return WorkingCapitalProcessState.PENDING_FUND_ALLOCATION; if (isPendingAuthorization()) return WorkingCapitalProcessState.PENDING_AUTHORIZATION; if (isPendingPayment()) return WorkingCapitalProcessState.PENDING_PAYMENT; <MASK>if (isTerminated()) return WorkingCapitalProcessState.SENT_FOR_TERMINATION;</MASK> if (isPendingRefund()) return WorkingCapitalProcessState.SENT_FOR_FUND_REFUND; if (isRefunded()) return WorkingCapitalProcessState.TERMINATED; return WorkingCapitalProcessState.WORKING_CAPITAL_AVAILABLE; }"
Inversion-Mutation
megadiff
"@TestTargetNew( level = TestLevel.COMPLETE, method = "setDither", args = {boolean.class} ) public void testSetDither() { assertConstantStateNotSet(); assertNull(mDrawableContainer.getCurrent()); mDrawableContainer.setConstantState(mDrawableContainerState); mDrawableContainer.setDither(false); mDrawableContainer.setDither(true); MockDrawable dr = new MockDrawable(); addAndSelectDrawable(dr); // call current drawable's setDither if dither is changed. dr.reset(); mDrawableContainer.setDither(false); assertTrue(dr.hasSetDitherCalled()); // does not call it if dither is not changed. dr.reset(); mDrawableContainer.setDither(true); assertTrue(dr.hasSetDitherCalled()); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "testSetDither"
"@TestTargetNew( level = TestLevel.COMPLETE, method = "setDither", args = {boolean.class} ) public void testSetDither() { assertConstantStateNotSet(); assertNull(mDrawableContainer.getCurrent()); mDrawableContainer.setDither(false); mDrawableContainer.setDither(true); <MASK>mDrawableContainer.setConstantState(mDrawableContainerState);</MASK> MockDrawable dr = new MockDrawable(); addAndSelectDrawable(dr); // call current drawable's setDither if dither is changed. dr.reset(); mDrawableContainer.setDither(false); assertTrue(dr.hasSetDitherCalled()); // does not call it if dither is not changed. dr.reset(); mDrawableContainer.setDither(true); assertTrue(dr.hasSetDitherCalled()); }"
Inversion-Mutation
megadiff
"public @Nonnull Org authenticate(boolean force) throws CloudException, InternalException { Cache<Org> cache = Cache.getInstance(provider, "vCloudOrgs", Org.class, CacheLevel.CLOUD_ACCOUNT, new TimePeriod<Minute>(25, TimePeriod.MINUTE)); ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new CloudException("No context was defined for this request"); } String accountNumber = ctx.getAccountNumber(); Iterable<Org> orgs = cache.get(ctx); Iterator<Org> it = ((force || orgs == null) ? null : orgs.iterator()); if( it == null || !it.hasNext() ) { String endpoint = getVersion().loginUrl; HttpClient client = getClient(true); HttpPost method = new HttpPost(endpoint); Org org = new Org(); org.version = getVersion(); method.addHeader("Accept", "application/*+xml;version=" + org.version.version + ",application/*+xml;version=" + org.version.version); if( wire.isDebugEnabled() ) { wire.debug(""); wire.debug(">>> [POST (" + (new Date()) + ")] -> " + endpoint + " >--------------------------------------------------------------------------------------"); } HttpResponse response; StatusLine status; String body = null; try { if( wire.isDebugEnabled() ) { wire.debug(method.getRequestLine().toString()); for( Header header : method.getAllHeaders() ) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } try { APITrace.trace(provider, "POST sessions"); response = client.execute(method); if( wire.isDebugEnabled() ) { wire.debug(response.getStatusLine().toString()); for( Header header : response.getAllHeaders() ) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } status = response.getStatusLine(); } catch( IOException e ) { throw new CloudException(e); } HttpEntity entity = response.getEntity(); try { body = EntityUtils.toString(entity); if( wire.isDebugEnabled() ) { wire.debug(body); wire.debug(""); } } catch( IOException e ) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } } finally { if( wire.isDebugEnabled() ) { wire.debug("<<< [POST (" + (new Date()) + ")] -> " + endpoint + " <--------------------------------------------------------------------------------------"); wire.debug(""); } } if( status.getStatusCode() == HttpServletResponse.SC_OK ) { if( matches(getAPIVersion(), "0.8", "0.8") ) { for( Header h : response.getHeaders("Set-Cookie") ) { String value = h.getValue(); if( value != null ) { value = value.trim(); if( value.startsWith("vcloud-token") ) { value = value.substring("vcloud-token=".length()); int idx = value.indexOf(";"); if( idx == -1 ) { org.token = value; } else { org.token = value.substring(0, idx); } } } } } else { org.token = response.getFirstHeader("x-vcloud-authorization").getValue(); } if( org.token == null ) { throw new CloudException(CloudErrorType.AUTHENTICATION, 200, "Token Empty", "No token was provided"); } try { ByteArrayInputStream bas = new ByteArrayInputStream(body.getBytes()); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document doc = parser.parse(bas); bas.close(); if( matches(org.version.version, "1.5", null) ) { NodeList orgNodes = doc.getElementsByTagName("Link"); String orgList = null; for( int i=0; i<orgNodes.getLength(); i++ ) { Node orgNode = orgNodes.item(i); if( orgNode.hasAttributes() ) { Node type = orgNode.getAttributes().getNamedItem("type"); if( type != null && type.getNodeValue().trim().equals(getMediaTypeForOrg()) ) { Node name = orgNode.getAttributes().getNamedItem("name"); if( name != null && name.getNodeValue().trim().equals(accountNumber) ) { Node href = orgNode.getAttributes().getNamedItem("href"); if( href != null ) { Region region = new Region(); String url = href.getNodeValue().trim(); region.setActive(true); region.setAvailable(true); if( provider.isCompat() ) { region.setProviderRegionId("/org/" + url.substring(url.lastIndexOf('/') + 1)); } else { region.setProviderRegionId(url.substring(url.lastIndexOf('/') + 1)); } region.setJurisdiction("US"); region.setName(name.getNodeValue().trim()); org.endpoint = url.substring(0, url.lastIndexOf("/api/org")); org.region = region; org.url = url; } } } if( type != null && type.getNodeValue().trim().equals(getMediaTypeForOrgList()) ) { Node href = orgNode.getAttributes().getNamedItem("href"); if( href != null ) { orgList = href.getNodeValue().trim(); } } } } if( org.endpoint == null && orgList != null ) { loadOrg(orgList, org, accountNumber); } } else { NodeList orgNodes = doc.getElementsByTagName("Org"); for( int i=0; i<orgNodes.getLength(); i++ ) { Node orgNode = orgNodes.item(i); if( orgNode.hasAttributes() ) { Node name = orgNode.getAttributes().getNamedItem("name"); Node href = orgNode.getAttributes().getNamedItem("href"); if( href != null ) { String url = href.getNodeValue().trim(); Region region = new Region(); if( !url.endsWith("/org/" + accountNumber) ) { continue; } region.setActive(true); region.setAvailable(true); if( provider.isCompat() ) { region.setProviderRegionId("/org/" + url.substring(url.lastIndexOf('/') + 1)); } else { region.setProviderRegionId(url.substring(url.lastIndexOf('/') + 1)); } region.setJurisdiction("US"); region.setName(name == null ? accountNumber : name.getNodeValue().trim()); org.endpoint = url.substring(0, url.lastIndexOf("/org/")); org.region = region; org.url = url; } } } } } catch( IOException e ) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } catch( ParserConfigurationException e ) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } catch( SAXException e ) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } } else { HttpEntity entity = response.getEntity(); if( entity != null ) { vCloudException.Data data = null; if( body != null && !body.equals("") ) { NodeList errors = parseXML(body).getElementsByTagName("Error"); if( errors.getLength() > 0 ) { data = vCloudException.parseException(status.getStatusCode(), errors.item(0)); } } if( data == null ) { logger.error("Received an error from " + provider.getCloudName() + " with no data: " + status.getStatusCode() + "/" + response.getStatusLine().getReasonPhrase()); throw new vCloudException(CloudErrorType.GENERAL, status.getStatusCode(), response.getStatusLine().getReasonPhrase(), "No further information"); } logger.error("[" + status.getStatusCode() + " : " + data.title + "] " + data.description); throw new vCloudException(data); } throw new CloudException(CloudErrorType.AUTHENTICATION, status.getStatusCode(), status.getReasonPhrase(), "Authentication failed"); } if( org.endpoint == null ) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), "No Org", "No org was identified for " + ctx.getAccountNumber()); } loadVDCs(org); cache.put(ctx, Collections.singletonList(org)); return org; } else { return it.next(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "authenticate"
"public @Nonnull Org authenticate(boolean force) throws CloudException, InternalException { Cache<Org> cache = Cache.getInstance(provider, "vCloudOrgs", Org.class, CacheLevel.CLOUD_ACCOUNT, new TimePeriod<Minute>(25, TimePeriod.MINUTE)); ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new CloudException("No context was defined for this request"); } String accountNumber = ctx.getAccountNumber(); Iterable<Org> orgs = cache.get(ctx); Iterator<Org> it = ((force || orgs == null) ? null : orgs.iterator()); if( it == null || !it.hasNext() ) { String endpoint = getVersion().loginUrl; HttpClient client = getClient(true); HttpPost method = new HttpPost(endpoint); Org org = new Org(); org.version = getVersion(); method.addHeader("Accept", "application/*+xml;version=" + org.version.version + ",application/*+xml;version=" + org.version.version); if( wire.isDebugEnabled() ) { wire.debug(""); wire.debug(">>> [POST (" + (new Date()) + ")] -> " + endpoint + " >--------------------------------------------------------------------------------------"); } HttpResponse response; StatusLine status; String body = null; try { if( wire.isDebugEnabled() ) { wire.debug(method.getRequestLine().toString()); for( Header header : method.getAllHeaders() ) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } try { APITrace.trace(provider, "POST sessions"); response = client.execute(method); if( wire.isDebugEnabled() ) { wire.debug(response.getStatusLine().toString()); for( Header header : response.getAllHeaders() ) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } status = response.getStatusLine(); } catch( IOException e ) { throw new CloudException(e); } HttpEntity entity = response.getEntity(); try { body = EntityUtils.toString(entity); if( wire.isDebugEnabled() ) { wire.debug(body); wire.debug(""); } } catch( IOException e ) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } } finally { if( wire.isDebugEnabled() ) { wire.debug("<<< [POST (" + (new Date()) + ")] -> " + endpoint + " <--------------------------------------------------------------------------------------"); wire.debug(""); } } if( status.getStatusCode() == HttpServletResponse.SC_OK ) { if( matches(getAPIVersion(), "0.8", "0.8") ) { for( Header h : response.getHeaders("Set-Cookie") ) { String value = h.getValue(); if( value != null ) { value = value.trim(); if( value.startsWith("vcloud-token") ) { value = value.substring("vcloud-token=".length()); int idx = value.indexOf(";"); if( idx == -1 ) { org.token = value; } else { org.token = value.substring(0, idx); } } } } } else { org.token = response.getFirstHeader("x-vcloud-authorization").getValue(); } if( org.token == null ) { throw new CloudException(CloudErrorType.AUTHENTICATION, 200, "Token Empty", "No token was provided"); } try { ByteArrayInputStream bas = new ByteArrayInputStream(body.getBytes()); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document doc = parser.parse(bas); bas.close(); if( matches(org.version.version, "1.5", null) ) { NodeList orgNodes = doc.getElementsByTagName("Link"); String orgList = null; for( int i=0; i<orgNodes.getLength(); i++ ) { Node orgNode = orgNodes.item(i); if( orgNode.hasAttributes() ) { Node type = orgNode.getAttributes().getNamedItem("type"); if( type != null && type.getNodeValue().trim().equals(getMediaTypeForOrg()) ) { Node name = orgNode.getAttributes().getNamedItem("name"); if( name != null && name.getNodeValue().trim().equals(accountNumber) ) { Node href = orgNode.getAttributes().getNamedItem("href"); if( href != null ) { Region region = new Region(); String url = href.getNodeValue().trim(); region.setActive(true); region.setAvailable(true); if( provider.isCompat() ) { region.setProviderRegionId("/org/" + url.substring(url.lastIndexOf('/') + 1)); } else { region.setProviderRegionId(url.substring(url.lastIndexOf('/') + 1)); } region.setJurisdiction("US"); region.setName(name.getNodeValue().trim()); org.endpoint = url.substring(0, url.lastIndexOf("/api/org")); org.region = region; org.url = url; } } } if( type != null && type.getNodeValue().trim().equals(getMediaTypeForOrgList()) ) { Node href = orgNode.getAttributes().getNamedItem("href"); if( href != null ) { orgList = href.getNodeValue().trim(); } } } } if( org.endpoint == null && orgList != null ) { loadOrg(orgList, org, accountNumber); } } else { NodeList orgNodes = doc.getElementsByTagName("Org"); for( int i=0; i<orgNodes.getLength(); i++ ) { Node orgNode = orgNodes.item(i); if( orgNode.hasAttributes() ) { Node name = orgNode.getAttributes().getNamedItem("name"); Node href = orgNode.getAttributes().getNamedItem("href"); if( href != null ) { String url = href.getNodeValue().trim(); Region region = new Region(); if( !url.endsWith("/org/" + accountNumber) ) { continue; } region.setActive(true); region.setAvailable(true); if( provider.isCompat() ) { region.setProviderRegionId("/org/" + url.substring(url.lastIndexOf('/') + 1)); } else { region.setProviderRegionId(url.substring(url.lastIndexOf('/') + 1)); } region.setJurisdiction("US"); region.setName(name == null ? accountNumber : name.getNodeValue().trim()); org.endpoint = url.substring(0, url.lastIndexOf("/org/")); org.region = region; org.url = url; } } } } } catch( IOException e ) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } catch( ParserConfigurationException e ) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } catch( SAXException e ) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } } else { HttpEntity entity = response.getEntity(); if( entity != null ) { vCloudException.Data data = null; if( body != null && !body.equals("") ) { NodeList errors = parseXML(body).getElementsByTagName("Error"); if( errors.getLength() > 0 ) { data = vCloudException.parseException(status.getStatusCode(), errors.item(0)); } } if( data == null ) { logger.error("Received an error from " + provider.getCloudName() + " with no data: " + status.getStatusCode() + "/" + response.getStatusLine().getReasonPhrase()); throw new vCloudException(CloudErrorType.GENERAL, status.getStatusCode(), response.getStatusLine().getReasonPhrase(), "No further information"); } logger.error("[" + status.getStatusCode() + " : " + data.title + "] " + data.description); throw new vCloudException(data); } throw new CloudException(CloudErrorType.AUTHENTICATION, status.getStatusCode(), status.getReasonPhrase(), "Authentication failed"); } if( org.endpoint == null ) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), "No Org", "No org was identified for " + ctx.getAccountNumber()); } <MASK>cache.put(ctx, Collections.singletonList(org));</MASK> loadVDCs(org); return org; } else { return it.next(); } }"
Inversion-Mutation
megadiff
"public static Object tryToMakeCompatible( final boolean isPrimitive, final boolean isArray, final Class<?> paramType, final Class<?> paramTypeComponentType, final Object param) throws Exception { if (param == null || param == VoltType.NULL_STRING_OR_VARBINARY || param == VoltType.NULL_DECIMAL) { if (isPrimitive) { VoltType type = VoltType.typeFromClass(paramType); switch (type) { case TINYINT: case SMALLINT: case INTEGER: case BIGINT: case FLOAT: return type.getNullValue(); } } // Pass null reference to the procedure run() method. These null values will be // converted to a serialize-able NULL representation for the EE in getCleanParams() // when the parameters are serialized for the plan fragment. return null; } if (param instanceof ExecutionSite.SystemProcedureExecutionContext) { return param; } Class<?> pclass = param.getClass(); // hack to make strings work with input as byte[] if ((paramType == String.class) && (pclass == byte[].class)) { String sparam = null; sparam = new String((byte[]) param, "UTF-8"); return sparam; } // hack to make varbinary work with input as string if ((paramType == byte[].class) && (pclass == String.class)) { return Encoder.hexDecode((String) param); } if (isArray != pclass.isArray()) { throw new Exception("Array / Scalar parameter mismatch"); } if (isArray) { Class<?> pSubCls = pclass.getComponentType(); Class<?> sSubCls = paramTypeComponentType; if (pSubCls == sSubCls) { return param; } // if it's an empty array, let it through // this is a bit ugly as it might hide passing // arrays of the wrong type, but it "does the right thing" // more often that not I guess... else if (Array.getLength(param) == 0) { return Array.newInstance(sSubCls, 0); } else { /* * Arrays can be quite large so it doesn't make sense to silently do the conversion * and incur the performance hit. The client should serialize the correct invocation * parameters */ throw new Exception( "tryScalarMakeCompatible: Unable to match parameter array:" + sSubCls.getName() + " to provided " + pSubCls.getName()); } } /* * inline tryScalarMakeCompatible so we can save on reflection */ final Class<?> slot = paramType; if ((slot == long.class) && (pclass == Long.class || pclass == Integer.class || pclass == Short.class || pclass == Byte.class)) return param; if ((slot == int.class) && (pclass == Integer.class || pclass == Short.class || pclass == Byte.class)) return param; if ((slot == short.class) && (pclass == Short.class || pclass == Byte.class)) return param; if ((slot == byte.class) && (pclass == Byte.class)) return param; if ((slot == double.class) && (param instanceof Number)) return ((Number)param).doubleValue(); if ((slot == String.class) && (pclass == String.class)) return param; if (slot == TimestampType.class) { if (pclass == Long.class) return new TimestampType((Long)param); if (pclass == TimestampType.class) return param; if (pclass == Date.class) return new TimestampType((Date) param); // if a string is given for a date, use java's JDBC parsing if (pclass == String.class) { try { return new TimestampType((String)param); } catch (IllegalArgumentException e) { // ignore errors if it's not the right format } } } if (slot == BigDecimal.class) { if ((pclass == Long.class) || (pclass == Integer.class) || (pclass == Short.class) || (pclass == Byte.class)) { BigInteger bi = new BigInteger(param.toString()); BigDecimal bd = new BigDecimal(bi); bd.setScale(4, BigDecimal.ROUND_HALF_EVEN); return bd; } if (pclass == BigDecimal.class) { BigDecimal bd = (BigDecimal) param; bd.setScale(4, BigDecimal.ROUND_HALF_EVEN); return bd; } if (pclass == String.class) { BigDecimal bd = VoltDecimalHelper.deserializeBigDecimalFromString((String) param); return bd; } } if (slot == VoltTable.class && pclass == VoltTable.class) { return param; } // handle truncation for integers // Long targeting int parameter if ((slot == int.class) && (pclass == Long.class)) { long val = ((Number) param).longValue(); // if it's in the right range, and not null (target null), crop the value and return if ((val <= Integer.MAX_VALUE) && (val >= Integer.MIN_VALUE) && (val != VoltType.NULL_INTEGER)) return ((Number) param).intValue(); } // Long or Integer targeting short parameter if ((slot == short.class) && (pclass == Long.class || pclass == Integer.class)) { long val = ((Number) param).longValue(); // if it's in the right range, and not null (target null), crop the value and return if ((val <= Short.MAX_VALUE) && (val >= Short.MIN_VALUE) && (val != VoltType.NULL_SMALLINT)) return ((Number) param).shortValue(); } // Long, Integer or Short targeting byte parameter if ((slot == byte.class) && (pclass == Long.class || pclass == Integer.class || pclass == Short.class)) { long val = ((Number) param).longValue(); // if it's in the right range, and not null (target null), crop the value and return if ((val <= Byte.MAX_VALUE) && (val >= Byte.MIN_VALUE) && (val != VoltType.NULL_TINYINT)) return ((Number) param).byteValue(); } // Coerce strings to primitive numbers. if (pclass == String.class) { try { if (slot == byte.class) { return Byte.parseByte((String) param); } if (slot == short.class) { return Short.parseShort((String) param); } if (slot == int.class) { return Integer.parseInt((String) param); } if (slot == long.class) { return Long.parseLong((String) param); } } catch (NumberFormatException nfe) { throw new Exception( "tryToMakeCompatible: Unable to convert string " + (String)param + " to " + slot.getName() + " value for target parameter " + slot.getName()); } } throw new Exception( "tryToMakeCompatible: Unable to match parameters or out of range for taget param: " + slot.getName() + " to provided " + pclass.getName()); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "tryToMakeCompatible"
"public static Object tryToMakeCompatible( final boolean isPrimitive, final boolean isArray, final Class<?> paramType, final Class<?> paramTypeComponentType, final Object param) throws Exception { if (param == null || param == VoltType.NULL_STRING_OR_VARBINARY || param == VoltType.NULL_DECIMAL) { <MASK>VoltType type = VoltType.typeFromClass(paramType);</MASK> if (isPrimitive) { switch (type) { case TINYINT: case SMALLINT: case INTEGER: case BIGINT: case FLOAT: return type.getNullValue(); } } // Pass null reference to the procedure run() method. These null values will be // converted to a serialize-able NULL representation for the EE in getCleanParams() // when the parameters are serialized for the plan fragment. return null; } if (param instanceof ExecutionSite.SystemProcedureExecutionContext) { return param; } Class<?> pclass = param.getClass(); // hack to make strings work with input as byte[] if ((paramType == String.class) && (pclass == byte[].class)) { String sparam = null; sparam = new String((byte[]) param, "UTF-8"); return sparam; } // hack to make varbinary work with input as string if ((paramType == byte[].class) && (pclass == String.class)) { return Encoder.hexDecode((String) param); } if (isArray != pclass.isArray()) { throw new Exception("Array / Scalar parameter mismatch"); } if (isArray) { Class<?> pSubCls = pclass.getComponentType(); Class<?> sSubCls = paramTypeComponentType; if (pSubCls == sSubCls) { return param; } // if it's an empty array, let it through // this is a bit ugly as it might hide passing // arrays of the wrong type, but it "does the right thing" // more often that not I guess... else if (Array.getLength(param) == 0) { return Array.newInstance(sSubCls, 0); } else { /* * Arrays can be quite large so it doesn't make sense to silently do the conversion * and incur the performance hit. The client should serialize the correct invocation * parameters */ throw new Exception( "tryScalarMakeCompatible: Unable to match parameter array:" + sSubCls.getName() + " to provided " + pSubCls.getName()); } } /* * inline tryScalarMakeCompatible so we can save on reflection */ final Class<?> slot = paramType; if ((slot == long.class) && (pclass == Long.class || pclass == Integer.class || pclass == Short.class || pclass == Byte.class)) return param; if ((slot == int.class) && (pclass == Integer.class || pclass == Short.class || pclass == Byte.class)) return param; if ((slot == short.class) && (pclass == Short.class || pclass == Byte.class)) return param; if ((slot == byte.class) && (pclass == Byte.class)) return param; if ((slot == double.class) && (param instanceof Number)) return ((Number)param).doubleValue(); if ((slot == String.class) && (pclass == String.class)) return param; if (slot == TimestampType.class) { if (pclass == Long.class) return new TimestampType((Long)param); if (pclass == TimestampType.class) return param; if (pclass == Date.class) return new TimestampType((Date) param); // if a string is given for a date, use java's JDBC parsing if (pclass == String.class) { try { return new TimestampType((String)param); } catch (IllegalArgumentException e) { // ignore errors if it's not the right format } } } if (slot == BigDecimal.class) { if ((pclass == Long.class) || (pclass == Integer.class) || (pclass == Short.class) || (pclass == Byte.class)) { BigInteger bi = new BigInteger(param.toString()); BigDecimal bd = new BigDecimal(bi); bd.setScale(4, BigDecimal.ROUND_HALF_EVEN); return bd; } if (pclass == BigDecimal.class) { BigDecimal bd = (BigDecimal) param; bd.setScale(4, BigDecimal.ROUND_HALF_EVEN); return bd; } if (pclass == String.class) { BigDecimal bd = VoltDecimalHelper.deserializeBigDecimalFromString((String) param); return bd; } } if (slot == VoltTable.class && pclass == VoltTable.class) { return param; } // handle truncation for integers // Long targeting int parameter if ((slot == int.class) && (pclass == Long.class)) { long val = ((Number) param).longValue(); // if it's in the right range, and not null (target null), crop the value and return if ((val <= Integer.MAX_VALUE) && (val >= Integer.MIN_VALUE) && (val != VoltType.NULL_INTEGER)) return ((Number) param).intValue(); } // Long or Integer targeting short parameter if ((slot == short.class) && (pclass == Long.class || pclass == Integer.class)) { long val = ((Number) param).longValue(); // if it's in the right range, and not null (target null), crop the value and return if ((val <= Short.MAX_VALUE) && (val >= Short.MIN_VALUE) && (val != VoltType.NULL_SMALLINT)) return ((Number) param).shortValue(); } // Long, Integer or Short targeting byte parameter if ((slot == byte.class) && (pclass == Long.class || pclass == Integer.class || pclass == Short.class)) { long val = ((Number) param).longValue(); // if it's in the right range, and not null (target null), crop the value and return if ((val <= Byte.MAX_VALUE) && (val >= Byte.MIN_VALUE) && (val != VoltType.NULL_TINYINT)) return ((Number) param).byteValue(); } // Coerce strings to primitive numbers. if (pclass == String.class) { try { if (slot == byte.class) { return Byte.parseByte((String) param); } if (slot == short.class) { return Short.parseShort((String) param); } if (slot == int.class) { return Integer.parseInt((String) param); } if (slot == long.class) { return Long.parseLong((String) param); } } catch (NumberFormatException nfe) { throw new Exception( "tryToMakeCompatible: Unable to convert string " + (String)param + " to " + slot.getName() + " value for target parameter " + slot.getName()); } } throw new Exception( "tryToMakeCompatible: Unable to match parameters or out of range for taget param: " + slot.getName() + " to provided " + pclass.getName()); }"
Inversion-Mutation
megadiff
"@Override public boolean onOptionsItemSelected(MenuItem item) { boolean handled = false ; switch ( item.getItemId() ) { case MENU_TOGGLE: if( this.mLoggerServiceManager.isLogging() ) { this.mLoggerServiceManager.stopGPSLoggerService(); item.setTitle( R.string.menu_toggle_on ); } else { this.mTrackId = this.mLoggerServiceManager.startGPSLoggerService(null); attempToMoveToTrack( this.mTrackId ); item.setTitle( R.string.menu_toggle_off ); LayoutInflater factory = LayoutInflater.from( this ); View view = factory.inflate( R.layout.namedialog, null ); mTrackNameView = (EditText) view.findViewById( R.id.nameField ); createTrackTitleDialog( this, view, mTrackNameDialogListener ).show(); } updateBlankingBehavior(); handled = true; break; case MENU_SETTINGS: Intent i = new Intent( this, SettingsDialog.class ); startActivity( i ); handled = true; break; case MENU_TRACKLIST: Intent tracklistIntent = new Intent(this, TrackList.class); tracklistIntent.putExtra( Tracks._ID, this.mTrackId ); startActivityForResult(tracklistIntent, MENU_TRACKLIST); break; case MENU_ACTION: if( this.mTrackId >= 0 ) { LayoutInflater factory = LayoutInflater.from( this ); View view = factory.inflate( R.layout.filenamedialog, null ); mFileNameView = (EditText) view.findViewById( R.id.fileNameField ); mFileNameView.setText( mTrackName+".gpx" ); createAlertFileName( this, view, mFileNameDialogListener, null ).show(); } else { createAlertNoTrack( this, mNoTrackDialogListener, null ).show(); } handled = true; break; default: handled = super.onOptionsItemSelected(item); } return handled; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onOptionsItemSelected"
"@Override public boolean onOptionsItemSelected(MenuItem item) { boolean handled = false ; switch ( item.getItemId() ) { case MENU_TOGGLE: if( this.mLoggerServiceManager.isLogging() ) { this.mLoggerServiceManager.stopGPSLoggerService(); <MASK>updateBlankingBehavior();</MASK> item.setTitle( R.string.menu_toggle_on ); } else { this.mTrackId = this.mLoggerServiceManager.startGPSLoggerService(null); attempToMoveToTrack( this.mTrackId ); item.setTitle( R.string.menu_toggle_off ); LayoutInflater factory = LayoutInflater.from( this ); View view = factory.inflate( R.layout.namedialog, null ); mTrackNameView = (EditText) view.findViewById( R.id.nameField ); createTrackTitleDialog( this, view, mTrackNameDialogListener ).show(); } handled = true; break; case MENU_SETTINGS: Intent i = new Intent( this, SettingsDialog.class ); startActivity( i ); handled = true; break; case MENU_TRACKLIST: Intent tracklistIntent = new Intent(this, TrackList.class); tracklistIntent.putExtra( Tracks._ID, this.mTrackId ); startActivityForResult(tracklistIntent, MENU_TRACKLIST); break; case MENU_ACTION: if( this.mTrackId >= 0 ) { LayoutInflater factory = LayoutInflater.from( this ); View view = factory.inflate( R.layout.filenamedialog, null ); mFileNameView = (EditText) view.findViewById( R.id.fileNameField ); mFileNameView.setText( mTrackName+".gpx" ); createAlertFileName( this, view, mFileNameDialogListener, null ).show(); } else { createAlertNoTrack( this, mNoTrackDialogListener, null ).show(); } handled = true; break; default: handled = super.onOptionsItemSelected(item); } return handled; }"
Inversion-Mutation
megadiff
"public void popupDismissed(boolean topPopupOnly) { initializePopup(); // if the 2nd level popup gets dismissed if (mPopupStatus == POPUP_SECOND_LEVEL) { mPopupStatus = POPUP_FIRST_LEVEL; if (topPopupOnly) mModule.showPopup(mPopup); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "popupDismissed"
"public void popupDismissed(boolean topPopupOnly) { // if the 2nd level popup gets dismissed if (mPopupStatus == POPUP_SECOND_LEVEL) { <MASK>initializePopup();</MASK> mPopupStatus = POPUP_FIRST_LEVEL; if (topPopupOnly) mModule.showPopup(mPopup); } }"
Inversion-Mutation
megadiff
"private void bindMailboxItem(View view, Context context, Cursor cursor, boolean isLastChild) { // Reset the view (in case it was recycled) and prepare for binding AccountFolderListItem itemView = (AccountFolderListItem) view; itemView.bindViewInit(this, false); // Invisible (not "gone") to maintain spacing view.findViewById(R.id.chip).setVisibility(View.INVISIBLE); String text = cursor.getString(MAILBOX_DISPLAY_NAME); if (text != null) { TextView nameView = (TextView) view.findViewById(R.id.name); nameView.setText(text); } // TODO get/track live folder status text = null; TextView statusView = (TextView) view.findViewById(R.id.status); if (text != null) { statusView.setText(text); statusView.setVisibility(View.VISIBLE); } else { statusView.setVisibility(View.GONE); } int count = -1; text = cursor.getString(MAILBOX_UNREAD_COUNT); if (text != null) { count = Integer.valueOf(text); } TextView unreadCountView = (TextView) view.findViewById(R.id.new_message_count); TextView allCountView = (TextView) view.findViewById(R.id.all_message_count); int id = cursor.getInt(MAILBOX_COLUMN_ID); // If the unread count is zero, not to show countView. if (count > 0) { if (id == Mailbox.QUERY_ALL_FAVORITES || id == Mailbox.QUERY_ALL_DRAFTS || id == Mailbox.QUERY_ALL_OUTBOX) { allCountView.setVisibility(View.GONE); unreadCountView.setVisibility(View.VISIBLE); unreadCountView.setText(text); } else { unreadCountView.setVisibility(View.GONE); allCountView.setVisibility(View.VISIBLE); allCountView.setText(text); } } else { allCountView.setVisibility(View.GONE); unreadCountView.setVisibility(View.GONE); } view.findViewById(R.id.folder_button).setVisibility(View.GONE); view.findViewById(R.id.folder_separator).setVisibility(View.GONE); view.findViewById(R.id.default_sender).setVisibility(View.GONE); view.findViewById(R.id.folder_icon).setVisibility(View.VISIBLE); ((ImageView)view.findViewById(R.id.folder_icon)).setImageDrawable( Utility.FolderProperties.getInstance(context).getSummaryMailboxIconIds(id)); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "bindMailboxItem"
"private void bindMailboxItem(View view, Context context, Cursor cursor, boolean isLastChild) { // Reset the view (in case it was recycled) and prepare for binding AccountFolderListItem itemView = (AccountFolderListItem) view; itemView.bindViewInit(this, false); // Invisible (not "gone") to maintain spacing view.findViewById(R.id.chip).setVisibility(View.INVISIBLE); String text = cursor.getString(MAILBOX_DISPLAY_NAME); if (text != null) { TextView nameView = (TextView) view.findViewById(R.id.name); nameView.setText(text); } // TODO get/track live folder status text = null; TextView statusView = (TextView) view.findViewById(R.id.status); if (text != null) { statusView.setText(text); statusView.setVisibility(View.VISIBLE); } else { statusView.setVisibility(View.GONE); } int count = -1; text = cursor.getString(MAILBOX_UNREAD_COUNT); if (text != null) { count = Integer.valueOf(text); } TextView unreadCountView = (TextView) view.findViewById(R.id.new_message_count); TextView allCountView = (TextView) view.findViewById(R.id.all_message_count); // If the unread count is zero, not to show countView. if (count > 0) { <MASK>int id = cursor.getInt(MAILBOX_COLUMN_ID);</MASK> if (id == Mailbox.QUERY_ALL_FAVORITES || id == Mailbox.QUERY_ALL_DRAFTS || id == Mailbox.QUERY_ALL_OUTBOX) { allCountView.setVisibility(View.GONE); unreadCountView.setVisibility(View.VISIBLE); unreadCountView.setText(text); } else { unreadCountView.setVisibility(View.GONE); allCountView.setVisibility(View.VISIBLE); allCountView.setText(text); } } else { allCountView.setVisibility(View.GONE); unreadCountView.setVisibility(View.GONE); } view.findViewById(R.id.folder_button).setVisibility(View.GONE); view.findViewById(R.id.folder_separator).setVisibility(View.GONE); view.findViewById(R.id.default_sender).setVisibility(View.GONE); view.findViewById(R.id.folder_icon).setVisibility(View.VISIBLE); ((ImageView)view.findViewById(R.id.folder_icon)).setImageDrawable( Utility.FolderProperties.getInstance(context).getSummaryMailboxIconIds(id)); }"
Inversion-Mutation
megadiff
"List<String> getOutputAsList() { psout.flush(); String carray[] = baout.toString().split("\\n"); List<String> tmp = Arrays.asList(carray); return tmp; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getOutputAsList"
"List<String> getOutputAsList() { <MASK>String carray[] = baout.toString().split("\\n");</MASK> psout.flush(); List<String> tmp = Arrays.asList(carray); return tmp; }"
Inversion-Mutation
megadiff
"@FireExtended public void setDTG_End(final HiResDate newEnd) { // ok, how far is this from the current end long delta = newEnd.getMicros() - endDTG().getMicros(); // right, do we need to prune a few off? if (delta < 0) { // right, we're shortening the track. // check the end point is after the start if (newEnd.getMicros() < startDTG().getMicros()) return; // ok, it's worth bothering with. get ready to store ones we'll lose Vector<FixWrapper> onesToRemove = new Vector<FixWrapper>(); Iterator<Editable> iter = this.getData().iterator(); while (iter.hasNext()) { FixWrapper thisF = (FixWrapper) iter.next(); if (thisF.getTime().greaterThan(newEnd)) { onesToRemove.add(thisF); } } // and ditch them for (Iterator<FixWrapper> iterator = onesToRemove.iterator(); iterator .hasNext();) { FixWrapper thisFix = iterator.next(); this.removeElement(thisFix); } } // right, we may have pruned off too far. See if we need to put a bit back in... if (newEnd.greaterThan(endDTG())) { // right, we if we have to add another // find the current last point FixWrapper theLoc = (FixWrapper) this.last(); // don't worry about the location, we're going to DR it on anyway... WorldLocation newLoc = null; Fix newFix = new Fix(newEnd, newLoc, MWC.Algorithms.Conversions .Degs2Rads(this.getCourse()), MWC.Algorithms.Conversions.Kts2Yps(this.getSpeed().getValueIn( WorldSpeed.Kts))); // and apply the stretch FixWrapper newItem = new FixWrapper(newFix); // set some other bits newItem.setTrackWrapper(this._myTrack); newItem.setColor(theLoc.getActualColor()); newItem.setSymbolShowing(theLoc.getSymbolShowing()); newItem.setLabelShowing(theLoc.getLabelShowing()); newItem.setLabelLocation(theLoc.getLabelLocation()); newItem.setLabelFormat(theLoc.getLabelFormat()); this.add(newItem); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setDTG_End"
"@FireExtended public void setDTG_End(final HiResDate newEnd) { // ok, how far is this from the current end long delta = newEnd.getMicros() - endDTG().getMicros(); // right, do we need to prune a few off? if (delta < 0) { // right, we're shortening the track. // check the end point is after the start if (newEnd.getMicros() < startDTG().getMicros()) return; // ok, it's worth bothering with. get ready to store ones we'll lose Vector<FixWrapper> onesToRemove = new Vector<FixWrapper>(); Iterator<Editable> iter = this.getData().iterator(); while (iter.hasNext()) { FixWrapper thisF = (FixWrapper) iter.next(); if (thisF.getTime().greaterThan(newEnd)) { onesToRemove.add(thisF); } } // and ditch them for (Iterator<FixWrapper> iterator = onesToRemove.iterator(); iterator .hasNext();) { FixWrapper thisFix = iterator.next(); this.removeElement(thisFix); } } // right, we may have pruned off too far. See if we need to put a bit back in... if (newEnd.greaterThan(endDTG())) { // right, we if we have to add another // find the current last point FixWrapper theLoc = (FixWrapper) this.last(); // don't worry about the location, we're going to DR it on anyway... WorldLocation newLoc = null; Fix newFix = new Fix(newEnd, newLoc, MWC.Algorithms.Conversions .Degs2Rads(this.getCourse()), MWC.Algorithms.Conversions.Kts2Yps(this.getSpeed().getValueIn( WorldSpeed.Kts))); // and apply the stretch FixWrapper newItem = new FixWrapper(newFix); // set some other bits <MASK>newItem.setColor(theLoc.getActualColor());</MASK> newItem.setTrackWrapper(this._myTrack); newItem.setSymbolShowing(theLoc.getSymbolShowing()); newItem.setLabelShowing(theLoc.getLabelShowing()); newItem.setLabelLocation(theLoc.getLabelLocation()); newItem.setLabelFormat(theLoc.getLabelFormat()); this.add(newItem); } }"
Inversion-Mutation
megadiff
"void doResetRecords() { if (migrating) { throw new RuntimeException("Migration is already in progress"); } InitialState initialState = new InitialState(); Collection<CMap> cmaps = maps.values(); for (final CMap cmap : cmaps) { initialState.createAndAddMapState(cmap); } sendProcessableToAll(initialState, false); if (isSuperClient()) return; migrating = true; cmaps = maps.values(); final AtomicInteger count = new AtomicInteger(0); for (final CMap cmap : cmaps) { final Object[] records = cmap.mapRecords.values().toArray(); cmap.reset(); for (Object recObj : records) { final Record rec = (Record) recObj; if (rec.isActive()) { if (rec.getKey() == null || rec.getKey().size() == 0) { throw new RuntimeException("Record.key is null or empty " + rec.getKey()); } count.incrementAndGet(); executeLocally(new Runnable() { public void run() { try { MMigrate mmigrate = new MMigrate(); if (cmap.isMultiMap()) { List<Data> values = rec.getMultiValues(); if (values == null || values.size() == 0) { mmigrate.migrateMulti(rec, null); } else { for (Data value : values) { mmigrate.migrateMulti(rec, value); } } } else { boolean migrated = mmigrate.migrate(rec); if (!migrated) { logger.log(Level.FINEST, "Migration failed " + rec.getKey()); } } } finally { count.decrementAndGet(); } } }); } } } executeLocally(new Runnable() { public void run() { while (count.get() != 0) { try { Thread.sleep(1000); } catch (InterruptedException ignored) { return; } } MultiMigrationComplete mmc = new MultiMigrationComplete(); mmc.call(); logger.log(Level.FINEST, "Migration ended!"); migrating = false; } }); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doResetRecords"
"void doResetRecords() { if (migrating) { throw new RuntimeException("Migration is already in progress"); } <MASK>migrating = true;</MASK> InitialState initialState = new InitialState(); Collection<CMap> cmaps = maps.values(); for (final CMap cmap : cmaps) { initialState.createAndAddMapState(cmap); } sendProcessableToAll(initialState, false); if (isSuperClient()) return; cmaps = maps.values(); final AtomicInteger count = new AtomicInteger(0); for (final CMap cmap : cmaps) { final Object[] records = cmap.mapRecords.values().toArray(); cmap.reset(); for (Object recObj : records) { final Record rec = (Record) recObj; if (rec.isActive()) { if (rec.getKey() == null || rec.getKey().size() == 0) { throw new RuntimeException("Record.key is null or empty " + rec.getKey()); } count.incrementAndGet(); executeLocally(new Runnable() { public void run() { try { MMigrate mmigrate = new MMigrate(); if (cmap.isMultiMap()) { List<Data> values = rec.getMultiValues(); if (values == null || values.size() == 0) { mmigrate.migrateMulti(rec, null); } else { for (Data value : values) { mmigrate.migrateMulti(rec, value); } } } else { boolean migrated = mmigrate.migrate(rec); if (!migrated) { logger.log(Level.FINEST, "Migration failed " + rec.getKey()); } } } finally { count.decrementAndGet(); } } }); } } } executeLocally(new Runnable() { public void run() { while (count.get() != 0) { try { Thread.sleep(1000); } catch (InterruptedException ignored) { return; } } MultiMigrationComplete mmc = new MultiMigrationComplete(); mmc.call(); logger.log(Level.FINEST, "Migration ended!"); migrating = false; } }); }"
Inversion-Mutation
megadiff
"protected List<ResultConfig> buildResultConfigs(Class<?> clazz, PackageConfig.Builder pcb) { List<ResultConfig> configs = CollectUtils.newArrayList(); // load annotation results Result[] results = new Result[0]; Results rs = clazz.getAnnotation(Results.class); if (null == rs) { org.beangle.struts2.annotation.Action an = clazz .getAnnotation(org.beangle.struts2.annotation.Action.class); if (null != an) results = an.results(); } else { results = rs.value(); } Set<String> annotationResults = CollectUtils.newHashSet(); if (null != results) { for (Result result : results) { String resultType = result.type(); if (Strings.isEmpty(resultType)) resultType = "dispatcher"; ResultTypeConfig rtc = pcb.getResultType(resultType); configs.add(new ResultConfig.Builder(result.name(), rtc.getClassName()).addParam( rtc.getDefaultResultParam(), result.location()).build()); annotationResults.add(result.name()); } } // load ftl convension results if (null == profileService) return configs; String extention = profileService.getProfile(clazz.getName()).getViewExtension(); if (!extention.equals("ftl")) return configs; ResultTypeConfig rtc = pcb.getResultType("freemarker"); for (Method m : clazz.getMethods()) { String methodName = m.getName(); if (!annotationResults.contains(methodName) && shouldGenerateResult(m)) { String path = templateFinder.find(clazz, methodName, methodName, extention); if (null != path) { configs.add(new ResultConfig.Builder(m.getName(), rtc.getClassName()).addParam( rtc.getDefaultResultParam(), path).build()); } } } return configs; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "buildResultConfigs"
"protected List<ResultConfig> buildResultConfigs(Class<?> clazz, PackageConfig.Builder pcb) { List<ResultConfig> configs = CollectUtils.newArrayList(); // load annotation results Result[] results = new Result[0]; Results rs = clazz.getAnnotation(Results.class); if (null == rs) { org.beangle.struts2.annotation.Action an = clazz .getAnnotation(org.beangle.struts2.annotation.Action.class); if (null != an) results = an.results(); } else { results = rs.value(); } Set<String> annotationResults = CollectUtils.newHashSet(); if (null != results) { for (Result result : results) { String resultType = result.type(); if (Strings.isEmpty(resultType)) resultType = "dispatcher"; ResultTypeConfig rtc = pcb.getResultType(resultType); configs.add(new ResultConfig.Builder(result.name(), rtc.getClassName()).addParam( rtc.getDefaultResultParam(), result.location()).build()); annotationResults.add(result.name()); } } // load ftl convension results if (null == profileService) return configs; String extention = profileService.getProfile(clazz.getName()).getViewExtension(); if (!extention.equals("ftl")) return configs; for (Method m : clazz.getMethods()) { String methodName = m.getName(); if (!annotationResults.contains(methodName) && shouldGenerateResult(m)) { String path = templateFinder.find(clazz, methodName, methodName, extention); if (null != path) { <MASK>ResultTypeConfig rtc = pcb.getResultType("freemarker");</MASK> configs.add(new ResultConfig.Builder(m.getName(), rtc.getClassName()).addParam( rtc.getDefaultResultParam(), path).build()); } } } return configs; }"
Inversion-Mutation
megadiff
"public void getTitle() { StringBuilder sb = new StringBuilder(); String pageTitle = (String) request.getAttribute(SESSION_PAGE_TITLE); if (StringUtils.isNotEmpty(pageTitle)) { sb.append(" | "); sb.append(pageTitle); } sb.append(context.getServletContext().getServletContextName()); String title = sb.toString(); print(title); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getTitle"
"public void getTitle() { StringBuilder sb = new StringBuilder(); <MASK>sb.append(context.getServletContext().getServletContextName());</MASK> String pageTitle = (String) request.getAttribute(SESSION_PAGE_TITLE); if (StringUtils.isNotEmpty(pageTitle)) { sb.append(" | "); sb.append(pageTitle); } String title = sb.toString(); print(title); }"
Inversion-Mutation
megadiff
"public WidgetDataEvents addControls(Composite parent, final Listener statusListener) { Composite configCom = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(3, false); configCom.setLayout(layout); configCom.setLayoutData(new GridData(GridData.FILL_BOTH)); // custom package name Label lblCustomPakage = new Label(configCom, SWT.NONE); lblCustomPakage .setText(JBossWSCreationCoreMessages.Label_Custom_Package_Name); final Text txtCustomPkgName = new Text(configCom, SWT.BORDER); GridData gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 2; txtCustomPkgName.setLayoutData(gd); txtCustomPkgName.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { if (validatePackage(txtCustomPkgName.getText())) { model.setCustomPackage(txtCustomPkgName.getText()); } statusListener.handleEvent(null); } }); txtCustomPkgName.setText(model.getCustomPackage()); // target new Label(configCom, SWT.NONE) .setText(JBossWSCreationCoreMessages.Label_JaxWS_Target); final Combo cbSpec = new Combo(configCom, SWT.BORDER | SWT.READ_ONLY); cbSpec.add(JBossWSCreationCoreMessages.Value_Target_0, 0); cbSpec.add(JBossWSCreationCoreMessages.Value_Target_1, 1); if (JBossWSCreationCoreMessages.Value_Target_0 .equals(model.getTarget())) { cbSpec.select(0); } else { cbSpec.select(1); } gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 2; cbSpec.setLayoutData(gd); cbSpec.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { model.setTarget(cbSpec.getText()); } }); // catalog file new Label(configCom, SWT.NONE) .setText(JBossWSCreationCoreMessages.Label_Catalog_File); final Text txtCatlog = new Text(configCom, SWT.BORDER); txtCatlog.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Button btnCatlog = new Button(configCom, SWT.NONE); btnCatlog .setText(JBossWSCreationCoreMessages.Label_Button_Text_Seletion); btnCatlog.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { String fileLocation = new FileDialog(Display.getCurrent() .getActiveShell(), SWT.NONE).open(); txtCatlog.setText(fileLocation); model.setCatalog(fileLocation); } }); // binding files new Label(configCom, SWT.NONE) .setText(JBossWSCreationCoreMessages.Label_Binding_File); final List bindingList = new List(configCom, SWT.BORDER | SWT.SCROLL_LINE | SWT.V_SCROLL | SWT.H_SCROLL); gd = new GridData(GridData.FILL_HORIZONTAL); gd.heightHint = Display.getCurrent().getActiveShell().getBounds().height / 4; gd.verticalSpan = 3; bindingList.setLayoutData(gd); loadBindingFiles(bindingList); bindingList.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (bindingList.getSelectionIndex() >= 0) { btnRemove.setEnabled(true); } else { btnRemove.setEnabled(false); } } }); Button btnSelect = new Button(configCom, SWT.NONE); btnSelect .setText(JBossWSCreationCoreMessages.Label_Button_Text_Seletion); btnSelect.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { String fileLocation = new FileDialog(Display.getCurrent() .getActiveShell(), SWT.NONE).open(); if (fileLocation != null && !model.getBindingFiles().contains(fileLocation)) { bindingList.add(fileLocation); model.addBindingFile(fileLocation); } } }); new Label(configCom, SWT.NONE); btnRemove = new Button(configCom, SWT.NONE); btnRemove.setEnabled(false); btnRemove.setText(JBossWSCreationCoreMessages.Label_Button_Text_Remove); btnRemove.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { model.getBindingFiles().remove(bindingList.getSelectionIndex()); bindingList.remove(bindingList.getSelectionIndex()); if (bindingList.getSelectionIndex() == -1) { btnRemove.setEnabled(false); } } }); btnExtension = new Button(configCom, SWT.CHECK); gd = new GridData(); gd.horizontalSpan = 3; btnExtension.setLayoutData(gd); btnExtension .setText(JBossWSCreationCoreMessages.Label_EnableSOAP12_Binding_Extension); btnExtension.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { model.setEnableSOAP12(btnExtension.getSelection()); } }); if (model.getWsScenario() != WebServiceScenario.CLIENT) { btnGenDefaultImpl = new Button(configCom, SWT.CHECK); gd = new GridData(); gd.horizontalSpan = 3; btnGenDefaultImpl.setLayoutData(gd); btnGenDefaultImpl .setText(JBossWSCreationCoreMessages.Label_Generate_Impelemtation); btnGenDefaultImpl.setSelection(true); btnGenDefaultImpl.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { model.setGenerateImplementatoin(btnGenDefaultImpl .getSelection()); btnUpdateWebxml .setEnabled(btnGenDefaultImpl.getSelection()); if (!btnGenDefaultImpl.getSelection()) { model.setUpdateWebxml(false); } else { model.setUpdateWebxml(btnUpdateWebxml.getSelection()); } } }); btnUpdateWebxml = new Button(configCom, SWT.CHECK); gd = new GridData(); gd.horizontalSpan = 3; btnUpdateWebxml.setLayoutData(gd); btnUpdateWebxml .setText(JBossWSCreationCoreMessages.Label_Update_Webxml); btnUpdateWebxml.setSelection(true); btnUpdateWebxml.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { model.setUpdateWebxml(btnUpdateWebxml.getSelection()); } }); } // enable enable soap12 checkbox if the target jbossws runtime is less // than 3.0 updateExtensionButtonStatus(); return this; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addControls"
"public WidgetDataEvents addControls(Composite parent, final Listener statusListener) { Composite configCom = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(3, false); configCom.setLayout(layout); configCom.setLayoutData(new GridData(GridData.FILL_BOTH)); // custom package name Label lblCustomPakage = new Label(configCom, SWT.NONE); lblCustomPakage .setText(JBossWSCreationCoreMessages.Label_Custom_Package_Name); final Text txtCustomPkgName = new Text(configCom, SWT.BORDER); <MASK>txtCustomPkgName.setText(model.getCustomPackage());</MASK> GridData gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 2; txtCustomPkgName.setLayoutData(gd); txtCustomPkgName.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { if (validatePackage(txtCustomPkgName.getText())) { model.setCustomPackage(txtCustomPkgName.getText()); } statusListener.handleEvent(null); } }); // target new Label(configCom, SWT.NONE) .setText(JBossWSCreationCoreMessages.Label_JaxWS_Target); final Combo cbSpec = new Combo(configCom, SWT.BORDER | SWT.READ_ONLY); cbSpec.add(JBossWSCreationCoreMessages.Value_Target_0, 0); cbSpec.add(JBossWSCreationCoreMessages.Value_Target_1, 1); if (JBossWSCreationCoreMessages.Value_Target_0 .equals(model.getTarget())) { cbSpec.select(0); } else { cbSpec.select(1); } gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 2; cbSpec.setLayoutData(gd); cbSpec.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { model.setTarget(cbSpec.getText()); } }); // catalog file new Label(configCom, SWT.NONE) .setText(JBossWSCreationCoreMessages.Label_Catalog_File); final Text txtCatlog = new Text(configCom, SWT.BORDER); txtCatlog.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Button btnCatlog = new Button(configCom, SWT.NONE); btnCatlog .setText(JBossWSCreationCoreMessages.Label_Button_Text_Seletion); btnCatlog.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { String fileLocation = new FileDialog(Display.getCurrent() .getActiveShell(), SWT.NONE).open(); txtCatlog.setText(fileLocation); model.setCatalog(fileLocation); } }); // binding files new Label(configCom, SWT.NONE) .setText(JBossWSCreationCoreMessages.Label_Binding_File); final List bindingList = new List(configCom, SWT.BORDER | SWT.SCROLL_LINE | SWT.V_SCROLL | SWT.H_SCROLL); gd = new GridData(GridData.FILL_HORIZONTAL); gd.heightHint = Display.getCurrent().getActiveShell().getBounds().height / 4; gd.verticalSpan = 3; bindingList.setLayoutData(gd); loadBindingFiles(bindingList); bindingList.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (bindingList.getSelectionIndex() >= 0) { btnRemove.setEnabled(true); } else { btnRemove.setEnabled(false); } } }); Button btnSelect = new Button(configCom, SWT.NONE); btnSelect .setText(JBossWSCreationCoreMessages.Label_Button_Text_Seletion); btnSelect.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { String fileLocation = new FileDialog(Display.getCurrent() .getActiveShell(), SWT.NONE).open(); if (fileLocation != null && !model.getBindingFiles().contains(fileLocation)) { bindingList.add(fileLocation); model.addBindingFile(fileLocation); } } }); new Label(configCom, SWT.NONE); btnRemove = new Button(configCom, SWT.NONE); btnRemove.setEnabled(false); btnRemove.setText(JBossWSCreationCoreMessages.Label_Button_Text_Remove); btnRemove.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { model.getBindingFiles().remove(bindingList.getSelectionIndex()); bindingList.remove(bindingList.getSelectionIndex()); if (bindingList.getSelectionIndex() == -1) { btnRemove.setEnabled(false); } } }); btnExtension = new Button(configCom, SWT.CHECK); gd = new GridData(); gd.horizontalSpan = 3; btnExtension.setLayoutData(gd); btnExtension .setText(JBossWSCreationCoreMessages.Label_EnableSOAP12_Binding_Extension); btnExtension.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { model.setEnableSOAP12(btnExtension.getSelection()); } }); if (model.getWsScenario() != WebServiceScenario.CLIENT) { btnGenDefaultImpl = new Button(configCom, SWT.CHECK); gd = new GridData(); gd.horizontalSpan = 3; btnGenDefaultImpl.setLayoutData(gd); btnGenDefaultImpl .setText(JBossWSCreationCoreMessages.Label_Generate_Impelemtation); btnGenDefaultImpl.setSelection(true); btnGenDefaultImpl.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { model.setGenerateImplementatoin(btnGenDefaultImpl .getSelection()); btnUpdateWebxml .setEnabled(btnGenDefaultImpl.getSelection()); if (!btnGenDefaultImpl.getSelection()) { model.setUpdateWebxml(false); } else { model.setUpdateWebxml(btnUpdateWebxml.getSelection()); } } }); btnUpdateWebxml = new Button(configCom, SWT.CHECK); gd = new GridData(); gd.horizontalSpan = 3; btnUpdateWebxml.setLayoutData(gd); btnUpdateWebxml .setText(JBossWSCreationCoreMessages.Label_Update_Webxml); btnUpdateWebxml.setSelection(true); btnUpdateWebxml.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { model.setUpdateWebxml(btnUpdateWebxml.getSelection()); } }); } // enable enable soap12 checkbox if the target jbossws runtime is less // than 3.0 updateExtensionButtonStatus(); return this; }"
Inversion-Mutation
megadiff
"public PactProgram(File jarFile, String className, String... args) throws ProgramInvocationException { this.jarFile = jarFile; this.args = args; this.assemblerClass = getPactAssemblerFromJar(jarFile, className); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "PactProgram"
"public PactProgram(File jarFile, String className, String... args) throws ProgramInvocationException { <MASK>this.assemblerClass = getPactAssemblerFromJar(jarFile, className);</MASK> this.jarFile = jarFile; this.args = args; }"
Inversion-Mutation
megadiff
"public int numberOfLeadingOnes() { int ones = 0; for (boolean bit : string) { if (!bit) return ones; ones++; } return ones; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "numberOfLeadingOnes"
"public int numberOfLeadingOnes() { int ones = 0; for (boolean bit : string) { <MASK>ones++;</MASK> if (!bit) return ones; } return ones; }"
Inversion-Mutation
megadiff
"private List<AggregationRecord> getAggregationResults() throws SQLException { log.debug("getAggregationResults(): <<<"); log.debug("Getting user list"); String unq = "select distinct client from networks"; List<Integer> clients = new ArrayList<Integer>(); PreparedStatement pst = con.prepareStatement(unq); ResultSet rst = pst.executeQuery(); while(rst.next()){ clients.add(rst.getInt(1)); } rst.close(); pst.close(); String collect = "select client, date_trunc('day', dat)::date as dat, sum(incoming) as input, sum(outcoming) " + "as output from client_ntraffic where dat >= date_trunc('day', now())::timestamp and client = ? group by 1,2"; PreparedStatement ps = con.prepareStatement(collect); List<AggregationRecord> results = new ArrayList<AggregationRecord>(); for (Integer id : clients){ ps.setInt(1, id); ResultSet rs = ps.executeQuery(); if (rs.next()){ results.add(new AggregationRecord(rs.getInt(1), rs.getDate(2), rs.getLong(3), rs.getLong(4))); } rs.close(); } ps.close(); log.debug("getAggregationResults(): >>>"); return results; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getAggregationResults"
"private List<AggregationRecord> getAggregationResults() throws SQLException { log.debug("getAggregationResults(): <<<"); log.debug("Getting user list"); String unq = "select distinct client from networks"; List<Integer> clients = new ArrayList<Integer>(); PreparedStatement pst = con.prepareStatement(unq); ResultSet rst = pst.executeQuery(); while(rst.next()){ clients.add(rst.getInt(1)); } rst.close(); pst.close(); String collect = "select client, date_trunc('day', dat)::date as dat, sum(incoming) as input, sum(outcoming) " + "as output from client_ntraffic where dat >= date_trunc('day', now())::timestamp and client = ? group by 1,2"; PreparedStatement ps = con.prepareStatement(collect); List<AggregationRecord> results = new ArrayList<AggregationRecord>(); for (Integer id : clients){ ps.setInt(1, id); ResultSet rs = ps.executeQuery(); if (rs.next()){ results.add(new AggregationRecord(rs.getInt(1), rs.getDate(2), rs.getLong(3), rs.getLong(4))); } rs.close(); <MASK>ps.close();</MASK> } log.debug("getAggregationResults(): >>>"); return results; }"
Inversion-Mutation
megadiff
"public Event handleEvent (Event event) { switch (event.getEventType()) { case START_BATCH: firstOutputCreated = false; if ( params.getOutputFormat().equals(Parameters.FORMAT_PO) ) { outputType = PO_OUTPUT; createPOWriter(); } else if ( params.getOutputFormat().equals(Parameters.FORMAT_TMX) ) { outputType = TMX_OUTPUT; createTMXWriter(); } else if ( params.getOutputFormat().equals(Parameters.FORMAT_PENSIEVE) ) { outputType = PENSIEVE_OUTPUT; createPensieveWriter(); } else if ( params.getOutputFormat().equals(Parameters.FORMAT_TABLE) ) { outputType = TABLE_OUTPUT; createTableWriter(); } // Start sending event to the writer writer.handleEvent(event); break; case END_BATCH: if ( params.isSingleOutput() ) { Ending ending = new Ending("end"); writer.handleEvent(new Event(EventType.END_DOCUMENT, ending)); writer.close(); } break; case START_DOCUMENT: if ( !firstOutputCreated || !params.isSingleOutput() ) { switch ( outputType ) { case PO_OUTPUT: startPOOutput(); break; case TMX_OUTPUT: startTMXOutput(); break; case TABLE_OUTPUT: startTableOutput(); break; case PENSIEVE_OUTPUT: startPensieveOutput(); break; } writer.handleEvent(event); } break; case END_DOCUMENT: if ( !params.isSingleOutput() ) { writer.handleEvent(event); writer.close(); } // Else: Do nothing break; case START_SUBDOCUMENT: case END_SUBDOCUMENT: case START_GROUP: case END_GROUP: writer.handleEvent(event); break; case TEXT_UNIT: processTextUnit(event); break; case START_BATCH_ITEM: case END_BATCH_ITEM: case RAW_DOCUMENT: case DOCUMENT_PART: case CUSTOM: // Do nothing break; } return event; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handleEvent"
"public Event handleEvent (Event event) { switch (event.getEventType()) { case START_BATCH: firstOutputCreated = false; if ( params.getOutputFormat().equals(Parameters.FORMAT_PO) ) { outputType = PO_OUTPUT; createPOWriter(); } else if ( params.getOutputFormat().equals(Parameters.FORMAT_TMX) ) { outputType = TMX_OUTPUT; createTMXWriter(); } else if ( params.getOutputFormat().equals(Parameters.FORMAT_PENSIEVE) ) { outputType = PENSIEVE_OUTPUT; createPensieveWriter(); } else if ( params.getOutputFormat().equals(Parameters.FORMAT_TABLE) ) { outputType = TABLE_OUTPUT; createTableWriter(); } // Start sending event to the writer <MASK>writer.handleEvent(event);</MASK> break; case END_BATCH: if ( params.isSingleOutput() ) { Ending ending = new Ending("end"); writer.handleEvent(new Event(EventType.END_DOCUMENT, ending)); writer.close(); } break; case START_DOCUMENT: if ( !firstOutputCreated || !params.isSingleOutput() ) { switch ( outputType ) { case PO_OUTPUT: startPOOutput(); break; case TMX_OUTPUT: startTMXOutput(); break; case TABLE_OUTPUT: startTableOutput(); break; case PENSIEVE_OUTPUT: startPensieveOutput(); break; } } <MASK>writer.handleEvent(event);</MASK> break; case END_DOCUMENT: if ( !params.isSingleOutput() ) { <MASK>writer.handleEvent(event);</MASK> writer.close(); } // Else: Do nothing break; case START_SUBDOCUMENT: case END_SUBDOCUMENT: case START_GROUP: case END_GROUP: <MASK>writer.handleEvent(event);</MASK> break; case TEXT_UNIT: processTextUnit(event); break; case START_BATCH_ITEM: case END_BATCH_ITEM: case RAW_DOCUMENT: case DOCUMENT_PART: case CUSTOM: // Do nothing break; } return event; }"
Inversion-Mutation
megadiff
"public boolean processBitstream(Context c, Item item, Bitstream source, boolean overWrite) throws Exception { // get bitstream filename, calculate destination filename String newName = getFilteredName(source.getName()); Bitstream existingBitstream = null; // is there an existing rendition? Bundle targetBundle = null; // bundle we're modifying Bundle [] bundles = item.getBundles(getBundleName()); // check if destination bitstream exists if( bundles.length > 0 ) { // only finds the last match (FIXME?) for(int i = 0; i < bundles.length; i++) { Bitstream [] bitstreams = bundles[i].getBitstreams(); for(int j = 0; j < bitstreams.length; j++) { if(bitstreams[j].getName().equals(newName)) { targetBundle = bundles[i]; existingBitstream = bitstreams[j]; } } } } // if exists and overwrite = false, exit if( !overWrite && (existingBitstream!=null) ) { System.out.println("SKIPPED: bitstream " + source.getID() + " because '" + newName + "' already exists"); return false; } // create new bundle if needed if( bundles.length < 1 ) { targetBundle=item.createBundle(getBundleName()); } else { // take the first match targetBundle = bundles[0]; } InputStream destStream = getDestinationStream(source.retrieve()); Bitstream b = targetBundle.createBitstream(destStream); // Now set the format and name of the bitstream b.setName(newName); b.setSource("Written by MediaFilter " + this.getClass().getName() ); // or obj.getClass().getName(); // Find the proper format BitstreamFormat bf = BitstreamFormat.findByShortDescription( c, getFormatString()); b.setFormat(bf); b.update(); // fixme - set date? // we are overwriting, so remove old bitstream if(existingBitstream != null) { targetBundle.removeBitstream(existingBitstream); } System.out.println("FILTERED: bitstream "+source.getID()+" and created '" + newName + "'"); return true; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "processBitstream"
"public boolean processBitstream(Context c, Item item, Bitstream source, boolean overWrite) throws Exception { // get bitstream filename, calculate destination filename String newName = getFilteredName(source.getName()); Bitstream existingBitstream = null; // is there an existing rendition? Bundle targetBundle = null; // bundle we're modifying Bundle [] bundles = item.getBundles(getBundleName()); // check if destination bitstream exists if( bundles.length > 0 ) { // only finds the last match (FIXME?) for(int i = 0; i < bundles.length; i++) { Bitstream [] bitstreams = bundles[i].getBitstreams(); for(int j = 0; j < bitstreams.length; j++) { if(bitstreams[j].getName().equals(newName)) { targetBundle = bundles[i]; existingBitstream = bitstreams[j]; } } } } // if exists and overwrite = false, exit if( !overWrite && (existingBitstream!=null) ) { System.out.println("SKIPPED: bitstream " + source.getID() + " because '" + newName + "' already exists"); return false; } // create new bundle if needed if( bundles.length < 1 ) { targetBundle=item.createBundle(getBundleName()); } else { // take the first match targetBundle = bundles[0]; } InputStream destStream = getDestinationStream(source.retrieve()); Bitstream b = targetBundle.createBitstream(destStream); // Now set the format and name of the bitstream b.setName(newName); b.setSource("Written by MediaFilter " + this.getClass().getName() ); // or obj.getClass().getName(); <MASK>b.update();</MASK> // Find the proper format BitstreamFormat bf = BitstreamFormat.findByShortDescription( c, getFormatString()); b.setFormat(bf); // fixme - set date? // we are overwriting, so remove old bitstream if(existingBitstream != null) { targetBundle.removeBitstream(existingBitstream); } System.out.println("FILTERED: bitstream "+source.getID()+" and created '" + newName + "'"); return true; }"