type
stringclasses
1 value
dataset
stringclasses
1 value
input
stringlengths
75
160k
instruction
stringlengths
117
171
output
stringlengths
88
168k
Inversion-Mutation
megadiff
"@Override public void onEntityDeath(EntityDeathEvent event) { Entity defender = event.getEntity(); Player attacker = null; EntityDamageEvent lastDamage = defender.getLastDamageCause(); if (lastDamage instanceof EntityDamageByEntityEvent) { Entity damager = ((EntityDamageByEntityEvent) lastDamage).getDamager(); if (damager instanceof Player) { attacker = (Player) damager; } else if (damager instanceof Projectile) { Projectile projectile = (Projectile) damager; if (projectile.getShooter() instanceof Player) { attacker = (Player) projectile.getShooter(); } } } Properties prop = plugin.getConfigManager().getProperties(); if (defender instanceof Player) { // Incur 5% experience loss to dying player // 5% of the next level's experience requirement // Experience loss can optionally reduce Level Hero heroDefender = plugin.getHeroManager().getHero((Player) defender); double exp = heroDefender.getExperience(); int level = prop.getLevel(exp); if(prop.resetOnDeath) { //Wipe xp if we are in hardcore mode heroDefender.gainExp(-heroDefender.getExperience(), ExperienceType.DEATH, false); heroDefender.changeHeroClass(plugin.getClassManager().getDefaultClass()); } else { //otherwise just do standard loss int currentLevelExp = (int) prop.getExperience(level); int nextLevelExp = (int) prop.getExperience(level + 1); double expLossPercent = prop.expLoss; if(heroDefender.getHeroClass().getExpLoss() != -1) { expLossPercent = heroDefender.getHeroClass().getExpLoss(); } double expLoss = (nextLevelExp - currentLevelExp) * expLossPercent; heroDefender.gainExp(-expLoss, ExperienceType.DEATH, false); } //Always reset mana on death heroDefender.setMana(0); // Remove any nonpersistent effects for (Effect effect : heroDefender.getEffects()) { if (!effect.isPersistent()) { heroDefender.removeEffect(effect); } } } if (attacker != null) { // Get the Hero representing the player Hero hero = plugin.getHeroManager().getHero(attacker); // Get the player's class definition HeroClass playerClass = hero.getHeroClass(); // Get the sources of experience for the player's class Set<ExperienceType> expSources = playerClass.getExperienceSources(); double addedExp = 0; ExperienceType experienceType = null; // If the Player killed another Player we check to see if they can earn EXP from PVP. if (defender instanceof Player && expSources.contains(ExperienceType.PVP)) { // Don't award XP for Players killing themselves if (!(defender.equals(attacker))) { prop.playerDeaths.put((Player) defender, defender.getLocation()); addedExp = prop.playerKillingExp; experienceType = ExperienceType.PVP; } } //If this entity is on the summon map, don't award XP! if (hero.getSummons().contains(defender)) return; // If the Player killed a Monster/Animal then we check to see if they can earn EXP from KILLING. if (defender instanceof LivingEntity && !(defender instanceof Player) && expSources.contains(ExperienceType.KILLING)) { // Get the dying entity's CreatureType CreatureType type = Properties.getCreatureFromEntity(defender); if (type != null && !hero.getSummons().contains(defender)) { // If EXP hasn't been assigned for this Entity then we stop here. if (!prop.creatureKillingExp.containsKey(type)) return; addedExp = prop.creatureKillingExp.get(type); experienceType = ExperienceType.KILLING; } } if (experienceType != null && addedExp > 0) { hero.gainExp(addedExp, experienceType); } // Make sure to remove any effects this creature may have had from the creatureEffect map if (defender instanceof Creature) { plugin.getHeroManager().clearCreatureEffects((Creature) defender); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onEntityDeath"
"@Override public void onEntityDeath(EntityDeathEvent event) { Entity defender = event.getEntity(); Player attacker = null; EntityDamageEvent lastDamage = defender.getLastDamageCause(); if (lastDamage instanceof EntityDamageByEntityEvent) { Entity damager = ((EntityDamageByEntityEvent) lastDamage).getDamager(); if (damager instanceof Player) { attacker = (Player) damager; } else if (damager instanceof Projectile) { Projectile projectile = (Projectile) damager; if (projectile.getShooter() instanceof Player) { attacker = (Player) projectile.getShooter(); } } } Properties prop = plugin.getConfigManager().getProperties(); if (defender instanceof Player) { // Incur 5% experience loss to dying player // 5% of the next level's experience requirement // Experience loss can optionally reduce Level Hero heroDefender = plugin.getHeroManager().getHero((Player) defender); double exp = heroDefender.getExperience(); int level = prop.getLevel(exp); if(prop.resetOnDeath) { //Wipe xp if we are in hardcore mode <MASK>heroDefender.changeHeroClass(plugin.getClassManager().getDefaultClass());</MASK> heroDefender.gainExp(-heroDefender.getExperience(), ExperienceType.DEATH, false); } else { //otherwise just do standard loss int currentLevelExp = (int) prop.getExperience(level); int nextLevelExp = (int) prop.getExperience(level + 1); double expLossPercent = prop.expLoss; if(heroDefender.getHeroClass().getExpLoss() != -1) { expLossPercent = heroDefender.getHeroClass().getExpLoss(); } double expLoss = (nextLevelExp - currentLevelExp) * expLossPercent; heroDefender.gainExp(-expLoss, ExperienceType.DEATH, false); } //Always reset mana on death heroDefender.setMana(0); // Remove any nonpersistent effects for (Effect effect : heroDefender.getEffects()) { if (!effect.isPersistent()) { heroDefender.removeEffect(effect); } } } if (attacker != null) { // Get the Hero representing the player Hero hero = plugin.getHeroManager().getHero(attacker); // Get the player's class definition HeroClass playerClass = hero.getHeroClass(); // Get the sources of experience for the player's class Set<ExperienceType> expSources = playerClass.getExperienceSources(); double addedExp = 0; ExperienceType experienceType = null; // If the Player killed another Player we check to see if they can earn EXP from PVP. if (defender instanceof Player && expSources.contains(ExperienceType.PVP)) { // Don't award XP for Players killing themselves if (!(defender.equals(attacker))) { prop.playerDeaths.put((Player) defender, defender.getLocation()); addedExp = prop.playerKillingExp; experienceType = ExperienceType.PVP; } } //If this entity is on the summon map, don't award XP! if (hero.getSummons().contains(defender)) return; // If the Player killed a Monster/Animal then we check to see if they can earn EXP from KILLING. if (defender instanceof LivingEntity && !(defender instanceof Player) && expSources.contains(ExperienceType.KILLING)) { // Get the dying entity's CreatureType CreatureType type = Properties.getCreatureFromEntity(defender); if (type != null && !hero.getSummons().contains(defender)) { // If EXP hasn't been assigned for this Entity then we stop here. if (!prop.creatureKillingExp.containsKey(type)) return; addedExp = prop.creatureKillingExp.get(type); experienceType = ExperienceType.KILLING; } } if (experienceType != null && addedExp > 0) { hero.gainExp(addedExp, experienceType); } // Make sure to remove any effects this creature may have had from the creatureEffect map if (defender instanceof Creature) { plugin.getHeroManager().clearCreatureEffects((Creature) defender); } } }"
Inversion-Mutation
megadiff
"public static File identifyDeployment(URL url) { String actualFilePath = url.getPath(); String nestedPath = ""; if (actualFilePath.startsWith("file:")) { actualFilePath = actualFilePath.substring(5); } int nestedSeperator = actualFilePath.indexOf('!'); if (nestedSeperator != -1) { nestedPath = actualFilePath.substring(nestedSeperator + 1); actualFilePath = actualFilePath.substring(0, nestedSeperator); if (nestedPath.equals("/")) { nestedPath = ""; } } if (nestedPath.length() != 0) { throw new RuntimeException("cannot access nested resource: " + actualFilePath); } log.info("identifying deployment type for uri: " + actualFilePath); return findActualDeploymentFile(new File(actualFilePath)); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "identifyDeployment"
"public static File identifyDeployment(URL url) { String actualFilePath = url.getPath(); String nestedPath = ""; if (actualFilePath.startsWith("file:")) { actualFilePath = actualFilePath.substring(5); } int nestedSeperator = actualFilePath.indexOf('!'); if (nestedSeperator != -1) { <MASK>actualFilePath = actualFilePath.substring(0, nestedSeperator);</MASK> nestedPath = actualFilePath.substring(nestedSeperator + 1); if (nestedPath.equals("/")) { nestedPath = ""; } } if (nestedPath.length() != 0) { throw new RuntimeException("cannot access nested resource: " + actualFilePath); } log.info("identifying deployment type for uri: " + actualFilePath); return findActualDeploymentFile(new File(actualFilePath)); }"
Inversion-Mutation
megadiff
"@Override public void react( SEMAINEMessage m ) throws JMSException { if( m instanceof SEMAINEEmmaMessage ) { SEMAINEEmmaMessage em = (SEMAINEEmmaMessage)m; /* Reading words */ //System.out.println(em.getText()); Element wordSequence = em.getSequence(); if( wordSequence != null ) { //System.out.println("WordSequence found"); List<Element> wordElements = XMLTool.getChildrenByLocalNameNS(wordSequence, EMMA.E_INTERPRETATION, EMMA.namespaceURI); if( wordElements.size() > 0 ) { //System.out.println("WordElements found"); String detectedKeywords = ""; String starttime = null; String detectedTimes = ""; String confidences = ""; for( Element wordElem : wordElements ) { if( wordElem.hasAttribute("tokens") ) { detectedKeywords = detectedKeywords + wordElem.getAttribute("tokens") + " "; } if( wordElem.hasAttribute("offset-to-start") ) { detectedTimes = detectedTimes + wordElem.getAttribute("offset-to-start") + " "; } if( wordElem.hasAttribute("confidence") ) { confidences = confidences + wordElem.getAttribute("confidence") + " "; } if( starttime == null && wordSequence.hasAttribute("offset-to-start") ) { starttime = wordSequence.getAttribute("offset-to-start"); } } detectedKeywords = detectedKeywords.replaceAll("<s>", "").replaceAll("</s>", "").trim(); detectedTimes = detectedTimes.trim(); if(starttime != null) { DMLogger.getLogger().logWords( Long.parseLong( starttime ), detectedKeywords, detectedTimes, confidences ); DialogueAct act = analyseData( detectedKeywords, Long.parseLong( starttime ) ); sendDialogueAct( act ); } } } } if( m instanceof SEMAINEStateMessage ) { SEMAINEStateMessage sm = ((SEMAINEStateMessage)m); StateInfo stateInfo = sm.getState(); StateInfo.Type stateInfoType = stateInfo.getType(); switch (stateInfoType) { case UserState: processHeadMovements( stateInfo ); break; } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "react"
"@Override public void react( SEMAINEMessage m ) throws JMSException { if( m instanceof SEMAINEEmmaMessage ) { SEMAINEEmmaMessage em = (SEMAINEEmmaMessage)m; /* Reading words */ //System.out.println(em.getText()); Element wordSequence = em.getSequence(); if( wordSequence != null ) { //System.out.println("WordSequence found"); List<Element> wordElements = XMLTool.getChildrenByLocalNameNS(wordSequence, EMMA.E_INTERPRETATION, EMMA.namespaceURI); if( wordElements.size() > 0 ) { //System.out.println("WordElements found"); String detectedKeywords = ""; String starttime = null; String detectedTimes = ""; String confidences = ""; for( Element wordElem : wordElements ) { if( wordElem.hasAttribute("tokens") ) { detectedKeywords = detectedKeywords + wordElem.getAttribute("tokens") + " "; } if( wordElem.hasAttribute("offset-to-start") ) { detectedTimes = detectedTimes + wordElem.getAttribute("offset-to-start") + " "; } if( wordElem.hasAttribute("confidence") ) { confidences = confidences + wordElem.getAttribute("confidence") + " "; } if( starttime == null && wordSequence.hasAttribute("offset-to-start") ) { starttime = wordSequence.getAttribute("offset-to-start"); } } detectedKeywords = detectedKeywords.replaceAll("<s>", "").replaceAll("</s>", "").trim(); detectedTimes = detectedTimes.trim(); <MASK>DMLogger.getLogger().logWords( Long.parseLong( starttime ), detectedKeywords, detectedTimes, confidences );</MASK> if(starttime != null) { DialogueAct act = analyseData( detectedKeywords, Long.parseLong( starttime ) ); sendDialogueAct( act ); } } } } if( m instanceof SEMAINEStateMessage ) { SEMAINEStateMessage sm = ((SEMAINEStateMessage)m); StateInfo stateInfo = sm.getState(); StateInfo.Type stateInfoType = stateInfo.getType(); switch (stateInfoType) { case UserState: processHeadMovements( stateInfo ); break; } } }"
Inversion-Mutation
megadiff
"public void end() { _running.set(false); _events.add(false); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "end"
"public void end() { <MASK>_events.add(false);</MASK> _running.set(false); }"
Inversion-Mutation
megadiff
"@SuppressWarnings("unchecked") protected AbstractBeanDefinition parseInternal(final Element element, final ParserContext parserContext) { // this is the bean peforming the registration of custom listeners BeanDefinitionBuilder listenerRegBean = BeanDefinitionBuilder.rootBeanDefinition(CustomListenersBean.class); Element emElement = DomUtils.getChildElementByTagName(element, "eventManager"); if (emElement != null) { // if the user overrides the default eventManager final String beanName = emElement.getAttribute("ref"); listenerRegBean.addDependsOn(beanName); listenerRegBean.addPropertyReference("eventManager", beanName); } List<Element> listenerElements = DomUtils.getChildElementsByTagName(element, "listener"); ManagedList listeners = new ManagedList(listenerElements.size()); for (Element listenerElement : listenerElements) { final BeanDefinitionParserDelegate beanParserDelegate = new BeanDefinitionParserDelegate(parserContext.getReaderContext()); // parse nested spring bean definitions Element bean = DomUtils.getChildElementByTagName(listenerElement, "bean"); // it could be a ref to an existing bean too if (bean == null) { Element ref = DomUtils.getChildElementByTagName(listenerElement, "ref"); String beanName = StringUtils.defaultString(ref.getAttribute("bean"), ref.getAttribute("local")); if (StringUtils.isBlank(beanName)) { throw new IllegalArgumentException("A listener ref element has neither 'bean' nor 'local' attributes"); } listeners.add(new RuntimeBeanReference(beanName)); } else { // need to init defaults beanParserDelegate.initDefaults(bean); BeanDefinitionHolder listener = beanParserDelegate.parseBeanDefinitionElement(bean); listeners.add(listener); } } listenerRegBean.addPropertyValue("customListeners", listeners); return listenerRegBean.getBeanDefinition(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "parseInternal"
"@SuppressWarnings("unchecked") protected AbstractBeanDefinition parseInternal(final Element element, final ParserContext parserContext) { // this is the bean peforming the registration of custom listeners BeanDefinitionBuilder listenerRegBean = BeanDefinitionBuilder.rootBeanDefinition(CustomListenersBean.class); Element emElement = DomUtils.getChildElementByTagName(element, "eventManager"); if (emElement != null) { // if the user overrides the default eventManager final String beanName = emElement.getAttribute("ref"); listenerRegBean.addDependsOn(beanName); listenerRegBean.addPropertyReference("eventManager", beanName); } List<Element> listenerElements = DomUtils.getChildElementsByTagName(element, "listener"); ManagedList listeners = new ManagedList(listenerElements.size()); for (Element listenerElement : listenerElements) { final BeanDefinitionParserDelegate beanParserDelegate = new BeanDefinitionParserDelegate(parserContext.getReaderContext()); // parse nested spring bean definitions Element bean = DomUtils.getChildElementByTagName(listenerElement, "bean"); // it could be a ref to an existing bean too if (bean == null) { Element ref = DomUtils.getChildElementByTagName(listenerElement, "ref"); String beanName = StringUtils.defaultString(ref.getAttribute("bean"), ref.getAttribute("local")); if (StringUtils.isBlank(beanName)) { throw new IllegalArgumentException("A listener ref element has neither 'bean' nor 'local' attributes"); } listeners.add(new RuntimeBeanReference(beanName)); } else { <MASK>BeanDefinitionHolder listener = beanParserDelegate.parseBeanDefinitionElement(bean);</MASK> // need to init defaults beanParserDelegate.initDefaults(bean); listeners.add(listener); } } listenerRegBean.addPropertyValue("customListeners", listeners); return listenerRegBean.getBeanDefinition(); }"
Inversion-Mutation
megadiff
"@Override public void handleMessage(Message msg) { BluetoothAudioGateway.IncomingConnectionInfo info = (BluetoothAudioGateway.IncomingConnectionInfo)msg.obj; int type = BluetoothHandsfree.TYPE_UNKNOWN; switch(msg.what) { case BluetoothAudioGateway.MSG_INCOMING_HEADSET_CONNECTION: type = BluetoothHandsfree.TYPE_HEADSET; break; case BluetoothAudioGateway.MSG_INCOMING_HANDSFREE_CONNECTION: type = BluetoothHandsfree.TYPE_HANDSFREE; break; } Log.i(TAG, "Incoming rfcomm (" + BluetoothHandsfree.typeToString(type) + ") connection from " + info.mRemoteDevice + "on channel " + info.mRfcommChan); int priority = BluetoothHeadset.PRIORITY_OFF; HeadsetBase headset; try { priority = mBinder.getPriority(info.mRemoteDevice); } catch (RemoteException e) {} if (priority <= BluetoothHeadset.PRIORITY_OFF) { Log.i(TAG, "Rejecting incoming connection because priority = " + priority); headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice, info.mSocketFd, info.mRfcommChan, null); headset.disconnect(); return; } switch (mState) { case BluetoothHeadset.STATE_DISCONNECTED: // headset connecting us, lets join mRemoteDevice = info.mRemoteDevice; setState(BluetoothHeadset.STATE_CONNECTING); headset = new HeadsetBase(mPowerManager, mAdapter, mRemoteDevice, info.mSocketFd, info.mRfcommChan, mConnectedStatusHandler); mHeadsetType = type; mConnectingStatusHandler.obtainMessage(RFCOMM_CONNECTED, headset).sendToTarget(); break; case BluetoothHeadset.STATE_CONNECTING: if (!info.mRemoteDevice.equals(mRemoteDevice)) { // different headset, ignoring Log.i(TAG, "Already attempting connect to " + mRemoteDevice + ", disconnecting " + info.mRemoteDevice); headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice, info.mSocketFd, info.mRfcommChan, null); headset.disconnect(); } // If we are here, we are in danger of a race condition // incoming rfcomm connection, but we are also attempting an // outgoing connection. Lets try and interrupt the outgoing // connection. Log.i(TAG, "Incoming and outgoing connections to " + info.mRemoteDevice + ". Cancel outgoing connection."); if (mConnectThread != null) { mConnectThread.interrupt(); } // Now continue with new connection, including calling callback mHeadset = new HeadsetBase(mPowerManager, mAdapter, mRemoteDevice, info.mSocketFd, info.mRfcommChan, mConnectedStatusHandler); mHeadsetType = type; setState(BluetoothHeadset.STATE_CONNECTED, BluetoothHeadset.RESULT_SUCCESS); mBtHandsfree.connectHeadset(mHeadset, mHeadsetType); // Make sure that old outgoing connect thread is dead. if (mConnectThread != null) { try { // TODO: Don't block in the main thread Log.w(TAG, "Block in main thread to join stale outgoing connection thread"); mConnectThread.join(); } catch (InterruptedException e) { Log.e(TAG, "Connection cancelled twice eh?", e); } mConnectThread = null; } if (DBG) log("Successfully used incoming connection, and cancelled outgoing " + " connection"); break; case BluetoothHeadset.STATE_CONNECTED: Log.i(TAG, "Already connected to " + mRemoteDevice + ", disconnecting " + info.mRemoteDevice); headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice, info.mSocketFd, info.mRfcommChan, null); headset.disconnect(); break; } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handleMessage"
"@Override public void handleMessage(Message msg) { BluetoothAudioGateway.IncomingConnectionInfo info = (BluetoothAudioGateway.IncomingConnectionInfo)msg.obj; int type = BluetoothHandsfree.TYPE_UNKNOWN; switch(msg.what) { case BluetoothAudioGateway.MSG_INCOMING_HEADSET_CONNECTION: type = BluetoothHandsfree.TYPE_HEADSET; break; case BluetoothAudioGateway.MSG_INCOMING_HANDSFREE_CONNECTION: type = BluetoothHandsfree.TYPE_HANDSFREE; break; } Log.i(TAG, "Incoming rfcomm (" + BluetoothHandsfree.typeToString(type) + ") connection from " + info.mRemoteDevice + "on channel " + info.mRfcommChan); int priority = BluetoothHeadset.PRIORITY_OFF; HeadsetBase headset; try { priority = mBinder.getPriority(info.mRemoteDevice); } catch (RemoteException e) {} if (priority <= BluetoothHeadset.PRIORITY_OFF) { Log.i(TAG, "Rejecting incoming connection because priority = " + priority); headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice, info.mSocketFd, info.mRfcommChan, null); headset.disconnect(); return; } switch (mState) { case BluetoothHeadset.STATE_DISCONNECTED: // headset connecting us, lets join <MASK>setState(BluetoothHeadset.STATE_CONNECTING);</MASK> mRemoteDevice = info.mRemoteDevice; headset = new HeadsetBase(mPowerManager, mAdapter, mRemoteDevice, info.mSocketFd, info.mRfcommChan, mConnectedStatusHandler); mHeadsetType = type; mConnectingStatusHandler.obtainMessage(RFCOMM_CONNECTED, headset).sendToTarget(); break; case BluetoothHeadset.STATE_CONNECTING: if (!info.mRemoteDevice.equals(mRemoteDevice)) { // different headset, ignoring Log.i(TAG, "Already attempting connect to " + mRemoteDevice + ", disconnecting " + info.mRemoteDevice); headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice, info.mSocketFd, info.mRfcommChan, null); headset.disconnect(); } // If we are here, we are in danger of a race condition // incoming rfcomm connection, but we are also attempting an // outgoing connection. Lets try and interrupt the outgoing // connection. Log.i(TAG, "Incoming and outgoing connections to " + info.mRemoteDevice + ". Cancel outgoing connection."); if (mConnectThread != null) { mConnectThread.interrupt(); } // Now continue with new connection, including calling callback mHeadset = new HeadsetBase(mPowerManager, mAdapter, mRemoteDevice, info.mSocketFd, info.mRfcommChan, mConnectedStatusHandler); mHeadsetType = type; setState(BluetoothHeadset.STATE_CONNECTED, BluetoothHeadset.RESULT_SUCCESS); mBtHandsfree.connectHeadset(mHeadset, mHeadsetType); // Make sure that old outgoing connect thread is dead. if (mConnectThread != null) { try { // TODO: Don't block in the main thread Log.w(TAG, "Block in main thread to join stale outgoing connection thread"); mConnectThread.join(); } catch (InterruptedException e) { Log.e(TAG, "Connection cancelled twice eh?", e); } mConnectThread = null; } if (DBG) log("Successfully used incoming connection, and cancelled outgoing " + " connection"); break; case BluetoothHeadset.STATE_CONNECTED: Log.i(TAG, "Already connected to " + mRemoteDevice + ", disconnecting " + info.mRemoteDevice); headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice, info.mSocketFd, info.mRfcommChan, null); headset.disconnect(); break; } }"
Inversion-Mutation
megadiff
"@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
"protected void prepareDesign( ) { ReportRunnable runnable = executionContext.getRunnable( ); if( !runnable.prepared) { ReportDesignHandle reportDesign = executionContext.getDesign( ); ScriptedDesignSearcher searcher = new ScriptedDesignSearcher( reportDesign ); searcher.apply( reportDesign ); boolean hasOnprepare = searcher.hasOnPrepareScript( ); if ( hasOnprepare) { ReportRunnable newRunnable = executionContext.getRunnable( ) .cloneRunnable( ); executionContext.updateRunnable( newRunnable ); ReportDesignHandle newDesign = newRunnable.designHandle; ScriptedDesignVisitor visitor = new ScriptedDesignHandler( newDesign, executionContext ); visitor.apply( newDesign.getRoot( ) ); newRunnable.setPrepared( true ); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "prepareDesign"
"protected void prepareDesign( ) { ReportRunnable runnable = executionContext.getRunnable( ); if( !runnable.prepared) { ReportDesignHandle reportDesign = executionContext.getDesign( ); ScriptedDesignSearcher searcher = new ScriptedDesignSearcher( reportDesign ); searcher.apply( reportDesign ); boolean hasOnprepare = searcher.hasOnPrepareScript( ); if ( hasOnprepare) { ReportRunnable newRunnable = executionContext.getRunnable( ) .cloneRunnable( ); ReportDesignHandle newDesign = newRunnable.designHandle; ScriptedDesignVisitor visitor = new ScriptedDesignHandler( newDesign, executionContext ); visitor.apply( newDesign.getRoot( ) ); newRunnable.setPrepared( true ); <MASK>executionContext.updateRunnable( newRunnable );</MASK> } } }"
Inversion-Mutation
megadiff
"private Map<String, Map<String, Cell>> generateCellMap(int count, Filter filter, Pattern testStatusRegex, int testStatusGroup, int logLinesToSearch) { assert count > 0 : "Must request more than 0 rows"; assert filter != null : "Filter must not be null"; assert testStatusGroup >= 0 : "testStatusGroup should be greater than or equal to 0"; assert logLinesToSearch >= 0 : "logLinesToSearch should be greater than or equal to 0"; Map<String, Map<String, Cell>> cellMap = new HashMap<String, Map<String, Cell>>(); Map<String, Project> projects = ProjectUtils.findProjects(); for (Header jobHeader : jobs) { int i = 0; String jobName = jobHeader.getName(); Project project = projects.get(jobName); Run currentBuild = project.getLastBuild(); while(currentBuild != null) { String description = currentBuild.getDescription(); if(description != null) { if(descriptionPatternRegex == null) { descriptionPatternRegex = Pattern.compile(descriptionPattern); } Matcher matcher = descriptionPatternRegex.matcher(description); if(matcher.find()) { String rowID = matcher.group(descriptionPatternGroup); Cell cell = Cell.createFromBuild(currentBuild, jobHeader.getVisible(), testStatusRegex, testStatusGroup, logLinesToSearch, maxAge); if(filter.matches(cell)) { if(!cellMap.containsKey(rowID)) { cellMap.put(rowID, new HashMap<String, Cell>()); } Map<String, Cell> cells = cellMap.get(rowID); Cell oldCell = cells.get(jobName); if(oldCell == null || oldCell.getDate().before(cell.getDate())) { cells.put(jobName, cell); } i++; } } } currentBuild = currentBuild.getPreviousBuild(); if(i >= count) { break; } } } return cellMap; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "generateCellMap"
"private Map<String, Map<String, Cell>> generateCellMap(int count, Filter filter, Pattern testStatusRegex, int testStatusGroup, int logLinesToSearch) { assert count > 0 : "Must request more than 0 rows"; assert filter != null : "Filter must not be null"; assert testStatusGroup >= 0 : "testStatusGroup should be greater than or equal to 0"; assert logLinesToSearch >= 0 : "logLinesToSearch should be greater than or equal to 0"; Map<String, Map<String, Cell>> cellMap = new HashMap<String, Map<String, Cell>>(); Map<String, Project> projects = ProjectUtils.findProjects(); <MASK>int i = 0;</MASK> for (Header jobHeader : jobs) { String jobName = jobHeader.getName(); Project project = projects.get(jobName); Run currentBuild = project.getLastBuild(); while(currentBuild != null) { String description = currentBuild.getDescription(); if(description != null) { if(descriptionPatternRegex == null) { descriptionPatternRegex = Pattern.compile(descriptionPattern); } Matcher matcher = descriptionPatternRegex.matcher(description); if(matcher.find()) { String rowID = matcher.group(descriptionPatternGroup); Cell cell = Cell.createFromBuild(currentBuild, jobHeader.getVisible(), testStatusRegex, testStatusGroup, logLinesToSearch, maxAge); if(filter.matches(cell)) { if(!cellMap.containsKey(rowID)) { cellMap.put(rowID, new HashMap<String, Cell>()); } Map<String, Cell> cells = cellMap.get(rowID); Cell oldCell = cells.get(jobName); if(oldCell == null || oldCell.getDate().before(cell.getDate())) { cells.put(jobName, cell); } i++; } } } currentBuild = currentBuild.getPreviousBuild(); if(i >= count) { break; } } } return cellMap; }"
Inversion-Mutation
megadiff
"@Override public void run() { Thread thisThread = Thread.currentThread(); while (curThread == thisThread) { List<WebURL> part = collectionHandler.getNextPart(this); ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); for (WebURL url : part) { executor.submit(new PageProcessingTask(new Page(url), collectionHandler)); } try { executor.shutdown(); executor.awaitTermination(20, TimeUnit.MINUTES); } catch (InterruptedException e) { stop(); 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() { Thread thisThread = Thread.currentThread(); <MASK>ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE);</MASK> while (curThread == thisThread) { List<WebURL> part = collectionHandler.getNextPart(this); for (WebURL url : part) { executor.submit(new PageProcessingTask(new Page(url), collectionHandler)); } try { executor.shutdown(); executor.awaitTermination(20, TimeUnit.MINUTES); } catch (InterruptedException e) { stop(); e.printStackTrace(); } } }"
Inversion-Mutation
megadiff
"public void startGameLoop() { Runnable gR = new Runnable() { //Proof of concept variables int shotCount = 0; boolean thisFrameDrawn = false; //Testing FPS Only long startTime = 0; long endTime = 0; long timeCount = 0; int frameCount = 0; //Game Loop public void run() { while(gameLoop) { startTime = System.currentTimeMillis(); //IMPORTANT VARIABLE FOR RENDERER SYNCHRONIZATION thisFrameDrawn = false; //Handle touch events HandleTouchEvents(); //check victory conditions gameType.Update(); //gameType.getBot().getDrawableBot().moveByTouch(0.1f); gameType.getBot().getDrawableBot().move(); //gameType.getBot().getBotLayer().setRotationAngle(gameType.getBot().getDrawableBot().moveAngle-90); // Run Interpreter // ilvm.resume(30); //update players bot's gun if(gameType.getBot().getDrawableBot().isAlive) { gameType.getBot().getDrawableGun().update(); } //update all other bot's gun's for(int i = 0; i < gameType.getBots().length; i++) { if(gameType.getBots()[i].getDrawableBot().isAlive) { gameType.getBots()[i].getDrawableGun().update(); } } ilvm.resume(4); // //no? // if(shotCount >= 10) // { // if(gameType.getBot().getDrawableBot().isAlive) // { // gameType.getBot().getDrawableGun().fire(); // } // for(int i = 0; i < gameType.getBots().length; i++) // { // if(gameType.getBots()[i].getDrawableBot().isAlive) // { // gameType.getBots()[i].getDrawableGun().fire(); // } // } // numShotsFired++; // shotCount = 0; // } // shotCount++; //Collision Detection Updater collisionManager.update(); //Particle Emitter Updater particleEmitter.update(); //Camera Stuff gameRenderer.cameraX = gameType.getBot().getDrawableBot().parameters[0]; gameRenderer.cameraY = gameType.getBot().getDrawableBot().parameters[1]; // Add bots to the drawlist if they are alive for (int i = 0; i < gameType.getBots().length; i++) if(gameType.getBots()[i].getDrawableBot().isAlive) addToDrawList(gameType.getBots()[i]); // Add the player to the drawlist if he is alive. if (gameType.getBot().getDrawableBot().isAlive) addToDrawList(gameType.getBot()); //Renderer Synchronization / Draw Frame Request while (!thisFrameDrawn && gameLoop) { if(gameRenderer.getFrameDrawn()) { gameRenderer.drawListSize = drawListPointer; for(int i=0;i<2;i++) for(int j=0;j<drawListPointer;j++) gameRenderer.drawList[i][j] = drawList[i][j]; //gameRenderer.setFrameDrawn(false); gameRenderer.frameDrawn = false; glSurfaceView.requestRender(); thisFrameDrawn = true; drawListPointer = 0; } // If we're waiting on the gameRenderer, should the thread pause // to let other stuff happen? // try {Thread.sleep(1);} // catch (InterruptedException e) {} } // Count up the number of frames and every second print that number // out and reset the count. endTime = System.currentTimeMillis(); timeCount += (endTime-startTime); frameCount++; if(timeCount >= 1000.0) { Log.v("bitbot", "FPS: " + frameCount); frameCount = 0; timeCount = 0; } } } }; Thread gT = new Thread(gR); gT.setName("Game Thread: " + gT.getName()); gT.start(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "startGameLoop"
"public void startGameLoop() { Runnable gR = new Runnable() { //Proof of concept variables int shotCount = 0; boolean thisFrameDrawn = false; //Testing FPS Only long startTime = 0; long endTime = 0; long timeCount = 0; int frameCount = 0; //Game Loop public void run() { while(gameLoop) { startTime = System.currentTimeMillis(); //IMPORTANT VARIABLE FOR RENDERER SYNCHRONIZATION thisFrameDrawn = false; //Handle touch events HandleTouchEvents(); //check victory conditions gameType.Update(); //gameType.getBot().getDrawableBot().moveByTouch(0.1f); gameType.getBot().getDrawableBot().move(); //gameType.getBot().getBotLayer().setRotationAngle(gameType.getBot().getDrawableBot().moveAngle-90); // Run Interpreter // ilvm.resume(30); <MASK>ilvm.resume(4);</MASK> //update players bot's gun if(gameType.getBot().getDrawableBot().isAlive) { gameType.getBot().getDrawableGun().update(); } //update all other bot's gun's for(int i = 0; i < gameType.getBots().length; i++) { if(gameType.getBots()[i].getDrawableBot().isAlive) { gameType.getBots()[i].getDrawableGun().update(); } } // //no? // if(shotCount >= 10) // { // if(gameType.getBot().getDrawableBot().isAlive) // { // gameType.getBot().getDrawableGun().fire(); // } // for(int i = 0; i < gameType.getBots().length; i++) // { // if(gameType.getBots()[i].getDrawableBot().isAlive) // { // gameType.getBots()[i].getDrawableGun().fire(); // } // } // numShotsFired++; // shotCount = 0; // } // shotCount++; //Collision Detection Updater collisionManager.update(); //Particle Emitter Updater particleEmitter.update(); //Camera Stuff gameRenderer.cameraX = gameType.getBot().getDrawableBot().parameters[0]; gameRenderer.cameraY = gameType.getBot().getDrawableBot().parameters[1]; // Add bots to the drawlist if they are alive for (int i = 0; i < gameType.getBots().length; i++) if(gameType.getBots()[i].getDrawableBot().isAlive) addToDrawList(gameType.getBots()[i]); // Add the player to the drawlist if he is alive. if (gameType.getBot().getDrawableBot().isAlive) addToDrawList(gameType.getBot()); //Renderer Synchronization / Draw Frame Request while (!thisFrameDrawn && gameLoop) { if(gameRenderer.getFrameDrawn()) { gameRenderer.drawListSize = drawListPointer; for(int i=0;i<2;i++) for(int j=0;j<drawListPointer;j++) gameRenderer.drawList[i][j] = drawList[i][j]; //gameRenderer.setFrameDrawn(false); gameRenderer.frameDrawn = false; glSurfaceView.requestRender(); thisFrameDrawn = true; drawListPointer = 0; } // If we're waiting on the gameRenderer, should the thread pause // to let other stuff happen? // try {Thread.sleep(1);} // catch (InterruptedException e) {} } // Count up the number of frames and every second print that number // out and reset the count. endTime = System.currentTimeMillis(); timeCount += (endTime-startTime); frameCount++; if(timeCount >= 1000.0) { Log.v("bitbot", "FPS: " + frameCount); frameCount = 0; timeCount = 0; } } } }; Thread gT = new Thread(gR); gT.setName("Game Thread: " + gT.getName()); gT.start(); }"
Inversion-Mutation
megadiff
"public void run() { while(gameLoop) { startTime = System.currentTimeMillis(); //IMPORTANT VARIABLE FOR RENDERER SYNCHRONIZATION thisFrameDrawn = false; //Handle touch events HandleTouchEvents(); //check victory conditions gameType.Update(); //gameType.getBot().getDrawableBot().moveByTouch(0.1f); gameType.getBot().getDrawableBot().move(); //gameType.getBot().getBotLayer().setRotationAngle(gameType.getBot().getDrawableBot().moveAngle-90); // Run Interpreter // ilvm.resume(30); //update players bot's gun if(gameType.getBot().getDrawableBot().isAlive) { gameType.getBot().getDrawableGun().update(); } //update all other bot's gun's for(int i = 0; i < gameType.getBots().length; i++) { if(gameType.getBots()[i].getDrawableBot().isAlive) { gameType.getBots()[i].getDrawableGun().update(); } } ilvm.resume(4); // //no? // if(shotCount >= 10) // { // if(gameType.getBot().getDrawableBot().isAlive) // { // gameType.getBot().getDrawableGun().fire(); // } // for(int i = 0; i < gameType.getBots().length; i++) // { // if(gameType.getBots()[i].getDrawableBot().isAlive) // { // gameType.getBots()[i].getDrawableGun().fire(); // } // } // numShotsFired++; // shotCount = 0; // } // shotCount++; //Collision Detection Updater collisionManager.update(); //Particle Emitter Updater particleEmitter.update(); //Camera Stuff gameRenderer.cameraX = gameType.getBot().getDrawableBot().parameters[0]; gameRenderer.cameraY = gameType.getBot().getDrawableBot().parameters[1]; // Add bots to the drawlist if they are alive for (int i = 0; i < gameType.getBots().length; i++) if(gameType.getBots()[i].getDrawableBot().isAlive) addToDrawList(gameType.getBots()[i]); // Add the player to the drawlist if he is alive. if (gameType.getBot().getDrawableBot().isAlive) addToDrawList(gameType.getBot()); //Renderer Synchronization / Draw Frame Request while (!thisFrameDrawn && gameLoop) { if(gameRenderer.getFrameDrawn()) { gameRenderer.drawListSize = drawListPointer; for(int i=0;i<2;i++) for(int j=0;j<drawListPointer;j++) gameRenderer.drawList[i][j] = drawList[i][j]; //gameRenderer.setFrameDrawn(false); gameRenderer.frameDrawn = false; glSurfaceView.requestRender(); thisFrameDrawn = true; drawListPointer = 0; } // If we're waiting on the gameRenderer, should the thread pause // to let other stuff happen? // try {Thread.sleep(1);} // catch (InterruptedException e) {} } // Count up the number of frames and every second print that number // out and reset the count. endTime = System.currentTimeMillis(); timeCount += (endTime-startTime); frameCount++; if(timeCount >= 1000.0) { Log.v("bitbot", "FPS: " + frameCount); frameCount = 0; timeCount = 0; } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"public void run() { while(gameLoop) { startTime = System.currentTimeMillis(); //IMPORTANT VARIABLE FOR RENDERER SYNCHRONIZATION thisFrameDrawn = false; //Handle touch events HandleTouchEvents(); //check victory conditions gameType.Update(); //gameType.getBot().getDrawableBot().moveByTouch(0.1f); gameType.getBot().getDrawableBot().move(); //gameType.getBot().getBotLayer().setRotationAngle(gameType.getBot().getDrawableBot().moveAngle-90); // Run Interpreter // ilvm.resume(30); <MASK>ilvm.resume(4);</MASK> //update players bot's gun if(gameType.getBot().getDrawableBot().isAlive) { gameType.getBot().getDrawableGun().update(); } //update all other bot's gun's for(int i = 0; i < gameType.getBots().length; i++) { if(gameType.getBots()[i].getDrawableBot().isAlive) { gameType.getBots()[i].getDrawableGun().update(); } } // //no? // if(shotCount >= 10) // { // if(gameType.getBot().getDrawableBot().isAlive) // { // gameType.getBot().getDrawableGun().fire(); // } // for(int i = 0; i < gameType.getBots().length; i++) // { // if(gameType.getBots()[i].getDrawableBot().isAlive) // { // gameType.getBots()[i].getDrawableGun().fire(); // } // } // numShotsFired++; // shotCount = 0; // } // shotCount++; //Collision Detection Updater collisionManager.update(); //Particle Emitter Updater particleEmitter.update(); //Camera Stuff gameRenderer.cameraX = gameType.getBot().getDrawableBot().parameters[0]; gameRenderer.cameraY = gameType.getBot().getDrawableBot().parameters[1]; // Add bots to the drawlist if they are alive for (int i = 0; i < gameType.getBots().length; i++) if(gameType.getBots()[i].getDrawableBot().isAlive) addToDrawList(gameType.getBots()[i]); // Add the player to the drawlist if he is alive. if (gameType.getBot().getDrawableBot().isAlive) addToDrawList(gameType.getBot()); //Renderer Synchronization / Draw Frame Request while (!thisFrameDrawn && gameLoop) { if(gameRenderer.getFrameDrawn()) { gameRenderer.drawListSize = drawListPointer; for(int i=0;i<2;i++) for(int j=0;j<drawListPointer;j++) gameRenderer.drawList[i][j] = drawList[i][j]; //gameRenderer.setFrameDrawn(false); gameRenderer.frameDrawn = false; glSurfaceView.requestRender(); thisFrameDrawn = true; drawListPointer = 0; } // If we're waiting on the gameRenderer, should the thread pause // to let other stuff happen? // try {Thread.sleep(1);} // catch (InterruptedException e) {} } // Count up the number of frames and every second print that number // out and reset the count. endTime = System.currentTimeMillis(); timeCount += (endTime-startTime); frameCount++; if(timeCount >= 1000.0) { Log.v("bitbot", "FPS: " + frameCount); frameCount = 0; timeCount = 0; } } }"
Inversion-Mutation
megadiff
"@Override public void visit(DexInstruction_BinaryOpWide instruction) { assert DexRegisterHelper.isPair(instruction.getRegSourceA1(), instruction.getRegSourceA2()); assert DexRegisterHelper.isPair(instruction.getRegSourceB1(), instruction.getRegSourceB2()); assert DexRegisterHelper.isPair(instruction.getRegTarget1(), instruction.getRegTarget2()); switch(instruction.getInsnOpcode()){ case AddDouble: case SubDouble: case MulDouble: case DivDouble: case RemDouble: useFreezedRegister(instruction.getRegSourceA1(), RopType.DoubleLo); useFreezedRegister(instruction.getRegSourceA2(), RopType.DoubleHi); useFreezedRegister(instruction.getRegSourceB1(), RopType.DoubleLo); useFreezedRegister(instruction.getRegSourceB2(), RopType.DoubleHi); defineFreezedRegister(instruction.getRegTarget1(), RopType.DoubleLo); defineFreezedRegister(instruction.getRegTarget2(), RopType.DoubleHi); break; case AddLong: case AndLong: case DivLong: case MulLong: case OrLong: case RemLong: case SubLong: case XorLong: useFreezedRegister(instruction.getRegSourceA1(), RopType.LongLo); useFreezedRegister(instruction.getRegSourceA2(), RopType.LongHi); useFreezedRegister(instruction.getRegSourceB1(), RopType.LongLo); useFreezedRegister(instruction.getRegSourceB2(), RopType.LongHi); defineFreezedRegister(instruction.getRegTarget1(), RopType.LongLo); defineFreezedRegister(instruction.getRegTarget2(), RopType.LongHi); break; case ShlLong: case ShrLong: case UshrLong: useFreezedRegister(instruction.getRegSourceA1(), RopType.LongLo); useFreezedRegister(instruction.getRegSourceA2(), RopType.LongHi); useFreezedRegister(instruction.getRegSourceB1(), RopType.Integer); defineFreezedRegister(instruction.getRegTarget1(), RopType.LongLo); defineFreezedRegister(instruction.getRegTarget2(), RopType.LongHi); break; default: throw new ValidationException("Unknown opcode for DexInstruction_BinaryOpWide"); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "visit"
"@Override public void visit(DexInstruction_BinaryOpWide instruction) { assert DexRegisterHelper.isPair(instruction.getRegSourceA1(), instruction.getRegSourceA2()); assert DexRegisterHelper.isPair(instruction.getRegSourceB1(), instruction.getRegSourceB2()); assert DexRegisterHelper.isPair(instruction.getRegTarget1(), instruction.getRegTarget2()); switch(instruction.getInsnOpcode()){ case AddDouble: case SubDouble: case MulDouble: case DivDouble: case RemDouble: useFreezedRegister(instruction.getRegSourceA1(), RopType.DoubleLo); useFreezedRegister(instruction.getRegSourceA2(), RopType.DoubleHi); useFreezedRegister(instruction.getRegSourceB1(), RopType.DoubleLo); useFreezedRegister(instruction.getRegSourceB2(), RopType.DoubleHi); defineFreezedRegister(instruction.getRegTarget1(), RopType.DoubleLo); defineFreezedRegister(instruction.getRegTarget2(), RopType.DoubleHi); break; case AddLong: case AndLong: case DivLong: case MulLong: case OrLong: case RemLong: case SubLong: <MASK>case UshrLong:</MASK> case XorLong: useFreezedRegister(instruction.getRegSourceA1(), RopType.LongLo); useFreezedRegister(instruction.getRegSourceA2(), RopType.LongHi); useFreezedRegister(instruction.getRegSourceB1(), RopType.LongLo); useFreezedRegister(instruction.getRegSourceB2(), RopType.LongHi); defineFreezedRegister(instruction.getRegTarget1(), RopType.LongLo); defineFreezedRegister(instruction.getRegTarget2(), RopType.LongHi); break; case ShlLong: case ShrLong: useFreezedRegister(instruction.getRegSourceA1(), RopType.LongLo); useFreezedRegister(instruction.getRegSourceA2(), RopType.LongHi); useFreezedRegister(instruction.getRegSourceB1(), RopType.Integer); defineFreezedRegister(instruction.getRegTarget1(), RopType.LongLo); defineFreezedRegister(instruction.getRegTarget2(), RopType.LongHi); break; default: throw new ValidationException("Unknown opcode for DexInstruction_BinaryOpWide"); } }"
Inversion-Mutation
megadiff
"private void updateBusinessAccountFromAccount(final Account account, final BusinessAccount bac) { final List<UUID> invoiceIds = new ArrayList<UUID>(); try { DateTime lastInvoiceDate = null; BigDecimal totalInvoiceBalance = BigDecimal.ZERO; String lastPaymentStatus = null; String paymentMethod = null; String creditCardType = null; String billingAddressCountry = null; // Retrieve invoices information final List<Invoice> invoices = invoiceUserApi.getInvoicesByAccount(account.getId()); if (invoices != null && invoices.size() > 0) { for (final Invoice invoice : invoices) { invoiceIds.add(invoice.getId()); totalInvoiceBalance = totalInvoiceBalance.add(invoice.getBalance()); if (lastInvoiceDate == null || invoice.getInvoiceDate().isAfter(lastInvoiceDate)) { lastInvoiceDate = invoice.getInvoiceDate(); } } // Retrieve payments information for these invoices DateTime lastPaymentDate = null; final List<PaymentInfoEvent> payments = paymentApi.getPaymentInfo(invoiceIds); if (payments != null) { for (final PaymentInfoEvent payment : payments) { // Use the last payment method/type/country as the default one for the account if (lastPaymentDate == null || payment.getCreatedDate().isAfter(lastPaymentDate)) { lastPaymentDate = payment.getCreatedDate(); lastPaymentStatus = payment.getStatus(); paymentMethod = payment.getPaymentMethod(); creditCardType = payment.getCardType(); billingAddressCountry = payment.getCardCountry(); } } } } // Retrieve payments information for these invoices final PaymentInfoEvent payment = paymentApi.getLastPaymentInfo(invoiceIds); if (payment != null) { lastPaymentStatus = payment.getStatus(); paymentMethod = payment.getPaymentMethod(); creditCardType = payment.getCardType(); billingAddressCountry = payment.getCardCountry(); } bac.setLastPaymentStatus(lastPaymentStatus); bac.setPaymentMethod(paymentMethod); bac.setCreditCardType(creditCardType); bac.setBillingAddressCountry(billingAddressCountry); bac.setLastInvoiceDate(lastInvoiceDate); bac.setTotalInvoiceBalance(totalInvoiceBalance); bac.setBalance(invoiceUserApi.getAccountBalance(account.getId())); } catch (PaymentApiException ex) { log.error(String.format("Failed to handle acount update for account %s", account.getId()), ex); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "updateBusinessAccountFromAccount"
"private void updateBusinessAccountFromAccount(final Account account, final BusinessAccount bac) { final List<UUID> invoiceIds = new ArrayList<UUID>(); try { DateTime lastInvoiceDate = null; BigDecimal totalInvoiceBalance = BigDecimal.ZERO; String lastPaymentStatus = null; String paymentMethod = null; String creditCardType = null; String billingAddressCountry = null; // Retrieve invoices information final List<Invoice> invoices = invoiceUserApi.getInvoicesByAccount(account.getId()); if (invoices != null && invoices.size() > 0) { for (final Invoice invoice : invoices) { invoiceIds.add(invoice.getId()); totalInvoiceBalance = totalInvoiceBalance.add(invoice.getBalance()); if (lastInvoiceDate == null || invoice.getInvoiceDate().isAfter(lastInvoiceDate)) { lastInvoiceDate = invoice.getInvoiceDate(); } } // Retrieve payments information for these invoices DateTime lastPaymentDate = null; final List<PaymentInfoEvent> payments = paymentApi.getPaymentInfo(invoiceIds); if (payments != null) { for (final PaymentInfoEvent payment : payments) { // Use the last payment method/type/country as the default one for the account if (lastPaymentDate == null || payment.getCreatedDate().isAfter(lastPaymentDate)) { lastPaymentDate = payment.getCreatedDate(); lastPaymentStatus = payment.getStatus(); paymentMethod = payment.getPaymentMethod(); creditCardType = payment.getCardType(); <MASK>billingAddressCountry = payment.getCardCountry();</MASK> } } } } // Retrieve payments information for these invoices final PaymentInfoEvent payment = paymentApi.getLastPaymentInfo(invoiceIds); if (payment != null) { lastPaymentStatus = payment.getStatus(); paymentMethod = payment.getPaymentMethod(); creditCardType = payment.getCardType(); } <MASK>billingAddressCountry = payment.getCardCountry();</MASK> bac.setLastPaymentStatus(lastPaymentStatus); bac.setPaymentMethod(paymentMethod); bac.setCreditCardType(creditCardType); bac.setBillingAddressCountry(billingAddressCountry); bac.setLastInvoiceDate(lastInvoiceDate); bac.setTotalInvoiceBalance(totalInvoiceBalance); bac.setBalance(invoiceUserApi.getAccountBalance(account.getId())); } catch (PaymentApiException ex) { log.error(String.format("Failed to handle acount update for account %s", account.getId()), ex); } }"
Inversion-Mutation
megadiff
"private void check(){ File[] files = _deployDir.listFiles(_fileFilter); // Checking for new deployment directories for (File file : files) { if (checkIsNew(new File(file, "deploy.xml"))) { try { DeploymentUnit du = new DeploymentUnit(file, _pxeServer); du.deploy(false); _inspectedFiles.put(file.getName(), du); __log.info("Deployment of artifact " + file.getName() + " successful."); } catch (Exception e) { __log.error("Deployment of " + file.getName() + " failed, aborting for now.", e); } } } // Removing deployments that disappeared HashSet<String> removed = new HashSet<String>(); for (String duName : _inspectedFiles.keySet()) { DeploymentUnit du = _inspectedFiles.get(duName); if (!du.exists()) { du.undeploy(); removed.add(duName); } } if (removed.size() > 0) { for (String duName : removed) { _inspectedFiles.remove(duName); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "check"
"private void check(){ File[] files = _deployDir.listFiles(_fileFilter); // Checking for new deployment directories for (File file : files) { if (checkIsNew(new File(file, "deploy.xml"))) { try { DeploymentUnit du = new DeploymentUnit(file, _pxeServer); <MASK>_inspectedFiles.put(file.getName(), du);</MASK> du.deploy(false); __log.info("Deployment of artifact " + file.getName() + " successful."); } catch (Exception e) { __log.error("Deployment of " + file.getName() + " failed, aborting for now.", e); } } } // Removing deployments that disappeared HashSet<String> removed = new HashSet<String>(); for (String duName : _inspectedFiles.keySet()) { DeploymentUnit du = _inspectedFiles.get(duName); if (!du.exists()) { du.undeploy(); removed.add(duName); } } if (removed.size() > 0) { for (String duName : removed) { _inspectedFiles.remove(duName); } } }"
Inversion-Mutation
megadiff
"public WorkspaceSubscriber() { // Add subscribers for all projects that have them RepositoryProviderManager.getInstance().addListener(this); IProject[] allProjects = ResourcesPlugin.getWorkspace().getRoot().getProjects(); for (int i = 0; i < allProjects.length; i++) { IProject project = allProjects[i]; if (RepositoryProvider.isShared(project)) { // TODO This will instantiate all providers RepositoryProvider provider = RepositoryProvider.getProvider(project); Subscriber subscriber = provider.getSubscriber(); if (subscriber != null) { subscriber.addListener(this); projects.put(project, subscriber); } } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "WorkspaceSubscriber"
"public WorkspaceSubscriber() { // Add subscribers for all projects that have them RepositoryProviderManager.getInstance().addListener(this); IProject[] allProjects = ResourcesPlugin.getWorkspace().getRoot().getProjects(); for (int i = 0; i < allProjects.length; i++) { IProject project = allProjects[i]; if (RepositoryProvider.isShared(project)) { // TODO This will instantiate all providers RepositoryProvider provider = RepositoryProvider.getProvider(project); Subscriber subscriber = provider.getSubscriber(); <MASK>subscriber.addListener(this);</MASK> if (subscriber != null) { projects.put(project, subscriber); } } } }"
Inversion-Mutation
megadiff
"public void onUpdate(final Song playing, final Song[] queued) { runOnUiThread(new Runnable() { public void run() { nowPlaying = playing; updateSongs(playing, queued); } }); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onUpdate"
"public void onUpdate(final Song playing, final Song[] queued) { <MASK>nowPlaying = playing;</MASK> runOnUiThread(new Runnable() { public void run() { updateSongs(playing, queued); } }); }"
Inversion-Mutation
megadiff
"@Override public void runCommand(CommandSender sender, List<String> args) { CommandSender target = sender; String name = "Console"; int pageNum = 0; List<String> list = new ArrayList<String>(); if (args.size() == 1) { try { pageNum = Integer.parseInt(args.get(0)); } catch (NumberFormatException e) { pageNum = 0; CommandSender test = plugin.getServer().getPlayer(args.get(0)); if (test != null) { target = test; name = test.getName(); } else { sender.sendMessage("No player named '" + args.get(0) + "' is online."); return; } } } else if (args.size() == 2) { try { CommandSender test = plugin.getServer().getPlayer(args.get(0)); if (test != null) { target = test; name = test.getName(); } else { sender.sendMessage("No player named '" + args.get(0) + "' is online."); return; } pageNum = Integer.parseInt(args.get(1)); } catch (NumberFormatException e) { pageNum = 0; } } if (!target.equals(sender) && !sender.hasPermission("privileges.list.other")) { sender.sendMessage(ChatColor.RED + "You do not have permission to view other peoples' nodes."); return; } List<PermissionAttachmentInfo> attInfo = new ArrayList<PermissionAttachmentInfo>(target.getEffectivePermissions()); Collections.sort(attInfo, new Comparator<PermissionAttachmentInfo>() { public int compare(PermissionAttachmentInfo a, PermissionAttachmentInfo b) { return a.getPermission().compareTo(b.getPermission()); } }); // thanks SpaceManiac! for (PermissionAttachmentInfo att : attInfo) { String node = att.getPermission(); StringBuilder msg = new StringBuilder(); msg.append("&B").append(node).append("&A - &B").append(att.getValue()).append("&A "); msg.append("&A(").append(att.getAttachment() != null ? "set: &6" + att.getAttachment().getPlugin().getDescription().getName() + "&A" : "&3default&A").append(")"); list.add(ChatColor.translateAlternateColorCodes('&', msg.toString())); } FancyPage page = new FancyPage(list); String header; if (sender instanceof ConsoleCommandSender) { header = ChatColor.GREEN + "=== " + ChatColor.WHITE + "Permissions list for " + ChatColor.AQUA + name + ChatColor.GREEN + " ==="; sender.sendMessage(ChatColor.translateAlternateColorCodes('&', header)); for (String line : list) { sender.sendMessage(ChatColor.stripColor(line)); } } else { header = ChatColor.GREEN + "=== " + ChatColor.WHITE + " [Page " + pageNum + "/" + page.getPages() + "] " + ChatColor.GREEN + "==="; sender.sendMessage(ChatColor.translateAlternateColorCodes('&', header)); for (String line : page.getPage(pageNum)) { sender.sendMessage(line); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "runCommand"
"@Override public void runCommand(CommandSender sender, List<String> args) { CommandSender target = sender; String name = "Console"; int pageNum = 0; List<String> list = new ArrayList<String>(); if (args.size() == 1) { try { pageNum = Integer.parseInt(args.get(0)); } catch (NumberFormatException e) { pageNum = 0; CommandSender test = plugin.getServer().getPlayer(args.get(0)); if (test != null) { target = test; name = test.getName(); } else { sender.sendMessage("No player named '" + args.get(0) + "' is online."); return; } } } else if (args.size() == 2) { try { <MASK>pageNum = Integer.parseInt(args.get(1));</MASK> CommandSender test = plugin.getServer().getPlayer(args.get(0)); if (test != null) { target = test; name = test.getName(); } else { sender.sendMessage("No player named '" + args.get(0) + "' is online."); return; } } catch (NumberFormatException e) { pageNum = 0; } } if (!target.equals(sender) && !sender.hasPermission("privileges.list.other")) { sender.sendMessage(ChatColor.RED + "You do not have permission to view other peoples' nodes."); return; } List<PermissionAttachmentInfo> attInfo = new ArrayList<PermissionAttachmentInfo>(target.getEffectivePermissions()); Collections.sort(attInfo, new Comparator<PermissionAttachmentInfo>() { public int compare(PermissionAttachmentInfo a, PermissionAttachmentInfo b) { return a.getPermission().compareTo(b.getPermission()); } }); // thanks SpaceManiac! for (PermissionAttachmentInfo att : attInfo) { String node = att.getPermission(); StringBuilder msg = new StringBuilder(); msg.append("&B").append(node).append("&A - &B").append(att.getValue()).append("&A "); msg.append("&A(").append(att.getAttachment() != null ? "set: &6" + att.getAttachment().getPlugin().getDescription().getName() + "&A" : "&3default&A").append(")"); list.add(ChatColor.translateAlternateColorCodes('&', msg.toString())); } FancyPage page = new FancyPage(list); String header; if (sender instanceof ConsoleCommandSender) { header = ChatColor.GREEN + "=== " + ChatColor.WHITE + "Permissions list for " + ChatColor.AQUA + name + ChatColor.GREEN + " ==="; sender.sendMessage(ChatColor.translateAlternateColorCodes('&', header)); for (String line : list) { sender.sendMessage(ChatColor.stripColor(line)); } } else { header = ChatColor.GREEN + "=== " + ChatColor.WHITE + " [Page " + pageNum + "/" + page.getPages() + "] " + ChatColor.GREEN + "==="; sender.sendMessage(ChatColor.translateAlternateColorCodes('&', header)); for (String line : page.getPage(pageNum)) { sender.sendMessage(line); } } }"
Inversion-Mutation
megadiff
"public boolean hasSideEffects() { switch (type) { case Token.EXPR_VOID: case Token.COMMA: if (last != null) return last.hasSideEffects(); else return true; case Token.HOOK: if (first == null || first.next == null || first.next.next == null) Kit.codeBug(); return first.next.hasSideEffects() && first.next.next.hasSideEffects(); case Token.ERROR: // Avoid cascaded error messages case Token.EXPR_RESULT: case Token.ASSIGN: case Token.ASSIGN_ADD: case Token.ASSIGN_SUB: case Token.ASSIGN_MUL: case Token.ASSIGN_DIV: case Token.ASSIGN_MOD: case Token.ASSIGN_BITOR: case Token.ASSIGN_BITXOR: case Token.ASSIGN_BITAND: case Token.ASSIGN_LSH: case Token.ASSIGN_RSH: case Token.ASSIGN_URSH: case Token.ENTERWITH: case Token.LEAVEWITH: case Token.RETURN: case Token.GOTO: case Token.IFEQ: case Token.IFNE: case Token.NEW: case Token.DELPROP: case Token.SETNAME: case Token.SETPROP: case Token.SETELEM: case Token.CALL: case Token.THROW: case Token.RETHROW: case Token.SETVAR: case Token.CATCH_SCOPE: case Token.RETURN_RESULT: case Token.SET_REF: case Token.DEL_REF: case Token.REF_CALL: case Token.TRY: case Token.SEMI: case Token.INC: case Token.DEC: case Token.EXPORT: case Token.IMPORT: case Token.IF: case Token.ELSE: case Token.SWITCH: case Token.WHILE: case Token.DO: case Token.FOR: case Token.BREAK: case Token.CONTINUE: case Token.VAR: case Token.CONST: case Token.WITH: case Token.CATCH: case Token.FINALLY: case Token.BLOCK: case Token.LABEL: case Token.TARGET: case Token.LOOP: case Token.JSR: case Token.SETPROP_OP: case Token.SETELEM_OP: case Token.LOCAL_BLOCK: case Token.SET_REF_OP: case Token.YIELD: return true; default: return false; } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "hasSideEffects"
"public boolean hasSideEffects() { switch (type) { case Token.EXPR_VOID: <MASK>case Token.EXPR_RESULT:</MASK> case Token.COMMA: if (last != null) return last.hasSideEffects(); else return true; case Token.HOOK: if (first == null || first.next == null || first.next.next == null) Kit.codeBug(); return first.next.hasSideEffects() && first.next.next.hasSideEffects(); case Token.ERROR: // Avoid cascaded error messages case Token.ASSIGN: case Token.ASSIGN_ADD: case Token.ASSIGN_SUB: case Token.ASSIGN_MUL: case Token.ASSIGN_DIV: case Token.ASSIGN_MOD: case Token.ASSIGN_BITOR: case Token.ASSIGN_BITXOR: case Token.ASSIGN_BITAND: case Token.ASSIGN_LSH: case Token.ASSIGN_RSH: case Token.ASSIGN_URSH: case Token.ENTERWITH: case Token.LEAVEWITH: case Token.RETURN: case Token.GOTO: case Token.IFEQ: case Token.IFNE: case Token.NEW: case Token.DELPROP: case Token.SETNAME: case Token.SETPROP: case Token.SETELEM: case Token.CALL: case Token.THROW: case Token.RETHROW: case Token.SETVAR: case Token.CATCH_SCOPE: case Token.RETURN_RESULT: case Token.SET_REF: case Token.DEL_REF: case Token.REF_CALL: case Token.TRY: case Token.SEMI: case Token.INC: case Token.DEC: case Token.EXPORT: case Token.IMPORT: case Token.IF: case Token.ELSE: case Token.SWITCH: case Token.WHILE: case Token.DO: case Token.FOR: case Token.BREAK: case Token.CONTINUE: case Token.VAR: case Token.CONST: case Token.WITH: case Token.CATCH: case Token.FINALLY: case Token.BLOCK: case Token.LABEL: case Token.TARGET: case Token.LOOP: case Token.JSR: case Token.SETPROP_OP: case Token.SETELEM_OP: case Token.LOCAL_BLOCK: case Token.SET_REF_OP: case Token.YIELD: return true; default: return false; } }"
Inversion-Mutation
megadiff
"public FragmentActionResult markPaperRecordRequestAsSent(@RequestParam(value = "identifier", required = true) String identifier, @SpringBean("paperRecordService") PaperRecordService paperRecordService, UiUtils ui) { try { // fetch the pending request associated with this message PaperRecordRequest paperRecordRequest = paperRecordService.getPendingPaperRecordRequestByIdentifier(identifier); if (paperRecordRequest == null) { // if matching request found, determine what error we need to return paperRecordRequest = paperRecordService.getSentPaperRecordRequestByIdentifier(identifier); if (paperRecordRequest == null) { return new FailureResult(ui.message("emr.archivesRoom.error.paperRecordNotRequested", ui.format(identifier))); } else { return new FailureResult(ui.message("emr.archivesRoom.error.paperRecordAlreadySent", ui.format(identifier), ui.format(paperRecordRequest.getRequestLocation()), ui.format(paperRecordRequest.getDateStatusChanged()))); } } else { // otherwise, mark the record as sent paperRecordService.markPaperRecordRequestAsSent(paperRecordRequest); return new SuccessResult(ui.message("emr.archivesRoom.recordFound.message") + "<br/><br/>" + ui.message("emr.archivesRoom.requestedBy.label") + ": " +"<span class=\"toast-record-location\">" + ui.format(paperRecordRequest.getRequestLocation() + "</span>" + ui.message("emr.archivesRoom.recordNumber.label") + ": " + "<span class=\"toast-record-id\">" + ui.format(identifier) + "</span>" + ui.message("emr.archivesRoom.requestedAt.label") + ": " + timeAndDateFormat.format(paperRecordRequest.getDateCreated()))); } } catch (Exception e) { // generic catch-all log.error(e); return new FailureResult(ui.message("emr.error.systemError")); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "markPaperRecordRequestAsSent"
"public FragmentActionResult markPaperRecordRequestAsSent(@RequestParam(value = "identifier", required = true) String identifier, @SpringBean("paperRecordService") PaperRecordService paperRecordService, UiUtils ui) { try { // fetch the pending request associated with this message PaperRecordRequest paperRecordRequest = paperRecordService.getPendingPaperRecordRequestByIdentifier(identifier); if (paperRecordRequest == null) { // if matching request found, determine what error we need to return paperRecordRequest = paperRecordService.getSentPaperRecordRequestByIdentifier(identifier); if (paperRecordRequest == null) { return new FailureResult(ui.message("emr.archivesRoom.error.paperRecordNotRequested", ui.format(identifier))); } else { return new FailureResult(ui.message("emr.archivesRoom.error.paperRecordAlreadySent", ui.format(identifier), ui.format(paperRecordRequest.getRequestLocation()), ui.format(paperRecordRequest.getDateStatusChanged()))); } } else { // otherwise, mark the record as sent paperRecordService.markPaperRecordRequestAsSent(paperRecordRequest); return new SuccessResult(ui.message("emr.archivesRoom.recordFound.message") + "<br/><br/>" <MASK>+ ui.message("emr.archivesRoom.recordNumber.label") + ": " + "<span class=\"toast-record-id\">" + ui.format(identifier) + "</span>"</MASK> + ui.message("emr.archivesRoom.requestedBy.label") + ": " +"<span class=\"toast-record-location\">" + ui.format(paperRecordRequest.getRequestLocation() + "</span>" + ui.message("emr.archivesRoom.requestedAt.label") + ": " + timeAndDateFormat.format(paperRecordRequest.getDateCreated()))); } } catch (Exception e) { // generic catch-all log.error(e); return new FailureResult(ui.message("emr.error.systemError")); } }"
Inversion-Mutation
megadiff
"public static MediaItem createMediaItemFromUri(Context context, Uri target, int mediaType) { MediaItem item = null; long id = ContentUris.parseId(target); ContentResolver cr = context.getContentResolver(); String whereClause = Images.ImageColumns._ID + "=" + Long.toString(id); try { final Uri uri = (mediaType == MediaItem.MEDIA_TYPE_IMAGE) ? Images.Media.EXTERNAL_CONTENT_URI : Video.Media.EXTERNAL_CONTENT_URI; final String[] projection = (mediaType == MediaItem.MEDIA_TYPE_IMAGE) ? CacheService.PROJECTION_IMAGES : CacheService.PROJECTION_VIDEOS; Cursor cursor = cr.query(uri, projection, whereClause, null, null); if (cursor != null) { if (cursor.moveToFirst()) { item = new MediaItem(); CacheService.populateMediaItemFromCursor(item, cr, cursor, uri.toString() + "/"); item.mId = id; } cursor.close(); cursor = null; } } catch (Exception e) { // If the database operation failed for any reason. ; } return item; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createMediaItemFromUri"
"public static MediaItem createMediaItemFromUri(Context context, Uri target, int mediaType) { MediaItem item = null; long id = ContentUris.parseId(target); ContentResolver cr = context.getContentResolver(); String whereClause = Images.ImageColumns._ID + "=" + Long.toString(id); try { final Uri uri = (mediaType == MediaItem.MEDIA_TYPE_IMAGE) ? Images.Media.EXTERNAL_CONTENT_URI : Video.Media.EXTERNAL_CONTENT_URI; final String[] projection = (mediaType == MediaItem.MEDIA_TYPE_IMAGE) ? CacheService.PROJECTION_IMAGES : CacheService.PROJECTION_VIDEOS; Cursor cursor = cr.query(uri, projection, whereClause, null, null); if (cursor != null) { if (cursor.moveToFirst()) { item = new MediaItem(); CacheService.populateMediaItemFromCursor(item, cr, cursor, uri.toString() + "/"); } cursor.close(); cursor = null; } } catch (Exception e) { // If the database operation failed for any reason. ; } <MASK>item.mId = id;</MASK> return item; }"
Inversion-Mutation
megadiff
"public PageFormat getPageFormat(int pageIndex) throws IndexOutOfBoundsException { try { if (pageIndex >= getNumberOfPages()) { return null; } PageFormat pageFormat = new PageFormat(); Paper paper = new Paper(); Rectangle2D dim = getPageViewport(pageIndex).getViewArea(); double width = dim.getWidth(); double height = dim.getHeight(); // if the width is greater than the height assume lanscape mode // and swap the width and height values in the paper format if (width > height) { paper.setImageableArea(0, 0, height / 1000d, width / 1000d); paper.setSize(height / 1000d, width / 1000d); pageFormat.setOrientation(PageFormat.LANDSCAPE); } else { paper.setImageableArea(0, 0, width / 1000d, height / 1000d); paper.setSize(width / 1000d, height / 1000d); pageFormat.setOrientation(PageFormat.PORTRAIT); } pageFormat.setPaper(paper); return pageFormat; } catch (FOPException fopEx) { throw new IndexOutOfBoundsException(fopEx.getMessage()); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getPageFormat"
"public PageFormat getPageFormat(int pageIndex) throws IndexOutOfBoundsException { try { if (pageIndex >= getNumberOfPages()) { return null; } PageFormat pageFormat = new PageFormat(); Paper paper = new Paper(); <MASK>pageFormat.setPaper(paper);</MASK> Rectangle2D dim = getPageViewport(pageIndex).getViewArea(); double width = dim.getWidth(); double height = dim.getHeight(); // if the width is greater than the height assume lanscape mode // and swap the width and height values in the paper format if (width > height) { paper.setImageableArea(0, 0, height / 1000d, width / 1000d); paper.setSize(height / 1000d, width / 1000d); pageFormat.setOrientation(PageFormat.LANDSCAPE); } else { paper.setImageableArea(0, 0, width / 1000d, height / 1000d); paper.setSize(width / 1000d, height / 1000d); pageFormat.setOrientation(PageFormat.PORTRAIT); } return pageFormat; } catch (FOPException fopEx) { throw new IndexOutOfBoundsException(fopEx.getMessage()); } }"
Inversion-Mutation
megadiff
"public void performAnalysisInBackground() { synchronized (backgroundQueue) { if (!backgroundQueue.contains(this)) { backgroundQueue.add(this); if (backgroundJob == null) { backgroundJob = new BackgroundAnalysisJob(); backgroundJob.setPriority(Job.BUILD); } backgroundJob.schedule(); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "performAnalysisInBackground"
"public void performAnalysisInBackground() { synchronized (backgroundQueue) { if (!backgroundQueue.contains(this)) { backgroundQueue.add(this); if (backgroundJob == null) { backgroundJob = new BackgroundAnalysisJob(); backgroundJob.setPriority(Job.BUILD); <MASK>backgroundJob.schedule();</MASK> } } } }"
Inversion-Mutation
megadiff
"@Override protected void doCreateControl( TabbedPropertySheetWidgetFactory widgetFactory) { super.doCreateControl(widgetFactory); browse = widgetFactory.createButton(composite, Messages.Browse, SWT.FLAT); browse.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { super.widgetSelected(e); final AbstractProcess parentProcess = ModelHelper.getParentProcess(widget); if(parentProcess != null){ SelectFileStoreWizard selectImageFileStorWizard = new SelectFileStoreWizard(editingDomain, parentProcess, ((ImageWidget) widget).getImgPath().getContent()); WizardDialog wd = new WizardDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), selectImageFileStorWizard); if(wd.open() == IDialogConstants.OK_ID){ Expression expression = (Expression) ((IStructuredSelection) expressionViewer.getSelection()).getFirstElement(); if(expression != null){ CompoundCommand cc = new CompoundCommand(); cc.append(SetCommand.create(editingDomain, expression, ExpressionPackage.Literals.EXPRESSION__CONTENT, selectImageFileStorWizard.getSelectedFilePath())); cc.append(SetCommand.create(editingDomain, expression, ExpressionPackage.Literals.EXPRESSION__NAME, selectImageFileStorWizard.getSelectedFilePath())); cc.append(SetCommand.create(editingDomain, expression, ExpressionPackage.Literals.EXPRESSION__TYPE, ExpressionConstants.CONSTANT_TYPE)); cc.append(SetCommand.create(editingDomain, expression, ExpressionPackage.Literals.EXPRESSION__RETURN_TYPE, String.class.getName())); editingDomain.getCommandStack().execute(cc); } else { expression = ExpressionFactory.eINSTANCE.createExpression(); expression.setContent(selectImageFileStorWizard.getSelectedFilePath()); expression.setName(selectImageFileStorWizard.getSelectedFilePath()); expression.setReturnType(String.class.getName()); expression.setType(ExpressionConstants.CONSTANT_TYPE); } expressionViewer.setSelection(new StructuredSelection(expression)); } } } }); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doCreateControl"
"@Override protected void doCreateControl( TabbedPropertySheetWidgetFactory widgetFactory) { super.doCreateControl(widgetFactory); browse = widgetFactory.createButton(composite, Messages.Browse, SWT.FLAT); browse.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { super.widgetSelected(e); final AbstractProcess parentProcess = ModelHelper.getParentProcess(widget); if(parentProcess != null){ SelectFileStoreWizard selectImageFileStorWizard = new SelectFileStoreWizard(editingDomain, parentProcess, ((ImageWidget) widget).getImgPath().getContent()); WizardDialog wd = new WizardDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), selectImageFileStorWizard); if(wd.open() == IDialogConstants.OK_ID){ Expression expression = (Expression) ((IStructuredSelection) expressionViewer.getSelection()).getFirstElement(); if(expression != null){ CompoundCommand cc = new CompoundCommand(); cc.append(SetCommand.create(editingDomain, expression, ExpressionPackage.Literals.EXPRESSION__CONTENT, selectImageFileStorWizard.getSelectedFilePath())); cc.append(SetCommand.create(editingDomain, expression, ExpressionPackage.Literals.EXPRESSION__NAME, selectImageFileStorWizard.getSelectedFilePath())); cc.append(SetCommand.create(editingDomain, expression, ExpressionPackage.Literals.EXPRESSION__TYPE, ExpressionConstants.CONSTANT_TYPE)); cc.append(SetCommand.create(editingDomain, expression, ExpressionPackage.Literals.EXPRESSION__RETURN_TYPE, String.class.getName())); editingDomain.getCommandStack().execute(cc); } else { expression = ExpressionFactory.eINSTANCE.createExpression(); expression.setContent(selectImageFileStorWizard.getSelectedFilePath()); expression.setName(selectImageFileStorWizard.getSelectedFilePath()); expression.setReturnType(String.class.getName()); expression.setType(ExpressionConstants.CONSTANT_TYPE); <MASK>expressionViewer.setSelection(new StructuredSelection(expression));</MASK> } } } } }); }"
Inversion-Mutation
megadiff
"@Override public void widgetSelected(SelectionEvent e) { super.widgetSelected(e); final AbstractProcess parentProcess = ModelHelper.getParentProcess(widget); if(parentProcess != null){ SelectFileStoreWizard selectImageFileStorWizard = new SelectFileStoreWizard(editingDomain, parentProcess, ((ImageWidget) widget).getImgPath().getContent()); WizardDialog wd = new WizardDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), selectImageFileStorWizard); if(wd.open() == IDialogConstants.OK_ID){ Expression expression = (Expression) ((IStructuredSelection) expressionViewer.getSelection()).getFirstElement(); if(expression != null){ CompoundCommand cc = new CompoundCommand(); cc.append(SetCommand.create(editingDomain, expression, ExpressionPackage.Literals.EXPRESSION__CONTENT, selectImageFileStorWizard.getSelectedFilePath())); cc.append(SetCommand.create(editingDomain, expression, ExpressionPackage.Literals.EXPRESSION__NAME, selectImageFileStorWizard.getSelectedFilePath())); cc.append(SetCommand.create(editingDomain, expression, ExpressionPackage.Literals.EXPRESSION__TYPE, ExpressionConstants.CONSTANT_TYPE)); cc.append(SetCommand.create(editingDomain, expression, ExpressionPackage.Literals.EXPRESSION__RETURN_TYPE, String.class.getName())); editingDomain.getCommandStack().execute(cc); } else { expression = ExpressionFactory.eINSTANCE.createExpression(); expression.setContent(selectImageFileStorWizard.getSelectedFilePath()); expression.setName(selectImageFileStorWizard.getSelectedFilePath()); expression.setReturnType(String.class.getName()); expression.setType(ExpressionConstants.CONSTANT_TYPE); } expressionViewer.setSelection(new StructuredSelection(expression)); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "widgetSelected"
"@Override public void widgetSelected(SelectionEvent e) { super.widgetSelected(e); final AbstractProcess parentProcess = ModelHelper.getParentProcess(widget); if(parentProcess != null){ SelectFileStoreWizard selectImageFileStorWizard = new SelectFileStoreWizard(editingDomain, parentProcess, ((ImageWidget) widget).getImgPath().getContent()); WizardDialog wd = new WizardDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), selectImageFileStorWizard); if(wd.open() == IDialogConstants.OK_ID){ Expression expression = (Expression) ((IStructuredSelection) expressionViewer.getSelection()).getFirstElement(); if(expression != null){ CompoundCommand cc = new CompoundCommand(); cc.append(SetCommand.create(editingDomain, expression, ExpressionPackage.Literals.EXPRESSION__CONTENT, selectImageFileStorWizard.getSelectedFilePath())); cc.append(SetCommand.create(editingDomain, expression, ExpressionPackage.Literals.EXPRESSION__NAME, selectImageFileStorWizard.getSelectedFilePath())); cc.append(SetCommand.create(editingDomain, expression, ExpressionPackage.Literals.EXPRESSION__TYPE, ExpressionConstants.CONSTANT_TYPE)); cc.append(SetCommand.create(editingDomain, expression, ExpressionPackage.Literals.EXPRESSION__RETURN_TYPE, String.class.getName())); editingDomain.getCommandStack().execute(cc); } else { expression = ExpressionFactory.eINSTANCE.createExpression(); expression.setContent(selectImageFileStorWizard.getSelectedFilePath()); expression.setName(selectImageFileStorWizard.getSelectedFilePath()); expression.setReturnType(String.class.getName()); expression.setType(ExpressionConstants.CONSTANT_TYPE); <MASK>expressionViewer.setSelection(new StructuredSelection(expression));</MASK> } } } }"
Inversion-Mutation
megadiff
"public void assignInstanceVariable(String name) { // FIXME: more efficient with a callback loadSelf(); invokeIRubyObject("getInstanceVariables", cg.sig(InstanceVariables.class)); method.swap(); method.ldc(name); method.swap(); method.invokeinterface(cg.p(InstanceVariables.class), "fastSetInstanceVariable", cg.sig(IRubyObject.class, cg.params(String.class, IRubyObject.class))); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "assignInstanceVariable"
"public void assignInstanceVariable(String name) { // FIXME: more efficient with a callback loadSelf(); method.swap(); method.ldc(name); method.swap(); <MASK>invokeIRubyObject("getInstanceVariables", cg.sig(InstanceVariables.class));</MASK> method.invokeinterface(cg.p(InstanceVariables.class), "fastSetInstanceVariable", cg.sig(IRubyObject.class, cg.params(String.class, IRubyObject.class))); }"
Inversion-Mutation
megadiff
"private void startAsMaster() { this.broker = brokerFactory.create(); this.localGraph = new EmbeddedGraphDbImpl( storeDir, config, this, CommonFactories.defaultLockManagerFactory(), new MasterIdGeneratorFactory(), CommonFactories.defaultRelationshipTypeCreator(), CommonFactories.defaultTxIdGeneratorFactory(), CommonFactories.defaultTxRollbackHook(), new ZooKeeperLastCommittedTxIdSetter( broker ) ); this.masterServer = (MasterServer) broker.instantiateMasterServer( this ); instantiateIndexIfNeeded(); instantiateAutoUpdatePullerIfConfigSaysSo(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "startAsMaster"
"private void startAsMaster() { this.broker = brokerFactory.create(); <MASK>this.masterServer = (MasterServer) broker.instantiateMasterServer( this );</MASK> this.localGraph = new EmbeddedGraphDbImpl( storeDir, config, this, CommonFactories.defaultLockManagerFactory(), new MasterIdGeneratorFactory(), CommonFactories.defaultRelationshipTypeCreator(), CommonFactories.defaultTxIdGeneratorFactory(), CommonFactories.defaultTxRollbackHook(), new ZooKeeperLastCommittedTxIdSetter( broker ) ); instantiateIndexIfNeeded(); instantiateAutoUpdatePullerIfConfigSaysSo(); }"
Inversion-Mutation
megadiff
"public void noOneAnswered() { answerStateManager.setAnswerState(AnswerState.NOBODY_ANSWERED); priceManager.setPrice(priceManager.getPrice() + 1); gameStateManager.setGameState(GameState.FINISHED); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "noOneAnswered"
"public void noOneAnswered() { answerStateManager.setAnswerState(AnswerState.NOBODY_ANSWERED); <MASK>gameStateManager.setGameState(GameState.FINISHED);</MASK> priceManager.setPrice(priceManager.getPrice() + 1); }"
Inversion-Mutation
megadiff
"public TableRow createRow(LayoutInflater inflater, T device) { TableRow row = (TableRow) inflater.inflate(layoutId, null); SeekBar seekBar = (SeekBar) row.findViewById(R.id.seekBar); seekBar.setOnSeekBarChangeListener(createListener(device)); seekBar.setMax(maximumProgress); seekBar.setProgress(initialProgress); return row; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createRow"
"public TableRow createRow(LayoutInflater inflater, T device) { TableRow row = (TableRow) inflater.inflate(layoutId, null); SeekBar seekBar = (SeekBar) row.findViewById(R.id.seekBar); seekBar.setOnSeekBarChangeListener(createListener(device)); <MASK>seekBar.setProgress(initialProgress);</MASK> seekBar.setMax(maximumProgress); return row; }"
Inversion-Mutation
megadiff
"public boolean remove(TabBarButtonBase w) { int indexForWidget = getIndexForWidget(w); children.remove(w); if (indexForWidget != -1) { handlers.get(indexForWidget).removeHandler(); handlers.remove(indexForWidget); } return container.remove(w); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "remove"
"public boolean remove(TabBarButtonBase w) { <MASK>children.remove(w);</MASK> int indexForWidget = getIndexForWidget(w); if (indexForWidget != -1) { handlers.get(indexForWidget).removeHandler(); handlers.remove(indexForWidget); } return container.remove(w); }"
Inversion-Mutation
megadiff
"public void visitMethodInsn(int opcode, String owner, String name, String desc) { if (boxing(opcode,owner,name)) { boxingDesc = desc; dropBoxing(); } else { if (unboxing(opcode, owner, name)) { if (boxingDesc != null) boxingDesc = null; else super.visitMethodInsn(opcode, owner, name, desc); //To change body of overridden methods use File | Settings | File Templates. } else { dropBoxing(); super.visitMethodInsn(opcode, owner, name, desc); //To change body of overridden methods use File | Settings | File Templates. } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "visitMethodInsn"
"public void visitMethodInsn(int opcode, String owner, String name, String desc) { if (boxing(opcode,owner,name)) { <MASK>dropBoxing();</MASK> boxingDesc = desc; } else { if (unboxing(opcode, owner, name)) { if (boxingDesc != null) boxingDesc = null; else super.visitMethodInsn(opcode, owner, name, desc); //To change body of overridden methods use File | Settings | File Templates. } else { <MASK>dropBoxing();</MASK> super.visitMethodInsn(opcode, owner, name, desc); //To change body of overridden methods use File | Settings | File Templates. } } }"
Inversion-Mutation
megadiff
"private Bpmn2Resource unmarshall(JsonParser parser, String preProcessingData) throws JsonParseException, IOException { try { parser.nextToken(); // open the object ResourceSet rSet = new ResourceSetImpl(); rSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("bpmn2", new JBPMBpmn2ResourceFactoryImpl()); Bpmn2Resource bpmn2 = (Bpmn2Resource) rSet.createResource(URI.createURI("virtual.bpmn2")); rSet.getResources().add(bpmn2); _currentResource = bpmn2; // do the unmarshalling now: Definitions def = (Definitions) unmarshallItem(parser, preProcessingData); revisitServiceTasks(def); revisitMessages(def); revisitCatchEvents(def); revisitThrowEvents(def); revisitLanes(def); revisitArtifacts(def); revisitGroups(def); reviseTaskAssociations(def); reconnectFlows(); revisitGateways(def); revisitCatchEventsConvertToBoundary(def); createDiagram(def); // return def; _currentResource.getContents().add(def); return _currentResource; } finally { parser.close(); _objMap.clear(); _idMap.clear(); _outgoingFlows.clear(); _sequenceFlowTargets.clear(); _bounds.clear(); _currentResource = null; } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "unmarshall"
"private Bpmn2Resource unmarshall(JsonParser parser, String preProcessingData) throws JsonParseException, IOException { try { parser.nextToken(); // open the object ResourceSet rSet = new ResourceSetImpl(); rSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("bpmn2", new JBPMBpmn2ResourceFactoryImpl()); Bpmn2Resource bpmn2 = (Bpmn2Resource) rSet.createResource(URI.createURI("virtual.bpmn2")); rSet.getResources().add(bpmn2); _currentResource = bpmn2; // do the unmarshalling now: Definitions def = (Definitions) unmarshallItem(parser, preProcessingData); <MASK>revisitGateways(def);</MASK> revisitServiceTasks(def); revisitMessages(def); revisitCatchEvents(def); revisitThrowEvents(def); revisitLanes(def); revisitArtifacts(def); revisitGroups(def); reviseTaskAssociations(def); reconnectFlows(); revisitCatchEventsConvertToBoundary(def); createDiagram(def); // return def; _currentResource.getContents().add(def); return _currentResource; } finally { parser.close(); _objMap.clear(); _idMap.clear(); _outgoingFlows.clear(); _sequenceFlowTargets.clear(); _bounds.clear(); _currentResource = null; } }"
Inversion-Mutation
megadiff
"@Inject public Coordinator(RemoteSlotFactory remoteSlotFactory, CoordinatorConfig config) { Preconditions.checkNotNull(remoteSlotFactory, "remoteSlotFactory is null"); this.remoteSlotFactory = remoteSlotFactory; agents = new MapMaker() .expireAfterWrite((long) config.getStatusExpiration().toMillis(), TimeUnit.MILLISECONDS) .evictionListener(new MapEvictionListener<UUID, AgentStatus>() { @Override public void onEviction(UUID id, AgentStatus agentStatus) { slotsLock.writeLock().lock(); try { for (SlotStatus slotStatus : agentStatus.getSlots()) { slots.remove(slotStatus.getId()); } } finally { slotsLock.writeLock().unlock(); } } }) .makeMap(); slots = new MapMaker().makeMap(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "Coordinator"
"@Inject public Coordinator(RemoteSlotFactory remoteSlotFactory, CoordinatorConfig config) { Preconditions.checkNotNull(remoteSlotFactory, "remoteSlotFactory is null"); this.remoteSlotFactory = remoteSlotFactory; agents = new MapMaker() .expireAfterWrite((long) config.getStatusExpiration().toMillis(), TimeUnit.MILLISECONDS) .evictionListener(new MapEvictionListener<UUID, AgentStatus>() { @Override public void onEviction(UUID id, AgentStatus agentStatus) { try { <MASK>slotsLock.writeLock().lock();</MASK> for (SlotStatus slotStatus : agentStatus.getSlots()) { slots.remove(slotStatus.getId()); } } finally { slotsLock.writeLock().unlock(); } } }) .makeMap(); slots = new MapMaker().makeMap(); }"
Inversion-Mutation
megadiff
"@Override public void onEviction(UUID id, AgentStatus agentStatus) { slotsLock.writeLock().lock(); try { for (SlotStatus slotStatus : agentStatus.getSlots()) { slots.remove(slotStatus.getId()); } } finally { slotsLock.writeLock().unlock(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onEviction"
"@Override public void onEviction(UUID id, AgentStatus agentStatus) { try { <MASK>slotsLock.writeLock().lock();</MASK> for (SlotStatus slotStatus : agentStatus.getSlots()) { slots.remove(slotStatus.getId()); } } finally { slotsLock.writeLock().unlock(); } }"
Inversion-Mutation
megadiff
"private void runServer(int port, GameWorld game) { int uid = 0; // Listen for connections System.out.println("GAME SERVER LISTENING ON PORT " + port); try { game.addDeltaWatcher(new DeltaWatcher(){ @Override public void delta(final WorldDelta d) { toAllPlayers(new ClientMessenger() { @Override public void doTo(ServerThread client) { client.addDelta(d); } }); } }); // Now, we await connections. ServerSocket ss = new ServerSocket(port); while (true) { // Wait for a socket Socket s = ss.accept(); System.out.println("ACCEPTED CONNECTION FROM: " + s.getInetAddress()); final ServerThread newSer = new ServerThread(s,uid,game, this); // MaxZ's code: send initial state game.allDeltas(new DeltaWatcher(){ public void delta(WorldDelta d){ newSer.addDelta(d); } }); connections.add(newSer); newSer.start(); uid++;; //this will add players unique identifier in future. } } catch(IOException e) { System.err.println("I/O error: " + e.getMessage()); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "runServer"
"private void runServer(int port, GameWorld game) { int uid = 0; // Listen for connections System.out.println("GAME SERVER LISTENING ON PORT " + port); try { game.addDeltaWatcher(new DeltaWatcher(){ @Override public void delta(final WorldDelta d) { toAllPlayers(new ClientMessenger() { @Override public void doTo(ServerThread client) { client.addDelta(d); } }); } }); // Now, we await connections. ServerSocket ss = new ServerSocket(port); while (true) { // Wait for a socket Socket s = ss.accept(); System.out.println("ACCEPTED CONNECTION FROM: " + s.getInetAddress()); final ServerThread newSer = new ServerThread(s,uid,game, this); <MASK>connections.add(newSer);</MASK> // MaxZ's code: send initial state game.allDeltas(new DeltaWatcher(){ public void delta(WorldDelta d){ newSer.addDelta(d); } }); newSer.start(); uid++;; //this will add players unique identifier in future. } } catch(IOException e) { System.err.println("I/O error: " + e.getMessage()); } }"
Inversion-Mutation
megadiff
"public Gui_StreamRipStar(Boolean openPreferences) { super("StreamRipStar"); setIconImage( windowIcon.getImage() ); controlStreams = new Control_Stream(this); table = new Gui_TablePanel(controlStreams,this); addWindowListener(this); setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE ); Container contPane = getContentPane(); BorderLayout mainLayout = new BorderLayout(); contPane.setLayout(mainLayout); contPane.add(iconBar,BorderLayout.PAGE_START); contPane.add(table, BorderLayout.CENTER); //Add that shows all streams buildMenuBar(); setLanguage(); loadProp(); buildIconBar(); setSystemTray(); if(useInternalPlayer) { //load the audio panel audioPanel = new InternAudioControlPanel(this,volumeManager); contPane.add(this.audioPanel, BorderLayout.SOUTH); hearMusicButton.setEnabled(false); //and pre-load the audio system table.loadFirstAudioPlayer(); } //Center StreamRipStar //get size of window Dimension frameDim = getSize(); //get resolution Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize(); //calculates the app. values int x = (screenDim.width - frameDim.width)/2; int y = (screenDim.height - frameDim.height)/2; //set location setLocation(x, y); setVisible(true); //create object to control the next 2 Threads Control_Threads controlThreads = new Control_Threads(); // start filling the table with streams Thread_FillTableWithStreams fill = new Thread_FillTableWithStreams(controlStreams,table,controlThreads); fill.start(); //the schedul control is an thread -> start it controlJob = new Thread_Control_Schedul(this,controlThreads); controlJob.start(); //if preferences should open, do it here if(openPreferences) { JOptionPane.showMessageDialog(this, trans.getString("firstTime")); new Gui_Settings2(this); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "Gui_StreamRipStar"
"public Gui_StreamRipStar(Boolean openPreferences) { super("StreamRipStar"); setIconImage( windowIcon.getImage() ); controlStreams = new Control_Stream(this); table = new Gui_TablePanel(controlStreams,this); addWindowListener(this); setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE ); Container contPane = getContentPane(); BorderLayout mainLayout = new BorderLayout(); contPane.setLayout(mainLayout); contPane.add(iconBar,BorderLayout.PAGE_START); contPane.add(table, BorderLayout.CENTER); //Add that shows all streams buildMenuBar(); <MASK>buildIconBar();</MASK> setLanguage(); loadProp(); setSystemTray(); if(useInternalPlayer) { //load the audio panel audioPanel = new InternAudioControlPanel(this,volumeManager); contPane.add(this.audioPanel, BorderLayout.SOUTH); hearMusicButton.setEnabled(false); //and pre-load the audio system table.loadFirstAudioPlayer(); } //Center StreamRipStar //get size of window Dimension frameDim = getSize(); //get resolution Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize(); //calculates the app. values int x = (screenDim.width - frameDim.width)/2; int y = (screenDim.height - frameDim.height)/2; //set location setLocation(x, y); setVisible(true); //create object to control the next 2 Threads Control_Threads controlThreads = new Control_Threads(); // start filling the table with streams Thread_FillTableWithStreams fill = new Thread_FillTableWithStreams(controlStreams,table,controlThreads); fill.start(); //the schedul control is an thread -> start it controlJob = new Thread_Control_Schedul(this,controlThreads); controlJob.start(); //if preferences should open, do it here if(openPreferences) { JOptionPane.showMessageDialog(this, trans.getString("firstTime")); new Gui_Settings2(this); } }"
Inversion-Mutation
megadiff
"@Override public <E> void setProxyOwners(EntityMetadata entityMetadata, E e) { if (e != null && e.getClass().getAnnotation(Entity.class) != null && entityMetadata != null) { for (Relation r : entityMetadata.getRelations()) { Object entityId = PropertyAccessorHelper.getId(e, entityMetadata); if (r.isUnary()) { String entityName = entityMetadata.getEntityClazz().getName() + "_" + entityId + "#" + r.getProperty().getName(); KunderaProxy kunderaProxy = getProxy(entityName); if (kunderaProxy != null) { kunderaProxy.getKunderaLazyInitializer().setOwner(e); } } } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setProxyOwners"
"@Override public <E> void setProxyOwners(EntityMetadata entityMetadata, E e) { if (e != null && e.getClass().getAnnotation(Entity.class) != null && entityMetadata != null) { <MASK>Object entityId = PropertyAccessorHelper.getId(e, entityMetadata);</MASK> for (Relation r : entityMetadata.getRelations()) { if (r.isUnary()) { String entityName = entityMetadata.getEntityClazz().getName() + "_" + entityId + "#" + r.getProperty().getName(); KunderaProxy kunderaProxy = getProxy(entityName); if (kunderaProxy != null) { kunderaProxy.getKunderaLazyInitializer().setOwner(e); } } } } }"
Inversion-Mutation
megadiff
"@EventHandler(priority = EventPriority.LOW) public void onPlayerInteract(PlayerInteractEvent event) { Player player = event.getPlayer(); db.i("onPlayerInteract"); if (event.getAction().equals(Action.PHYSICAL)) { db.i("returning: physical"); return; } Arena arena = null; if (event.hasBlock()) { arena = ArenaManager.getArenaByRegionLocation(new PABlockLocation(event.getClickedBlock().getLocation())); } if (arena != null && PVPArena.instance.getAmm().onPlayerInteract(arena, event)) { db.i("returning: #1"); return; } if (PVPArena.instance.getAgm().checkSetFlag(player, event.getClickedBlock())) { db.i("returning: #2"); return; } if (ArenaRegionShape.checkRegionSetPosition(event, player)) { db.i("returning: #3"); return; } arena = ArenaPlayer.parsePlayer(player.getName()).getArena(); if (arena == null) { db.i("returning: #4"); ArenaManager.trySignJoin(event, player); return; } PVPArena.instance.getAgm().checkInteract(arena, player, event.getClickedBlock()); if (arena.isFightInProgress() && !PVPArena.instance.getAgm().allowsJoinInBattle(arena)) { db.i("exiting! fight in progress AND no INBATTLEJOIN arena!"); return; } ArenaPlayer ap = ArenaPlayer.parsePlayer(player.getName()); ArenaTeam team = ap.getArenaTeam(); if (!ap.getStatus().equals(Status.FIGHT)) { db.i("cancelling: no class"); // fighting player inside the lobby! event.setCancelled(true); } if (team == null) { db.i("returning: no team"); return; } if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)) { Block block = event.getClickedBlock(); db.i("player team: " + team.getName()); if (block.getState() instanceof Sign) { db.i("sign click!"); Sign sign = (Sign) block.getState(); if (((sign.getLine(0).equalsIgnoreCase("custom")) || (arena.getClass(sign.getLine(0)) != null)) && (team != null)) { arena.chooseClass(player, sign, sign.getLine(0)); } return; } db.i("block click!"); Material mMat = Material.IRON_BLOCK; db.i("reading ready block"); try { mMat = Material .getMaterial(arena.getArenaConfig().getInt(CFG.READY_BLOCK)); if (mMat == Material.AIR) mMat = Material.getMaterial(arena.getArenaConfig() .getString(CFG.READY_BLOCK)); db.i("mMat now is " + mMat.name()); } catch (Exception e) { db.i("exception reading ready block"); String sMat = arena.getArenaConfig().getString(CFG.READY_BLOCK); try { mMat = Material.getMaterial(sMat); db.i("mMat now is " + mMat.name()); } catch (Exception e2) { Language.log_warning(MSG.ERROR_MAT_NOT_FOUND, sMat); } } db.i("clicked " + block.getType().name() + ", is it " + mMat.name() + "?"); if (block.getTypeId() == mMat.getId()) { db.i("clicked ready block!"); if (ap.getClass().equals("")) { return; // not chosen class => OUT } if (arena.START_ID != -1) { return; // counting down => OUT } db.i("==============="); db.i("===== class: " + ap.getClass() + " ====="); db.i("==============="); if (!arena.isFightInProgress() && arena.START_ID == -1) { ArenaPlayer.parsePlayer(player.getName()).setStatus(Status.READY); if (arena.getArenaConfig().getBoolean(CFG.USES_EVENTEAMS)) { if (!TeamManager.checkEven(arena)) { arena.msg(player, Language.parse(MSG.NOTICE_WAITING_EQUAL)); return; // even teams desired, not done => announce } } if (!ArenaRegionShape.checkRegions(arena)) { arena.msg(player, Language.parse(MSG.NOTICE_WAITING_FOR_ARENA)); return; } String error = arena.ready(); if (error == null) { arena.start(); } else if (error.equals("")) { arena.countDown(); } else { arena.msg(player, error); } return; } if (arena.isFreeForAll()) { arena.tpPlayerToCoordName(player, "spawn"); } else { arena.tpPlayerToCoordName(player, team.getName() + "spawn"); } ArenaPlayer.parsePlayer(player.getName()).setStatus(Status.FIGHT); PVPArena.instance.getAmm().lateJoin(arena, player); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onPlayerInteract"
"@EventHandler(priority = EventPriority.LOW) public void onPlayerInteract(PlayerInteractEvent event) { Player player = event.getPlayer(); db.i("onPlayerInteract"); if (event.getAction().equals(Action.PHYSICAL)) { db.i("returning: physical"); return; } Arena arena = null; if (event.hasBlock()) { arena = ArenaManager.getArenaByRegionLocation(new PABlockLocation(event.getClickedBlock().getLocation())); } if (arena != null && PVPArena.instance.getAmm().onPlayerInteract(arena, event)) { db.i("returning: #1"); return; } if (PVPArena.instance.getAgm().checkSetFlag(player, event.getClickedBlock())) { db.i("returning: #2"); return; } if (ArenaRegionShape.checkRegionSetPosition(event, player)) { db.i("returning: #3"); return; } arena = ArenaPlayer.parsePlayer(player.getName()).getArena(); if (arena == null) { db.i("returning: #4"); ArenaManager.trySignJoin(event, player); return; } PVPArena.instance.getAgm().checkInteract(arena, player, event.getClickedBlock()); if (arena.isFightInProgress() && !PVPArena.instance.getAgm().allowsJoinInBattle(arena)) { db.i("exiting! fight in progress AND no INBATTLEJOIN arena!"); return; } ArenaPlayer ap = ArenaPlayer.parsePlayer(player.getName()); ArenaTeam team = ap.getArenaTeam(); if (!ap.getStatus().equals(Status.FIGHT)) { db.i("cancelling: no class"); // fighting player inside the lobby! event.setCancelled(true); } if (team == null) { db.i("returning: no team"); return; } if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)) { Block block = event.getClickedBlock(); db.i("player team: " + team.getName()); if (block.getState() instanceof Sign) { db.i("sign click!"); Sign sign = (Sign) block.getState(); if (((sign.getLine(0).equalsIgnoreCase("custom")) || (arena.getClass(sign.getLine(0)) != null)) && (team != null)) { arena.chooseClass(player, sign, sign.getLine(0)); } return; } db.i("block click!"); Material mMat = Material.IRON_BLOCK; db.i("reading ready block"); try { mMat = Material .getMaterial(arena.getArenaConfig().getInt(CFG.READY_BLOCK)); if (mMat == Material.AIR) mMat = Material.getMaterial(arena.getArenaConfig() .getString(CFG.READY_BLOCK)); db.i("mMat now is " + mMat.name()); } catch (Exception e) { db.i("exception reading ready block"); String sMat = arena.getArenaConfig().getString(CFG.READY_BLOCK); try { mMat = Material.getMaterial(sMat); db.i("mMat now is " + mMat.name()); } catch (Exception e2) { Language.log_warning(MSG.ERROR_MAT_NOT_FOUND, sMat); } } db.i("clicked " + block.getType().name() + ", is it " + mMat.name() + "?"); if (block.getTypeId() == mMat.getId()) { db.i("clicked ready block!"); if (ap.getClass().equals("")) { return; // not chosen class => OUT } if (arena.START_ID != -1) { return; // counting down => OUT } db.i("==============="); db.i("===== class: " + ap.getClass() + " ====="); db.i("==============="); if (!arena.isFightInProgress() && arena.START_ID == -1) { if (arena.getArenaConfig().getBoolean(CFG.USES_EVENTEAMS)) { if (!TeamManager.checkEven(arena)) { arena.msg(player, Language.parse(MSG.NOTICE_WAITING_EQUAL)); return; // even teams desired, not done => announce } } if (!ArenaRegionShape.checkRegions(arena)) { arena.msg(player, Language.parse(MSG.NOTICE_WAITING_FOR_ARENA)); return; } <MASK>ArenaPlayer.parsePlayer(player.getName()).setStatus(Status.READY);</MASK> String error = arena.ready(); if (error == null) { arena.start(); } else if (error.equals("")) { arena.countDown(); } else { arena.msg(player, error); } return; } if (arena.isFreeForAll()) { arena.tpPlayerToCoordName(player, "spawn"); } else { arena.tpPlayerToCoordName(player, team.getName() + "spawn"); } ArenaPlayer.parsePlayer(player.getName()).setStatus(Status.FIGHT); PVPArena.instance.getAmm().lateJoin(arena, player); } } }"
Inversion-Mutation
megadiff
"public synchronized MainFrame getMainWindow() { if (me == null) { statusBar = new SwingStatusBar(); me = new MainFrame(statusBar); ErrorListDialog.getErrorListDialog(); } return me; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getMainWindow"
"public synchronized MainFrame getMainWindow() { if (me == null) { statusBar = new SwingStatusBar(); <MASK>ErrorListDialog.getErrorListDialog();</MASK> me = new MainFrame(statusBar); } return me; }"
Inversion-Mutation
megadiff
"void run(final EditorArea editor, final Action action) { refreshControls(editor, false); final byte[] in = editor.getText(); final boolean eq = eq(in, editor.last); if(eq && action == Action.CHECK) return; if(action == Action.EXECUTE && gui.gopts.get(GUIOptions.SAVERUN)) { for(final EditorArea edit : editors()) { if(edit.opened()) edit.save(); } } IOFile file = editor.file; editor.last = in; final boolean xquery = file.hasSuffix(IO.XQSUFFIXES) || !file.path().contains("."); editor.script = !xquery && file.hasSuffix(IO.BXSSUFFIX); if(action == Action.EXECUTE && editor.script) { // execute query if forced, or if realtime execution is activated gui.execute(true, new Execute(string(in))); } else if(xquery || action == Action.EXECUTE) { // check if input is/might be an xquery main module String input = in.length == 0 ? "()" : string(in); boolean lib = QueryProcessor.isLibrary(input); final boolean exec = action == Action.EXECUTE || gui.gopts.get(GUIOptions.EXECRT); if(exec && lib) { final EditorArea ea = execEditor(); if(ea != null) { file = ea.file; input = string(ea.getText()); lib = false; } } gui.context.options.set(MainOptions.QUERYPATH, file.path()); if(!lib && exec) { // execute query if forced, or if realtime execution is activated gui.execute(true, new XQuery(input)); execFile = file; } else { // parse query final QueryContext qc = new QueryContext(gui.context); try { qc.parse(input, lib, null, null); info(null); } catch(final QueryException ex) { info(ex); } finally { qc.close(); } } } else if(file.hasSuffix(IO.JSONSUFFIX)) { try { final IOContent io = new IOContent(in); io.name(file.path()); JsonConverter.get(new JsonParserOptions()).convert(io); info(null); } catch(final IOException ex) { info(ex); } } else if(editor.script || file.hasSuffix(IO.XMLSUFFIXES) || file.hasSuffix(IO.XSLSUFFIXES)) { final ArrayInput ai = new ArrayInput(in); try { // check XML syntax if(startsWith(in, '<') || !editor.script) new XmlParser().parse(ai); // check command script if(editor.script) new CommandParser(string(in), gui.context).parse(); info(null); } catch(final Exception ex) { info(ex); } } else if(action != Action.CHECK) { info(null); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"void run(final EditorArea editor, final Action action) { refreshControls(editor, false); final byte[] in = editor.getText(); final boolean eq = eq(in, editor.last); if(eq && action == Action.CHECK) return; if(action == Action.EXECUTE && gui.gopts.get(GUIOptions.SAVERUN)) { for(final EditorArea edit : editors()) { if(edit.opened()) edit.save(); } } IOFile file = editor.file; editor.last = in; final boolean xquery = file.hasSuffix(IO.XQSUFFIXES) || !file.path().contains("."); editor.script = !xquery && file.hasSuffix(IO.BXSSUFFIX); if(action == Action.EXECUTE && editor.script) { // execute query if forced, or if realtime execution is activated gui.execute(true, new Execute(string(in))); } else if(xquery || action == Action.EXECUTE) { // check if input is/might be an xquery main module String input = in.length == 0 ? "()" : string(in); boolean lib = QueryProcessor.isLibrary(input); final boolean exec = action == Action.EXECUTE || gui.gopts.get(GUIOptions.EXECRT); if(exec && lib) { final EditorArea ea = execEditor(); if(ea != null) { file = ea.file; input = string(ea.getText()); lib = false; } } if(!lib && exec) { // execute query if forced, or if realtime execution is activated gui.execute(true, new XQuery(input)); execFile = file; } else { // parse query <MASK>gui.context.options.set(MainOptions.QUERYPATH, file.path());</MASK> final QueryContext qc = new QueryContext(gui.context); try { qc.parse(input, lib, null, null); info(null); } catch(final QueryException ex) { info(ex); } finally { qc.close(); } } } else if(file.hasSuffix(IO.JSONSUFFIX)) { try { final IOContent io = new IOContent(in); io.name(file.path()); JsonConverter.get(new JsonParserOptions()).convert(io); info(null); } catch(final IOException ex) { info(ex); } } else if(editor.script || file.hasSuffix(IO.XMLSUFFIXES) || file.hasSuffix(IO.XSLSUFFIXES)) { final ArrayInput ai = new ArrayInput(in); try { // check XML syntax if(startsWith(in, '<') || !editor.script) new XmlParser().parse(ai); // check command script if(editor.script) new CommandParser(string(in), gui.context).parse(); info(null); } catch(final Exception ex) { info(ex); } } else if(action != Action.CHECK) { info(null); } }"
Inversion-Mutation
megadiff
"@Override public void onStart() { super.onStart(); final ZLAndroidApplication application = ZLAndroidApplication.Instance(); final int fullScreenFlag = application.ShowStatusBarOption.getValue() ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN; if (fullScreenFlag != myFullScreenFlag) { finish(); startActivity(new Intent(this, this.getClass())); } if (myPanel.ControlPanel == null) { myPanel.ControlPanel = new ControlPanel(this); myPanel.ControlPanel.addButton(ActionCode.FIND_PREVIOUS, false, R.drawable.text_search_previous); myPanel.ControlPanel.addButton(ActionCode.CLEAR_FIND_RESULTS, true, R.drawable.text_search_close); myPanel.ControlPanel.addButton(ActionCode.FIND_NEXT, false, R.drawable.text_search_next); RelativeLayout root = (RelativeLayout)findViewById(R.id.root_view); RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); p.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); p.addRule(RelativeLayout.CENTER_HORIZONTAL); root.addView(myPanel.ControlPanel, p); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onStart"
"@Override public void onStart() { super.onStart(); final ZLAndroidApplication application = ZLAndroidApplication.Instance(); final int fullScreenFlag = application.ShowStatusBarOption.getValue() ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN; if (fullScreenFlag != myFullScreenFlag) { <MASK>startActivity(new Intent(this, this.getClass()));</MASK> finish(); } if (myPanel.ControlPanel == null) { myPanel.ControlPanel = new ControlPanel(this); myPanel.ControlPanel.addButton(ActionCode.FIND_PREVIOUS, false, R.drawable.text_search_previous); myPanel.ControlPanel.addButton(ActionCode.CLEAR_FIND_RESULTS, true, R.drawable.text_search_close); myPanel.ControlPanel.addButton(ActionCode.FIND_NEXT, false, R.drawable.text_search_next); RelativeLayout root = (RelativeLayout)findViewById(R.id.root_view); RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); p.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); p.addRule(RelativeLayout.CENTER_HORIZONTAL); root.addView(myPanel.ControlPanel, p); } }"
Inversion-Mutation
megadiff
"public void visitForExpression(JFXForExpression tree) { JavafxEnv<JavafxAttrContext> forExprEnv = env.dup(tree, env.info.dup(env.info.scope.dup())); forExprEnv.outer = env; if (forClauses == null) forClauses = new ArrayList<JFXForExpressionInClause>(); int forClausesOldSize = forClauses.size(); for (ForExpressionInClauseTree cl : tree.getInClauses()) { // Don't try to examine erroneous in clauses. We don't wish to // place the entire for expression into error nodes, just because // one or more in clauses was in error, so we jsut skip any // erroneous ones. // if (cl instanceof JFXErroneousForExpressionInClause) continue; JFXForExpressionInClause clause = (JFXForExpressionInClause)cl; forClauses.add(clause); JFXVar var = clause.getVar(); // Don't try to examine erroneous loop controls, such as // when a variable was missing. Again, this is because the IDE may // try to attribute a node that is mostly correct, but contains // one or more components that are in error. // if (var == null || var instanceof JFXErroneousVar) continue; Type declType = attribType(var.getJFXType(), forExprEnv); attribVar(var, forExprEnv); JFXExpression expr = (JFXExpression)clause.getSequenceExpression(); Type exprType = types.upperBound(attribExpr(expr, forExprEnv)); chk.checkNonVoid(((JFXTree)clause).pos(), exprType); Type elemtype; // if exprtype is T[], T is the element type of the for-each if (types.isSequence(exprType)) { elemtype = types.elementType(exprType); } // if exprtype implements Iterable<T>, T is the element type of the for-each else if (types.asSuper(exprType, syms.iterableType.tsym) != null) { if (clause.isBound()) { log.error(clause.getSequenceExpression().pos(), MsgSym.MESSAGE_JAVAFX_FOR_OVER_ITERABLE_DISALLOWED_IN_BIND); } Type base = types.asSuper(exprType, syms.iterableType.tsym); List<Type> iterableParams = base.allparams(); if (iterableParams.isEmpty()) { elemtype = syms.objectType; } else { elemtype = types.upperBound(iterableParams.last()); } } //FIXME: if exprtype is nativearray of T, T is the element type of the for-each (see JFXC-2784) else if (types.isArray(exprType)) { elemtype = types.elemtype(exprType); } else { log.warning(expr, MsgSym.MESSAGE_JAVAFX_ITERATING_NON_SEQUENCE); elemtype = exprType; } if (elemtype == syms.errType) { log.error(clause.getSequenceExpression().pos(), MsgSym.MESSAGE_FOREACH_NOT_APPLICABLE_TO_TYPE); } else if (elemtype == syms.botType || elemtype == syms.unreachableType) { elemtype = syms.objectType; } else { // if it is a primitive type, unbox it Type unboxed = types.unboxedType(elemtype); if (unboxed != Type.noType) { elemtype = unboxed; } chk.checkType(clause.getSequenceExpression().pos(), elemtype, declType, Sequenceness.DISALLOWED); } if (declType == syms.javafx_UnspecifiedType) { var.type = elemtype; var.sym.type = elemtype; } if (clause.getWhereExpression() != null) { attribExpr(clause.getWhereExpression(), env, syms.booleanType); } } forExprEnv.tree = tree; // before, we were not in loop! attribTree(tree.getBodyExpression(), forExprEnv, VAL, pt.tag != ERROR ? pt : Type.noType, Sequenceness.PERMITTED); Type bodyType = tree.getBodyExpression().type; if (bodyType == syms.unreachableType) log.error(tree.getBodyExpression(), MsgSym.MESSAGE_UNREACHABLE_STMT); Type owntype = (bodyType == null || bodyType == syms.voidType)? syms.voidType : types.isSequence(bodyType) ? bodyType : types.sequenceType(bodyType); while (forClauses.size() > forClausesOldSize) forClauses.remove(forClauses.size()-1); forExprEnv.info.scope.leave(); result = check(tree, owntype, VAL, pkind, pt, pSequenceness); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "visitForExpression"
"public void visitForExpression(JFXForExpression tree) { JavafxEnv<JavafxAttrContext> forExprEnv = env.dup(tree, env.info.dup(env.info.scope.dup())); forExprEnv.outer = env; if (forClauses == null) forClauses = new ArrayList<JFXForExpressionInClause>(); int forClausesOldSize = forClauses.size(); for (ForExpressionInClauseTree cl : tree.getInClauses()) { // Don't try to examine erroneous in clauses. We don't wish to // place the entire for expression into error nodes, just because // one or more in clauses was in error, so we jsut skip any // erroneous ones. // if (cl instanceof JFXErroneousForExpressionInClause) continue; JFXForExpressionInClause clause = (JFXForExpressionInClause)cl; forClauses.add(clause); JFXVar var = clause.getVar(); // Don't try to examine erroneous loop controls, such as // when a variable was missing. Again, this is because the IDE may // try to attribute a node that is mostly correct, but contains // one or more components that are in error. // if (var == null || var instanceof JFXErroneousVar) continue; Type declType = attribType(var.getJFXType(), forExprEnv); JFXExpression expr = (JFXExpression)clause.getSequenceExpression(); Type exprType = types.upperBound(attribExpr(expr, forExprEnv)); <MASK>attribVar(var, forExprEnv);</MASK> chk.checkNonVoid(((JFXTree)clause).pos(), exprType); Type elemtype; // if exprtype is T[], T is the element type of the for-each if (types.isSequence(exprType)) { elemtype = types.elementType(exprType); } // if exprtype implements Iterable<T>, T is the element type of the for-each else if (types.asSuper(exprType, syms.iterableType.tsym) != null) { if (clause.isBound()) { log.error(clause.getSequenceExpression().pos(), MsgSym.MESSAGE_JAVAFX_FOR_OVER_ITERABLE_DISALLOWED_IN_BIND); } Type base = types.asSuper(exprType, syms.iterableType.tsym); List<Type> iterableParams = base.allparams(); if (iterableParams.isEmpty()) { elemtype = syms.objectType; } else { elemtype = types.upperBound(iterableParams.last()); } } //FIXME: if exprtype is nativearray of T, T is the element type of the for-each (see JFXC-2784) else if (types.isArray(exprType)) { elemtype = types.elemtype(exprType); } else { log.warning(expr, MsgSym.MESSAGE_JAVAFX_ITERATING_NON_SEQUENCE); elemtype = exprType; } if (elemtype == syms.errType) { log.error(clause.getSequenceExpression().pos(), MsgSym.MESSAGE_FOREACH_NOT_APPLICABLE_TO_TYPE); } else if (elemtype == syms.botType || elemtype == syms.unreachableType) { elemtype = syms.objectType; } else { // if it is a primitive type, unbox it Type unboxed = types.unboxedType(elemtype); if (unboxed != Type.noType) { elemtype = unboxed; } chk.checkType(clause.getSequenceExpression().pos(), elemtype, declType, Sequenceness.DISALLOWED); } if (declType == syms.javafx_UnspecifiedType) { var.type = elemtype; var.sym.type = elemtype; } if (clause.getWhereExpression() != null) { attribExpr(clause.getWhereExpression(), env, syms.booleanType); } } forExprEnv.tree = tree; // before, we were not in loop! attribTree(tree.getBodyExpression(), forExprEnv, VAL, pt.tag != ERROR ? pt : Type.noType, Sequenceness.PERMITTED); Type bodyType = tree.getBodyExpression().type; if (bodyType == syms.unreachableType) log.error(tree.getBodyExpression(), MsgSym.MESSAGE_UNREACHABLE_STMT); Type owntype = (bodyType == null || bodyType == syms.voidType)? syms.voidType : types.isSequence(bodyType) ? bodyType : types.sequenceType(bodyType); while (forClauses.size() > forClausesOldSize) forClauses.remove(forClauses.size()-1); forExprEnv.info.scope.leave(); result = check(tree, owntype, VAL, pkind, pt, pSequenceness); }"
Inversion-Mutation
megadiff
"public TimeTravelAction() { super(); setEnabled(false); if (getController().getProject() == null) { } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "TimeTravelAction"
"public TimeTravelAction() { super(); if (getController().getProject() == null) { <MASK>setEnabled(false);</MASK> } }"
Inversion-Mutation
megadiff
"public CytoscapeWindow (cytoscape parentApp, CytoscapeConfig config, Logger logger, Graph2D graph, ExpressionData expressionData, BioDataServer bioDataServer, GraphObjAttributes nodeAttributes, GraphObjAttributes edgeAttributes, String geometryFilename, String expressionDataFilename, String title, boolean doFreshLayout) throws Exception { this.parentApp = parentApp; this.logger = logger; // do not set graph yet - set it using setGraph() function below // dramage 2002-08-16 // this.graph = graph; this.geometryFilename = geometryFilename; this.expressionDataFilename = expressionDataFilename; this.bioDataServer = bioDataServer; this.expressionData = expressionData; this.config = config; // setupLogging (); if (nodeAttributes != null) this.nodeAttributes = nodeAttributes; if (edgeAttributes != null) this.edgeAttributes = edgeAttributes; this.currentDirectory = new File (System.getProperty ("user.dir")); vizMapperCategories = new VizMapperCategories(); vizMapper = new AttributeMapper( vizMapperCategories.getInitialDefaults() ); AttributeMapperPropertiesAdapter adapter = new AttributeMapperPropertiesAdapter(vizMapper, vizMapperCategories); adapter.applyAllRangeProperties( config.getProperties() ); if (title == null) this.windowTitle = ""; else this.windowTitle = title; initializeWidgets (); setGraph(graph); displayCommonNodeNames (); displayNewGraph (doFreshLayout); mainFrame.addWindowListener (parentApp); mainFrame.setVisible (true); // load plugins last, after the main window is setup, since they // will often need access to all of the parts of a fully // instantiated CytoscapeWindow loadPlugins(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "CytoscapeWindow"
"public CytoscapeWindow (cytoscape parentApp, CytoscapeConfig config, Logger logger, Graph2D graph, ExpressionData expressionData, BioDataServer bioDataServer, GraphObjAttributes nodeAttributes, GraphObjAttributes edgeAttributes, String geometryFilename, String expressionDataFilename, String title, boolean doFreshLayout) throws Exception { this.parentApp = parentApp; this.logger = logger; // do not set graph yet - set it using setGraph() function below // dramage 2002-08-16 // this.graph = graph; this.geometryFilename = geometryFilename; this.expressionDataFilename = expressionDataFilename; this.bioDataServer = bioDataServer; this.expressionData = expressionData; this.config = config; // setupLogging (); if (nodeAttributes != null) this.nodeAttributes = nodeAttributes; if (edgeAttributes != null) this.edgeAttributes = edgeAttributes; this.currentDirectory = new File (System.getProperty ("user.dir")); vizMapperCategories = new VizMapperCategories(); vizMapper = new AttributeMapper( vizMapperCategories.getInitialDefaults() ); AttributeMapperPropertiesAdapter adapter = new AttributeMapperPropertiesAdapter(vizMapper, vizMapperCategories); adapter.applyAllRangeProperties( config.getProperties() ); if (title == null) this.windowTitle = ""; else this.windowTitle = title; initializeWidgets (); setGraph(graph); displayCommonNodeNames (); displayNewGraph (doFreshLayout); <MASK>mainFrame.setVisible (true);</MASK> mainFrame.addWindowListener (parentApp); // load plugins last, after the main window is setup, since they // will often need access to all of the parts of a fully // instantiated CytoscapeWindow loadPlugins(); }"
Inversion-Mutation
megadiff
"@Override public List<BeanMetaData> getBeans() { ArrayList<BeanMetaData> result = new ArrayList<BeanMetaData>(); //Create AspectBinding AbstractBeanMetaData stack = new AbstractBeanMetaData(); stack.setName(name); BeanMetaDataUtil.setSimpleProperty(stack, "name", name); stack.setBean(Stack.class.getName()); util.setAspectManagerProperty(stack, "manager"); result.add(stack); if (interceptors.size() > 0) { AbstractListMetaData almd = new AbstractListMetaData(); int i = 0; for (BaseInterceptorData interceptor : interceptors) { AbstractBeanMetaData bmd = new AbstractBeanMetaData(interceptor.getBeanClassName()); String intName = name + "$" + i++; bmd.setName(intName); util.setAspectManagerProperty(bmd, "manager"); BeanMetaDataUtil.setSimpleProperty(bmd, "forStack", Boolean.TRUE); if (interceptor instanceof AdviceData) { BeanMetaDataUtil.DependencyBuilder db = new BeanMetaDataUtil.DependencyBuilder(bmd, "aspect", interceptor.getRefName()); BeanMetaDataUtil.setDependencyProperty(db); if (((AdviceData)interceptor).getAdviceMethod() != null) { BeanMetaDataUtil.setSimpleProperty(bmd, "aspectMethod", ((AdviceData)interceptor).getAdviceMethod()); } BeanMetaDataUtil.setSimpleProperty(bmd, "type", ((AdviceData)interceptor).getType()); } else { BeanMetaDataUtil.DependencyBuilder db = new BeanMetaDataUtil.DependencyBuilder(bmd, "stack", interceptor.getRefName()); BeanMetaDataUtil.setDependencyProperty(db); } result.add(bmd); almd.add(new AbstractInjectionValueMetaData(intName)); } BeanMetaDataUtil.setSimpleProperty(stack, "advices", almd); } return result; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getBeans"
"@Override public List<BeanMetaData> getBeans() { ArrayList<BeanMetaData> result = new ArrayList<BeanMetaData>(); //Create AspectBinding AbstractBeanMetaData stack = new AbstractBeanMetaData(); stack.setName(name); BeanMetaDataUtil.setSimpleProperty(stack, "name", name); stack.setBean(Stack.class.getName()); util.setAspectManagerProperty(stack, "manager"); result.add(stack); if (interceptors.size() > 0) { AbstractListMetaData almd = new AbstractListMetaData(); int i = 0; for (BaseInterceptorData interceptor : interceptors) { AbstractBeanMetaData bmd = new AbstractBeanMetaData(interceptor.getBeanClassName()); String intName = name + "$" + i++; bmd.setName(intName); util.setAspectManagerProperty(bmd, "manager"); BeanMetaDataUtil.setSimpleProperty(bmd, "forStack", Boolean.TRUE); if (interceptor instanceof AdviceData) { BeanMetaDataUtil.DependencyBuilder db = new BeanMetaDataUtil.DependencyBuilder(bmd, "aspect", interceptor.getRefName()); BeanMetaDataUtil.setDependencyProperty(db); if (((AdviceData)interceptor).getAdviceMethod() != null) { BeanMetaDataUtil.setSimpleProperty(bmd, "aspectMethod", ((AdviceData)interceptor).getAdviceMethod()); } BeanMetaDataUtil.setSimpleProperty(bmd, "type", ((AdviceData)interceptor).getType()); } else { BeanMetaDataUtil.DependencyBuilder db = new BeanMetaDataUtil.DependencyBuilder(bmd, "stack", interceptor.getRefName()); BeanMetaDataUtil.setDependencyProperty(db); } result.add(bmd); almd.add(new AbstractInjectionValueMetaData(intName)); <MASK>BeanMetaDataUtil.setSimpleProperty(stack, "advices", almd);</MASK> } } return result; }"
Inversion-Mutation
megadiff
"public void resume() throws DebugException { if (!isSuspended()) { return; } try { setSuspended(false); getVM().resume(); Iterator threads = getThreadList().iterator(); while (threads.hasNext()) { ((JDIThread)threads.next()).resumedByVM(); } fireResumeEvent(DebugEvent.CLIENT_REQUEST); } catch (VMDisconnectedException e) { disconnected(); return; } catch (RuntimeException e) { setSuspended(true); fireSuspendEvent(DebugEvent.CLIENT_REQUEST); targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIDebugTarget.exception_resume"), new String[] {e.toString()}), e); //$NON-NLS-1$ } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "resume"
"public void resume() throws DebugException { if (!isSuspended()) { return; } try { setSuspended(false); <MASK>fireResumeEvent(DebugEvent.CLIENT_REQUEST);</MASK> getVM().resume(); Iterator threads = getThreadList().iterator(); while (threads.hasNext()) { ((JDIThread)threads.next()).resumedByVM(); } } catch (VMDisconnectedException e) { disconnected(); return; } catch (RuntimeException e) { setSuspended(true); fireSuspendEvent(DebugEvent.CLIENT_REQUEST); targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIDebugTarget.exception_resume"), new String[] {e.toString()}), e); //$NON-NLS-1$ } }"
Inversion-Mutation
megadiff
"private void switchGameMode(String mode) { changeConfig("mp_gamemode", mode); if("editor".equalsIgnoreCase(mode)) { gameplayController.endRound(-1, true); for(Player p : getPlayerController().getAllPlayers()) { getPlayerController().setDefaultEquipment(p); p.getControl().setGravity(0); } CWRITER.writeLine("switched gamemode to 'editor'"); }else if("ctf".equalsIgnoreCase(mode)) { gameplayController.endRound(-1, true); for(Player p : getPlayerController().getAllPlayers()) { getPlayerController().setDefaultEquipment(p); p.getControl().setGravity(25); } CWRITER.writeLine("switched gamemode to 'ctf'"); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "switchGameMode"
"private void switchGameMode(String mode) { if("editor".equalsIgnoreCase(mode)) { gameplayController.endRound(-1, true); for(Player p : getPlayerController().getAllPlayers()) { getPlayerController().setDefaultEquipment(p); p.getControl().setGravity(0); } CWRITER.writeLine("switched gamemode to 'editor'"); }else if("ctf".equalsIgnoreCase(mode)) { gameplayController.endRound(-1, true); for(Player p : getPlayerController().getAllPlayers()) { getPlayerController().setDefaultEquipment(p); p.getControl().setGravity(25); } CWRITER.writeLine("switched gamemode to 'ctf'"); } <MASK>changeConfig("mp_gamemode", mode);</MASK> }"
Inversion-Mutation
megadiff
"@SuppressWarnings("unchecked") public List<T> findAll() { String filter = "objectClass=" + getBeanClass().getSimpleName(); final QueryConfig<T> queryConfig = this.getQueryConfig(); if (queryConfig != null) if (queryConfig.getFilter() != null && !queryConfig.getFilter().isEmpty()) filter = getFilter(getBeanClass(), queryConfig.getFilter(), queryConfig.getFilterLogic(), queryConfig.getFilterComparison()); EntryQuery query = getEntryManager().createQuery(filter); if (queryConfig != null) { // TODO: implement pagination with LDAP Asynchronous Query // queryConfig.setTotalResults(countAll(queryConfig)); if (queryConfig.getMaxResults() > 0) { // query.setFirstResult(queryConfig.getFirstResult()); query.setMaxResults(queryConfig.getMaxResults()); } query.setBaseDN((String) queryConfig.getGeneric()); } return query.getResultList(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "findAll"
"@SuppressWarnings("unchecked") public List<T> findAll() { String filter = "objectClass=" + getBeanClass().getSimpleName(); final QueryConfig<T> queryConfig = this.getQueryConfig(); if (queryConfig != null) if (queryConfig.getFilter() != null && !queryConfig.getFilter().isEmpty()) filter = getFilter(getBeanClass(), queryConfig.getFilter(), queryConfig.getFilterLogic(), queryConfig.getFilterComparison()); EntryQuery query = getEntryManager().createQuery(filter); if (queryConfig != null) { // TODO: implement pagination with LDAP Asynchronous Query // queryConfig.setTotalResults(countAll(queryConfig)); if (queryConfig.getMaxResults() > 0) { // query.setFirstResult(queryConfig.getFirstResult()); <MASK>query.setBaseDN((String) queryConfig.getGeneric());</MASK> query.setMaxResults(queryConfig.getMaxResults()); } } return query.getResultList(); }"
Inversion-Mutation
megadiff
"public void setAttributes(Selector selector, CSSAttributeSet attributes) { Style style = getDynamicStyle(selector); if (style == null) { addDynamicStyle(new CSSStyle(selector, attributes)); } else { Map<CSSProperty, String> oldStyleProperties = style.properties(); boolean changed = style.putAll(attributes); if (changed) reload(); propertyChangeSupport.firePropertyChange("attributes", oldStyleProperties, style.properties()); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setAttributes"
"public void setAttributes(Selector selector, CSSAttributeSet attributes) { Style style = getDynamicStyle(selector); <MASK>Map<CSSProperty, String> oldStyleProperties = style.properties();</MASK> if (style == null) { addDynamicStyle(new CSSStyle(selector, attributes)); } else { boolean changed = style.putAll(attributes); if (changed) reload(); propertyChangeSupport.firePropertyChange("attributes", oldStyleProperties, style.properties()); } }"
Inversion-Mutation
megadiff
"private void logMessages(String path, Revision pegRevision, Revision revisionStart, Revision revisionEnd, boolean stopOnCopy, boolean discoverPath, boolean includeMergeInfo, String[] revisionProperties, long limit, ISVNLogEntryHandler logEntryHandler) throws ClientException { SVNLogClient client = getSVNLogClient(); try { if (isURL(path)) { client.doLog( SVNURL.parseURIEncoded(path), new String[]{""}, JavaHLObjectFactory.getSVNRevision(pegRevision), JavaHLObjectFactory.getSVNRevision(revisionStart), JavaHLObjectFactory.getSVNRevision(revisionEnd), stopOnCopy, discoverPath, includeMergeInfo, limit, revisionProperties, logEntryHandler); } else { client.doLog( new File[]{new File(path).getAbsoluteFile()}, JavaHLObjectFactory.getSVNRevision(revisionStart), JavaHLObjectFactory.getSVNRevision(revisionEnd), JavaHLObjectFactory.getSVNRevision(pegRevision), stopOnCopy, discoverPath, includeMergeInfo, limit, revisionProperties, logEntryHandler); } } catch (SVNException e) { throwException(e); } finally { resetLog(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "logMessages"
"private void logMessages(String path, Revision pegRevision, Revision revisionStart, Revision revisionEnd, boolean stopOnCopy, boolean discoverPath, boolean includeMergeInfo, String[] revisionProperties, long limit, ISVNLogEntryHandler logEntryHandler) throws ClientException { SVNLogClient client = getSVNLogClient(); try { if (isURL(path)) { client.doLog( SVNURL.parseURIEncoded(path), new String[]{""}, <MASK>JavaHLObjectFactory.getSVNRevision(pegRevision),</MASK> JavaHLObjectFactory.getSVNRevision(revisionStart), JavaHLObjectFactory.getSVNRevision(revisionEnd), stopOnCopy, discoverPath, includeMergeInfo, limit, revisionProperties, logEntryHandler); } else { client.doLog( new File[]{new File(path).getAbsoluteFile()}, <MASK>JavaHLObjectFactory.getSVNRevision(pegRevision),</MASK> JavaHLObjectFactory.getSVNRevision(revisionStart), JavaHLObjectFactory.getSVNRevision(revisionEnd), stopOnCopy, discoverPath, includeMergeInfo, limit, revisionProperties, logEntryHandler); } } catch (SVNException e) { throwException(e); } finally { resetLog(); } }"
Inversion-Mutation
megadiff
"private void computeName() throws CoreException { if (isResolved()) { fName= getIncludes().getLocation().getURI().getPath(); } else { fName= getNameForUnresolved().getString(); } fName= fName.substring(fName.lastIndexOf('/')+1); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "computeName"
"private void computeName() throws CoreException { if (isResolved()) { fName= getIncludes().getLocation().getURI().getPath(); <MASK>fName= fName.substring(fName.lastIndexOf('/')+1);</MASK> } else { fName= getNameForUnresolved().getString(); } }"
Inversion-Mutation
megadiff
"String getType(String name) { String type = null; if(name.endsWith(".class")) name = name.substring(0, name.length() - 6); boolean array = name.endsWith("[]"); if(array) name = name.substring(0, name.length()-2); if(name.indexOf('.') != -1) { return array ? (name + "[]") : name; } if(primitives.contains(name)) { return array ? (name + "[]") : name; } Pattern p = Pattern.compile("import\\s+(static\\s+)?([\\w\\d\\._\\$]+\\." + name + ");"); Matcher m = p.matcher(source); if(m.find()) { type = m.group(2); if(m.group(1) != null) { type = type.substring(0, type.lastIndexOf('.')); } } else { String src = name + ".java"; String[] siblings = file.getParentFile().list(); for(String sibling : siblings) { if(src.equals(sibling)) { type = packageName + "." + name; break; } } if(type == null) { type = "java.lang." + name; } } if(array) { return type + "[]"; } return type; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getType"
"String getType(String name) { String type = null; boolean array = name.endsWith("[]"); if(array) name = name.substring(0, name.length()-2); <MASK>if(name.endsWith(".class")) name = name.substring(0, name.length() - 6);</MASK> if(name.indexOf('.') != -1) { return array ? (name + "[]") : name; } if(primitives.contains(name)) { return array ? (name + "[]") : name; } Pattern p = Pattern.compile("import\\s+(static\\s+)?([\\w\\d\\._\\$]+\\." + name + ");"); Matcher m = p.matcher(source); if(m.find()) { type = m.group(2); if(m.group(1) != null) { type = type.substring(0, type.lastIndexOf('.')); } } else { String src = name + ".java"; String[] siblings = file.getParentFile().list(); for(String sibling : siblings) { if(src.equals(sibling)) { type = packageName + "." + name; break; } } if(type == null) { type = "java.lang." + name; } } if(array) { return type + "[]"; } return type; }"
Inversion-Mutation
megadiff
"public void run() { if (taskMonitor == null) { throw new IllegalStateException("Task Monitor is not set."); } taskMonitor.setStatus("Installing " + pluginInfo.getName() + " v" + pluginInfo.getPluginVersion()); taskMonitor.setPercentCompleted(-1); PluginManager Mgr = PluginManager.getPluginManager(); try { pluginInfo = Mgr.download(pluginInfo, taskMonitor); taskMonitor.setStatus(pluginInfo.getName() + " v" + pluginInfo.getPluginVersion() + " complete."); PluginManageDialog.this.setMessage(pluginInfo.getName() + " install complete."); taskMonitor.setStatus(pluginInfo.getName() + " v" + pluginInfo.getPluginVersion() + " loading..."); } catch (java.io.IOException ioe) { taskMonitor .setException(ioe, "Failed to download " + pluginInfo.getName() + " from " + pluginInfo.getUrl()); pluginInfo = null; } catch (cytoscape.plugin.ManagerException me) { pluginInfo = null; taskMonitor.setException(me, me.getMessage()); } finally { taskMonitor.setPercentCompleted(100); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"public void run() { if (taskMonitor == null) { throw new IllegalStateException("Task Monitor is not set."); } taskMonitor.setStatus("Installing " + pluginInfo.getName() + " v" + pluginInfo.getPluginVersion()); taskMonitor.setPercentCompleted(-1); PluginManager Mgr = PluginManager.getPluginManager(); try { pluginInfo = Mgr.download(pluginInfo, taskMonitor); taskMonitor.setStatus(pluginInfo.getName() + " v" + pluginInfo.getPluginVersion() + " complete."); PluginManageDialog.this.setMessage(pluginInfo.getName() + " install complete."); taskMonitor.setStatus(pluginInfo.getName() + " v" + pluginInfo.getPluginVersion() + " loading..."); } catch (java.io.IOException ioe) { <MASK>pluginInfo = null;</MASK> taskMonitor .setException(ioe, "Failed to download " + pluginInfo.getName() + " from " + pluginInfo.getUrl()); } catch (cytoscape.plugin.ManagerException me) { <MASK>pluginInfo = null;</MASK> taskMonitor.setException(me, me.getMessage()); } finally { taskMonitor.setPercentCompleted(100); } }"
Inversion-Mutation
megadiff
"private void updateDrbdResources() { final DrbdXML dxml = new DrbdXML(cluster.getHostsArray(), drbdParameters); boolean configUpdated = false; for (final Host host : cluster.getHostsArray()) { final String configString = dxml.getConfig(host); if (!Tools.areEqual(configString, oldDrbdConfigString.get(host))) { oldDrbdConfigString.put(host, configString); configUpdated = true; } dxml.update(configString); } drbdXML = dxml; if (!configUpdated) { return; } final boolean testOnly = false; final DrbdInfo drbdInfo = drbdGraph.getDrbdInfo(); boolean atLeastOneAdded = false; for (final Object k : dxml.getResourceDeviceMap().keySet()) { final String resName = (String) ((MultiKey) k).getKey(0); final String volumeNr = (String) ((MultiKey) k).getKey(1); final String drbdDev = dxml.getDrbdDevice(resName, volumeNr); final Map<String, String> hostDiskMap = dxml.getHostDiskMap(resName, volumeNr); BlockDevInfo bd1 = null; BlockDevInfo bd2 = null; if (hostDiskMap == null) { continue; } for (String hostName : hostDiskMap.keySet()) { if (!cluster.contains(hostName)) { continue; } final String disk = hostDiskMap.get(hostName); final BlockDevInfo bdi = drbdGraph.findBlockDevInfo(hostName, disk); if (bdi == null) { if (getDrbdDevHash().containsKey(disk)) { /* TODO: ignoring stacked device */ putDrbdDevHash(); continue; } else { putDrbdDevHash(); Tools.appWarning("could not find disk: " + disk + " on host: " + hostName); continue; } } bdi.setParameters(resName); if (bd1 == null) { bd1 = bdi; } else { bd2 = bdi; } } if (bd1 != null && bd2 != null) { /* add DRBD resource */ DrbdResourceInfo dri = getDrbdResHash().get(resName); putDrbdResHash(); if (dri == null) { dri = drbdInfo.addDrbdResource(resName, testOnly); atLeastOneAdded = true; } dri.setParameters(); DrbdVolumeInfo dvi = dri.getDrbdVolumeInfo(volumeNr); if (dvi == null) { dvi = drbdInfo.addDrbdVolume( dri, volumeNr, drbdDev, new ArrayList<BlockDevInfo>( Arrays.asList(bd1, bd2)), testOnly); atLeastOneAdded = true; } dvi.setParameters(); } } if (atLeastOneAdded) { drbdInfo.getInfoPanel(); Tools.invokeAndWait(new Runnable() { @Override public void run() { drbdInfo.setAllApplyButtons(); } }); drbdInfo.reloadDRBDResourceComboBoxes(); SwingUtilities.invokeLater(new Runnable() { public void run() { drbdGraph.scale(); } }); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "updateDrbdResources"
"private void updateDrbdResources() { final DrbdXML dxml = new DrbdXML(cluster.getHostsArray(), drbdParameters); boolean configUpdated = false; for (final Host host : cluster.getHostsArray()) { final String configString = dxml.getConfig(host); if (!Tools.areEqual(configString, oldDrbdConfigString.get(host))) { oldDrbdConfigString.put(host, configString); configUpdated = true; <MASK>dxml.update(configString);</MASK> } } drbdXML = dxml; if (!configUpdated) { return; } final boolean testOnly = false; final DrbdInfo drbdInfo = drbdGraph.getDrbdInfo(); boolean atLeastOneAdded = false; for (final Object k : dxml.getResourceDeviceMap().keySet()) { final String resName = (String) ((MultiKey) k).getKey(0); final String volumeNr = (String) ((MultiKey) k).getKey(1); final String drbdDev = dxml.getDrbdDevice(resName, volumeNr); final Map<String, String> hostDiskMap = dxml.getHostDiskMap(resName, volumeNr); BlockDevInfo bd1 = null; BlockDevInfo bd2 = null; if (hostDiskMap == null) { continue; } for (String hostName : hostDiskMap.keySet()) { if (!cluster.contains(hostName)) { continue; } final String disk = hostDiskMap.get(hostName); final BlockDevInfo bdi = drbdGraph.findBlockDevInfo(hostName, disk); if (bdi == null) { if (getDrbdDevHash().containsKey(disk)) { /* TODO: ignoring stacked device */ putDrbdDevHash(); continue; } else { putDrbdDevHash(); Tools.appWarning("could not find disk: " + disk + " on host: " + hostName); continue; } } bdi.setParameters(resName); if (bd1 == null) { bd1 = bdi; } else { bd2 = bdi; } } if (bd1 != null && bd2 != null) { /* add DRBD resource */ DrbdResourceInfo dri = getDrbdResHash().get(resName); putDrbdResHash(); if (dri == null) { dri = drbdInfo.addDrbdResource(resName, testOnly); atLeastOneAdded = true; } dri.setParameters(); DrbdVolumeInfo dvi = dri.getDrbdVolumeInfo(volumeNr); if (dvi == null) { dvi = drbdInfo.addDrbdVolume( dri, volumeNr, drbdDev, new ArrayList<BlockDevInfo>( Arrays.asList(bd1, bd2)), testOnly); atLeastOneAdded = true; } dvi.setParameters(); } } if (atLeastOneAdded) { drbdInfo.getInfoPanel(); Tools.invokeAndWait(new Runnable() { @Override public void run() { drbdInfo.setAllApplyButtons(); } }); drbdInfo.reloadDRBDResourceComboBoxes(); SwingUtilities.invokeLater(new Runnable() { public void run() { drbdGraph.scale(); } }); } }"
Inversion-Mutation
megadiff
"public <T> Future<T> push(final String channel, final T t) { String data = toJSON(t); final Future<?> f = broadcaster.addBroadcasterListener(new BroadcasterListener() { public void onPostCreate(Broadcaster broadcaster) { } public void onComplete(Broadcaster b) { for (PushContextListener p: listeners) { p.onComplete(channel, t); } b.removeBroadcasterListener(this); } public void onPreDestroy(Broadcaster broadcaster) { } }).broadcastTo(channel, data); return new WrappedFuture(f, t); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "push"
"public <T> Future<T> push(final String channel, final T t) { String data = toJSON(t); final Future<?> f = broadcaster.addBroadcasterListener(new BroadcasterListener() { public void onPostCreate(Broadcaster broadcaster) { } public void onComplete(Broadcaster b) { for (PushContextListener p: listeners) { p.onComplete(channel, t); <MASK>b.removeBroadcasterListener(this);</MASK> } } public void onPreDestroy(Broadcaster broadcaster) { } }).broadcastTo(channel, data); return new WrappedFuture(f, t); }"
Inversion-Mutation
megadiff
"public void onComplete(Broadcaster b) { for (PushContextListener p: listeners) { p.onComplete(channel, t); } b.removeBroadcasterListener(this); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onComplete"
"public void onComplete(Broadcaster b) { for (PushContextListener p: listeners) { p.onComplete(channel, t); <MASK>b.removeBroadcasterListener(this);</MASK> } }"
Inversion-Mutation
megadiff
"private void aniDBInfoReply(int queryId) { //System.out.println("Got Fileinfo reply"); Query query = api.Queries().get(queryId); int replyId = query.getReply().ReplyId(); int fileId = Integer.parseInt(query.getReply().Tag()); if (!files.contains("Id", fileId)) { return; //File not found (Todo: throw error) } FileInfo procFile = files.get("Id", fileId); procFile.ActionsTodo().remove(eAction.FileCmd); if (replyId == 320 || replyId == 505 || replyId == 322) { procFile.ActionsError().add(eAction.FileCmd); Log(ComEvent.eType.Information, eComType.FileEvent,replyId==320?eComSubType.FileCmd_NotFound:eComSubType.FileCmd_Error, procFile.Id()); } else { procFile.ActionsDone().add(eAction.FileCmd); ArrayDeque<String> df = new ArrayDeque<String>(query.getReply().DataField()); procFile.Data().put("DB_FId", df.poll()); procFile.Data().put("DB_AId", df.poll()); procFile.Data().put("DB_EId", df.poll()); procFile.Data().put("DB_GId", df.poll()); procFile.Data().put("DB_LId", df.poll()); procFile.Data().put("DB_Deprecated", df.poll()); procFile.Data().put("DB_State", df.poll()); procFile.Data().put("DB_CRC", df.poll()); procFile.Data().put("DB_Quality", df.poll()); procFile.Data().put("DB_VideoRes", df.poll()); procFile.Data().put("DB_Source", df.poll()); procFile.Data().put("DB_FileName", df.poll()); procFile.Data().put("DB_EpCount", df.poll()); procFile.Data().put("DB_EpHiCount", df.poll()); procFile.Data().put("DB_Year", df.poll()); procFile.Data().put("DB_Type", df.poll()); procFile.Data().put("DB_SN_Romaji", df.poll()); procFile.Data().put("DB_SN_Kanji", df.poll()); procFile.Data().put("DB_SN_English", df.poll()); procFile.Data().put("DB_SN_Other", df.poll()); procFile.Data().put("DB_SN_Short", df.poll()); procFile.Data().put("DB_SN_Synonym", df.poll()); procFile.Data().put("DB_EpNo", df.poll()); procFile.Data().put("DB_EpN_English", df.poll()); procFile.Data().put("DB_EpN_Romaji", df.poll()); procFile.Data().put("DB_EpN_Kanji", df.poll()); procFile.Data().put("DB_Group_Long", df.poll()); procFile.Data().put("DB_Group_Short", df.poll()); Log(ComEvent.eType.Information, eComType.FileEvent, eComSubType.FileCmd_GotInfo, procFile.Id()); } if (!procFile.IsFinal() && !(procFile.ActionsTodo().contains(eAction.FileCmd) || (procFile.ActionsTodo().contains(eAction.MyListCmd)))) { finalProcessing(procFile); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "aniDBInfoReply"
"private void aniDBInfoReply(int queryId) { //System.out.println("Got Fileinfo reply"); Query query = api.Queries().get(queryId); int replyId = query.getReply().ReplyId(); int fileId = Integer.parseInt(query.getReply().Tag()); if (!files.contains("Id", fileId)) { return; //File not found (Todo: throw error) } FileInfo procFile = files.get("Id", fileId); procFile.ActionsTodo().remove(eAction.FileCmd); if (replyId == 320 || replyId == 505 || replyId == 322) { procFile.ActionsError().add(eAction.FileCmd); Log(ComEvent.eType.Information, eComType.FileEvent,replyId==320?eComSubType.FileCmd_NotFound:eComSubType.FileCmd_Error, procFile.Id()); } else { procFile.ActionsDone().add(eAction.FileCmd); ArrayDeque<String> df = new ArrayDeque<String>(query.getReply().DataField()); procFile.Data().put("DB_FId", df.poll()); procFile.Data().put("DB_AId", df.poll()); procFile.Data().put("DB_EId", df.poll()); procFile.Data().put("DB_GId", df.poll()); procFile.Data().put("DB_LId", df.poll()); procFile.Data().put("DB_Deprecated", df.poll()); procFile.Data().put("DB_State", df.poll()); procFile.Data().put("DB_Quality", df.poll()); procFile.Data().put("DB_VideoRes", df.poll()); <MASK>procFile.Data().put("DB_CRC", df.poll());</MASK> procFile.Data().put("DB_Source", df.poll()); procFile.Data().put("DB_FileName", df.poll()); procFile.Data().put("DB_EpCount", df.poll()); procFile.Data().put("DB_EpHiCount", df.poll()); procFile.Data().put("DB_Year", df.poll()); procFile.Data().put("DB_Type", df.poll()); procFile.Data().put("DB_SN_Romaji", df.poll()); procFile.Data().put("DB_SN_Kanji", df.poll()); procFile.Data().put("DB_SN_English", df.poll()); procFile.Data().put("DB_SN_Other", df.poll()); procFile.Data().put("DB_SN_Short", df.poll()); procFile.Data().put("DB_SN_Synonym", df.poll()); procFile.Data().put("DB_EpNo", df.poll()); procFile.Data().put("DB_EpN_English", df.poll()); procFile.Data().put("DB_EpN_Romaji", df.poll()); procFile.Data().put("DB_EpN_Kanji", df.poll()); procFile.Data().put("DB_Group_Long", df.poll()); procFile.Data().put("DB_Group_Short", df.poll()); Log(ComEvent.eType.Information, eComType.FileEvent, eComSubType.FileCmd_GotInfo, procFile.Id()); } if (!procFile.IsFinal() && !(procFile.ActionsTodo().contains(eAction.FileCmd) || (procFile.ActionsTodo().contains(eAction.MyListCmd)))) { finalProcessing(procFile); } }"
Inversion-Mutation
megadiff
"private static void render() { // Reset any changes made to the model-view matrix. glLoadIdentity(); // Apply the camera position and orientation to the model-view matrix. camera.applyTranslations(); // Clear the screen. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Store the current attribute state. glPushAttrib(GL_ALL_ATTRIB_BITS); { generateTextureCoordinates(); drawGround(); drawShadowCastingObjects(); generateShadowMap(); } // Restore the previous attribute state. glPopAttrib(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "render"
"private static void render() { // Reset any changes made to the model-view matrix. glLoadIdentity(); // Apply the camera position and orientation to the model-view matrix. camera.applyTranslations(); // Clear the screen. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Store the current attribute state. glPushAttrib(GL_ALL_ATTRIB_BITS); { generateTextureCoordinates(); drawShadowCastingObjects(); generateShadowMap(); <MASK>drawGround();</MASK> } // Restore the previous attribute state. glPopAttrib(); }"
Inversion-Mutation
megadiff
"private void writeTo(@Nonnull String path) throws IOException { RandomAccessFile raf = new RandomAccessFile(path, "rw"); try { int dataSectionOffset = getDataSectionOffset(); DexWriter headerWriter = outputAt(raf, 0); DexWriter indexWriter = outputAt(raf, HeaderItem.HEADER_ITEM_SIZE); DexWriter offsetWriter = outputAt(raf, dataSectionOffset); try { stringPool.write(indexWriter, offsetWriter); typePool.write(indexWriter); typeListPool.write(offsetWriter); protoPool.write(indexWriter); fieldPool.write(indexWriter); methodPool.write(indexWriter); encodedArrayPool.write(offsetWriter); annotationPool.write(offsetWriter); annotationSetPool.write(offsetWriter); annotationSetRefPool.write(offsetWriter); annotationDirectoryPool.write(offsetWriter); debugInfoPool.write(offsetWriter); codeItemPool.write(offsetWriter); classDefPool.write(indexWriter, offsetWriter); mapItem.write(offsetWriter); headerItem.write(headerWriter, dataSectionOffset, offsetWriter.getPosition()); } finally { headerWriter.close(); indexWriter.close(); offsetWriter.close(); } FileChannel fileChannel = raf.getChannel(); headerItem.updateSignature(fileChannel); headerItem.updateChecksum(fileChannel); } finally { raf.close(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "writeTo"
"private void writeTo(@Nonnull String path) throws IOException { RandomAccessFile raf = new RandomAccessFile(path, "rw"); try { int dataSectionOffset = getDataSectionOffset(); DexWriter headerWriter = outputAt(raf, 0); DexWriter indexWriter = outputAt(raf, HeaderItem.HEADER_ITEM_SIZE); DexWriter offsetWriter = outputAt(raf, dataSectionOffset); try { stringPool.write(indexWriter, offsetWriter); typePool.write(indexWriter); <MASK>fieldPool.write(indexWriter);</MASK> typeListPool.write(offsetWriter); protoPool.write(indexWriter); methodPool.write(indexWriter); encodedArrayPool.write(offsetWriter); annotationPool.write(offsetWriter); annotationSetPool.write(offsetWriter); annotationSetRefPool.write(offsetWriter); annotationDirectoryPool.write(offsetWriter); debugInfoPool.write(offsetWriter); codeItemPool.write(offsetWriter); classDefPool.write(indexWriter, offsetWriter); mapItem.write(offsetWriter); headerItem.write(headerWriter, dataSectionOffset, offsetWriter.getPosition()); } finally { headerWriter.close(); indexWriter.close(); offsetWriter.close(); } FileChannel fileChannel = raf.getChannel(); headerItem.updateSignature(fileChannel); headerItem.updateChecksum(fileChannel); } finally { raf.close(); } }"
Inversion-Mutation
megadiff
"public ImageAnimationTest(int num, int size) throws VisADException, RemoteException { // (Time -> ((x, y) -> val)) RealTupleType pxl = new RealTupleType(RealType.getRealType("x"), RealType.getRealType("y")); FunctionType pxlVal = new FunctionType(pxl, RealType.getRealType("val")); FunctionType timePxlVal = new FunctionType(RealType.Time, pxlVal); System.err.println(timePxlVal.toString()); Field timeFld = new FieldImpl(timePxlVal, new Integer1DSet(RealType.Time, num)); float[][] samples = makeSamples(size, num); for (int i = 0; i < samples.length; i++) { Linear2DSet imgSet = new Linear2DSet(pxlVal.getDomain(), 0, size - 1, size, 0, size - 1, size); FlatField imgFld = new FlatField(pxlVal, imgSet); imgFld.setSamples(new float[][]{samples[i]}); // set image for time timeFld.setSample(i, imgFld); } DataReference ref = new DataReferenceImpl("image"); ref.setData(timeFld); DisplayImpl display = new DisplayImplJ3D("image display"); ImageRendererJ3D imgRend = new ImageRendererJ3D(); System.err.println("Renderer:"+imgRend.toString()); display.addMap(new ScalarMap(RealType.getRealType("x"), Display.XAxis)); display.addMap(new ScalarMap(RealType.getRealType("y"), Display.YAxis)); display.addMap(new ScalarMap(RealType.getRealType("val"), Display.RGBA)); ScalarMap aniMap = new ScalarMap(RealType.Time, Display.Animation); display.addMap(aniMap); AnimationControl aniCtrl = (AnimationControl) aniMap.getControl(); aniCtrl.setStep(1000); aniCtrl.setOn(true); display.addReferences(imgRend, ref); setLayout(new BorderLayout()); add(display.getComponent()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } BranchGroup scene = ((DisplayRendererJ3D) imgRend.getDisplayRenderer()).getRoot(); Util.printSceneGraph(scene); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "ImageAnimationTest"
"public ImageAnimationTest(int num, int size) throws VisADException, RemoteException { // (Time -> ((x, y) -> val)) RealTupleType pxl = new RealTupleType(RealType.getRealType("x"), RealType.getRealType("y")); FunctionType pxlVal = new FunctionType(pxl, RealType.getRealType("val")); FunctionType timePxlVal = new FunctionType(RealType.Time, pxlVal); System.err.println(timePxlVal.toString()); Field timeFld = new FieldImpl(timePxlVal, new Integer1DSet(RealType.Time, num)); float[][] samples = makeSamples(size, num); for (int i = 0; i < samples.length; i++) { Linear2DSet imgSet = new Linear2DSet(pxlVal.getDomain(), 0, size - 1, size, 0, size - 1, size); FlatField imgFld = new FlatField(pxlVal, imgSet); imgFld.setSamples(new float[][]{samples[i]}); // set image for time timeFld.setSample(i, imgFld); } DataReference ref = new DataReferenceImpl("image"); ref.setData(timeFld); DisplayImpl display = new DisplayImplJ3D("image display"); ImageRendererJ3D imgRend = new ImageRendererJ3D(); System.err.println("Renderer:"+imgRend.toString()); <MASK>display.addReferences(imgRend, ref);</MASK> display.addMap(new ScalarMap(RealType.getRealType("x"), Display.XAxis)); display.addMap(new ScalarMap(RealType.getRealType("y"), Display.YAxis)); display.addMap(new ScalarMap(RealType.getRealType("val"), Display.RGBA)); ScalarMap aniMap = new ScalarMap(RealType.Time, Display.Animation); display.addMap(aniMap); AnimationControl aniCtrl = (AnimationControl) aniMap.getControl(); aniCtrl.setStep(1000); aniCtrl.setOn(true); setLayout(new BorderLayout()); add(display.getComponent()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } BranchGroup scene = ((DisplayRendererJ3D) imgRend.getDisplayRenderer()).getRoot(); Util.printSceneGraph(scene); }"
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
"protected final void endLoop() { System.out.print(String.format(" \rdone: %s/%s in %s - %d/%d files done - %sBps - %d transfer(s) running.", Size.getReadableSize(doneTransfer()), prettyWholeSize(), FriendlyTime.elaspeTime(tick() / 10 + 1), nbDone(), nbFiles(), Size.getReadableSize(getBnd()), nbRunning())); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "endLoop"
"protected final void endLoop() { System.out.print(String.format(" \rdone: %s/%s in %s - %d/%d files done - %sBps - %d transfer(s) running.", Size.getReadableSize(doneTransfer()), <MASK>FriendlyTime.elaspeTime(tick() / 10 + 1),</MASK> prettyWholeSize(), nbDone(), nbFiles(), Size.getReadableSize(getBnd()), nbRunning())); }"
Inversion-Mutation
megadiff
"public void connect(BotConnectionSettings e) throws NickAlreadyInUseException, IOException, IrcException { if (this.isConnected()) { return; } this.bot.connect(e.getHostName(), e.getPort()); this.bot.sendMessage("nickserv", "ghost " + e.getNickName() + " " + e.getIdentity()); this.bot.changeNick(e.getNickName()); this.bot.identify(e.getIdentity()); this.joinChannels(e.getChannels()); this.recent = e; this.sendRawCommand("MODE " + e.getNickName() + " " + e.getModes()); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "connect"
"public void connect(BotConnectionSettings e) throws NickAlreadyInUseException, IOException, IrcException { if (this.isConnected()) { return; } this.bot.connect(e.getHostName(), e.getPort()); <MASK>this.bot.changeNick(e.getNickName());</MASK> this.bot.sendMessage("nickserv", "ghost " + e.getNickName() + " " + e.getIdentity()); this.bot.identify(e.getIdentity()); this.joinChannels(e.getChannels()); this.recent = e; this.sendRawCommand("MODE " + e.getNickName() + " " + e.getModes()); }"
Inversion-Mutation
megadiff
"@Override protected void onBindDialogView(View view) { super.onBindDialogView(view); mSeekBar = getSeekBar(view); mSeekBar.setMax(MAXIMUM_BACKLIGHT - MINIMUM_BACKLIGHT); try { mOldBrightness = Settings.System.getInt(getContext().getContentResolver(), Settings.System.SCREEN_BRIGHTNESS); } catch (SettingNotFoundException snfe) { mOldBrightness = MAXIMUM_BACKLIGHT; } mSeekBar.setProgress(mOldBrightness - MINIMUM_BACKLIGHT); mCheckBox = (CheckBox)view.findViewById(R.id.automatic_mode); if (mAutomaticAvailable) { mCheckBox.setOnCheckedChangeListener(this); try { mOldAutomatic = Settings.System.getInt(getContext().getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE); } catch (SettingNotFoundException snfe) { mOldAutomatic = 0; } mCheckBox.setChecked(mOldAutomatic != 0); } else { mCheckBox.setVisibility(View.GONE); } mSeekBar.setOnSeekBarChangeListener(this); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onBindDialogView"
"@Override protected void onBindDialogView(View view) { super.onBindDialogView(view); mSeekBar = getSeekBar(view); <MASK>mSeekBar.setOnSeekBarChangeListener(this);</MASK> mSeekBar.setMax(MAXIMUM_BACKLIGHT - MINIMUM_BACKLIGHT); try { mOldBrightness = Settings.System.getInt(getContext().getContentResolver(), Settings.System.SCREEN_BRIGHTNESS); } catch (SettingNotFoundException snfe) { mOldBrightness = MAXIMUM_BACKLIGHT; } mSeekBar.setProgress(mOldBrightness - MINIMUM_BACKLIGHT); mCheckBox = (CheckBox)view.findViewById(R.id.automatic_mode); if (mAutomaticAvailable) { mCheckBox.setOnCheckedChangeListener(this); try { mOldAutomatic = Settings.System.getInt(getContext().getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE); } catch (SettingNotFoundException snfe) { mOldAutomatic = 0; } mCheckBox.setChecked(mOldAutomatic != 0); } else { mCheckBox.setVisibility(View.GONE); } }"
Inversion-Mutation
megadiff
"@Nonnull public static ImmutableStartLocal of(@Nonnull StartLocal startLocal) { if (startLocal instanceof ImmutableStartLocal) { return (ImmutableStartLocal)startLocal; } return new ImmutableStartLocal( startLocal.getCodeAddress(), startLocal.getRegister(), startLocal.getName(), startLocal.getType(), startLocal.getSignature()); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "of"
"@Nonnull public static ImmutableStartLocal of(@Nonnull StartLocal startLocal) { if (startLocal instanceof ImmutableStartLocal) { return (ImmutableStartLocal)startLocal; } return new ImmutableStartLocal( startLocal.getCodeAddress(), startLocal.getRegister(), <MASK>startLocal.getType(),</MASK> startLocal.getName(), startLocal.getSignature()); }"
Inversion-Mutation
megadiff
"public ArrayList<SearchResult> find(String query) throws ControllerException { ArrayList<SearchResult> results = new ArrayList<SearchResult>(); if (query == null) { return results; } String cleanedQuery = query.replace(":", " "); cleanedQuery = cleanedQuery.replace("\\", " "); cleanedQuery = cleanedQuery.replace("[", "\\["); cleanedQuery = cleanedQuery.replace("]", "\\]"); cleanedQuery = cleanedQuery.replace("{", "\\{"); cleanedQuery = cleanedQuery.replace("}", "\\}"); cleanedQuery = cleanedQuery.replace("(", "\\("); cleanedQuery = cleanedQuery.replace(")", "\\)"); cleanedQuery = cleanedQuery.replace("+", "\\+"); cleanedQuery = cleanedQuery.replace("-", "\\-"); cleanedQuery = cleanedQuery.replace("'", "\\'"); cleanedQuery = cleanedQuery.replace("\"", "\\\""); cleanedQuery = cleanedQuery.replace("^", "\\^"); cleanedQuery = cleanedQuery.replace("&", "\\&"); cleanedQuery = (cleanedQuery.endsWith("\\") ? cleanedQuery.substring(0, cleanedQuery.length() - 1) : cleanedQuery); if (cleanedQuery.startsWith("*")) { cleanedQuery = cleanedQuery.substring(1); } if (cleanedQuery.startsWith("?")) { cleanedQuery = cleanedQuery.substring(1); } try { UsageLogger.info(String.format("Searching for: %s", cleanedQuery)); EntryController entryController = new EntryController(getAccount()); ArrayList<SearchResult> searchResults = AggregateSearch.query(cleanedQuery, getAccount()); if (searchResults != null) { for (SearchResult searchResult : searchResults) { Entry entry = searchResult.getEntry(); if (entryController.hasReadPermission(entry)) { results.add(searchResult); } } } UsageLogger.info(String.format("%d visible results found", (results == null) ? 0 : results.size())); } catch (SearchException e) { throw new ControllerException(e); } return results; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "find"
"public ArrayList<SearchResult> find(String query) throws ControllerException { ArrayList<SearchResult> results = new ArrayList<SearchResult>(); if (query == null) { return results; } String cleanedQuery = query.replace(":", " "); cleanedQuery = cleanedQuery.replace("[", "\\["); cleanedQuery = cleanedQuery.replace("]", "\\]"); cleanedQuery = cleanedQuery.replace("{", "\\{"); cleanedQuery = cleanedQuery.replace("}", "\\}"); cleanedQuery = cleanedQuery.replace("(", "\\("); cleanedQuery = cleanedQuery.replace(")", "\\)"); cleanedQuery = cleanedQuery.replace("+", "\\+"); cleanedQuery = cleanedQuery.replace("-", "\\-"); cleanedQuery = cleanedQuery.replace("'", "\\'"); cleanedQuery = cleanedQuery.replace("\"", "\\\""); cleanedQuery = cleanedQuery.replace("^", "\\^"); cleanedQuery = cleanedQuery.replace("&", "\\&"); <MASK>cleanedQuery = cleanedQuery.replace("\\", " ");</MASK> cleanedQuery = (cleanedQuery.endsWith("\\") ? cleanedQuery.substring(0, cleanedQuery.length() - 1) : cleanedQuery); if (cleanedQuery.startsWith("*")) { cleanedQuery = cleanedQuery.substring(1); } if (cleanedQuery.startsWith("?")) { cleanedQuery = cleanedQuery.substring(1); } try { UsageLogger.info(String.format("Searching for: %s", cleanedQuery)); EntryController entryController = new EntryController(getAccount()); ArrayList<SearchResult> searchResults = AggregateSearch.query(cleanedQuery, getAccount()); if (searchResults != null) { for (SearchResult searchResult : searchResults) { Entry entry = searchResult.getEntry(); if (entryController.hasReadPermission(entry)) { results.add(searchResult); } } } UsageLogger.info(String.format("%d visible results found", (results == null) ? 0 : results.size())); } catch (SearchException e) { throw new ControllerException(e); } return results; }"
Inversion-Mutation
megadiff
"public String getChartUrl(List<SelectableTelemetryStream> streams) { GoogleChart googleChart = new GoogleChart(ChartType.LINE, this.getWidth(), this.getHeight()); Map<String, TelemetryStreamYAxis> streamAxisMap = new HashMap<String, TelemetryStreamYAxis>(); //combine streams Y axes. for (SelectableTelemetryStream stream : streams) { if (stream.isEmpty()) { continue; } double streamMax = stream.getMaximum(); double streamMin = stream.getMinimum(); String streamUnitName = stream.getUnitName(); TelemetryStreamYAxis axis = streamAxisMap.get(streamUnitName); if (axis == null) { axis = newYAxis(streamUnitName, streamMax, streamMin); streamAxisMap.put(streamUnitName, axis); } else { double axisMax = axis.getMaximum(); double axisMin = axis.getMinimum(); axis.setMaximum((axisMax > streamMax) ? axisMax : streamMax); axis.setMinimum((axisMin < streamMin) ? axisMin : streamMin); } } //add the y axis and extend the range if it contains only one horizontal line. for (TelemetryStreamYAxis axis : streamAxisMap.values()) { String axisType = "r"; if (googleChart.isYAxisEmpty()) { axisType = "y"; } List<Double> rangeList = new ArrayList<Double>(); //extend the range of the axis if it contains only one vertical straight line. if (axis.getMaximum() - axis.getMinimum() < 0.1) { axis.setMaximum(axis.getMaximum() + 1.0); axis.setMinimum(axis.getMinimum() - 1.0); } rangeList.add(axis.getMinimum()); rangeList.add(axis.getMaximum()); //add the axis to the chart. googleChart.addAxisRange(axisType, rangeList, axis.getColor()); } //add streams to the chart. for (int i = 0; i < streams.size(); ++i) { SelectableTelemetryStream stream = streams.get(i); if (!stream.isEmpty()) { stream.setColor(streamAxisMap.get(stream.getUnitName()).getColor()); TelemetryStreamYAxis axis = streamAxisMap.get(stream.getUnitName()); this.addStreamToChart(stream, axis.getMinimum(), axis.getMaximum(), googleChart); } } //add the x axis. if (!streams.isEmpty()) { googleChart.addAxisLabel("x", getDateList(streams.get(0).getTelemetryStream().getTelemetryPoint()), ""); } return googleChart.getUrl(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getChartUrl"
"public String getChartUrl(List<SelectableTelemetryStream> streams) { GoogleChart googleChart = new GoogleChart(ChartType.LINE, this.getWidth(), this.getHeight()); Map<String, TelemetryStreamYAxis> streamAxisMap = new HashMap<String, TelemetryStreamYAxis>(); //combine streams Y axes. for (SelectableTelemetryStream stream : streams) { if (stream.isEmpty()) { continue; } double streamMax = stream.getMaximum(); double streamMin = stream.getMinimum(); String streamUnitName = stream.getUnitName(); TelemetryStreamYAxis axis = streamAxisMap.get(streamUnitName); if (axis == null) { axis = newYAxis(streamUnitName, streamMax, streamMin); streamAxisMap.put(streamUnitName, axis); } else { double axisMax = axis.getMaximum(); double axisMin = axis.getMinimum(); axis.setMaximum((axisMax > streamMax) ? axisMax : streamMax); axis.setMinimum((axisMin < streamMin) ? axisMin : streamMin); } } //add the y axis and extend the range if it contains only one horizontal line. for (TelemetryStreamYAxis axis : streamAxisMap.values()) { String axisType = "r"; if (googleChart.isYAxisEmpty()) { axisType = "y"; } List<Double> rangeList = new ArrayList<Double>(); //extend the range of the axis if it contains only one vertical straight line. if (axis.getMaximum() - axis.getMinimum() < 0.1) { axis.setMaximum(axis.getMaximum() + 1.0); axis.setMinimum(axis.getMinimum() - 1.0); } rangeList.add(axis.getMinimum()); rangeList.add(axis.getMaximum()); //add the axis to the chart. googleChart.addAxisRange(axisType, rangeList, axis.getColor()); } //add streams to the chart. for (int i = 0; i < streams.size(); ++i) { SelectableTelemetryStream stream = streams.get(i); <MASK>stream.setColor(streamAxisMap.get(stream.getUnitName()).getColor());</MASK> if (!stream.isEmpty()) { TelemetryStreamYAxis axis = streamAxisMap.get(stream.getUnitName()); this.addStreamToChart(stream, axis.getMinimum(), axis.getMaximum(), googleChart); } } //add the x axis. if (!streams.isEmpty()) { googleChart.addAxisLabel("x", getDateList(streams.get(0).getTelemetryStream().getTelemetryPoint()), ""); } return googleChart.getUrl(); }"
Inversion-Mutation
megadiff
"@Override public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException { //update map currentCell = MapLoader.getCurrentCell(); //check input Input input = gc.getInput(); if (input.isKeyPressed(Input.KEY_ESCAPE)){ if(gui.anyWindowOpen()){ gui.closeWindow(); }else{ gc.sleep(300); music.release(); Sounds.releaseSounds(); gc.exit(); } } if(!gui.anyWindowOpen()){ currentCell.updateEntities(gc, sbg, delta); world.step(delta/1000f, 8, 3); } gui.update(gc, sbg, delta); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "update"
"@Override public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException { //update map currentCell = MapLoader.getCurrentCell(); //check input Input input = gc.getInput(); if (input.isKeyPressed(Input.KEY_ESCAPE)){ if(gui.anyWindowOpen()){ gui.closeWindow(); }else{ gc.sleep(300); music.release(); Sounds.releaseSounds(); gc.exit(); } } if(!gui.anyWindowOpen()){ currentCell.updateEntities(gc, sbg, delta); world.step(delta/1000f, 8, 3); <MASK>gui.update(gc, sbg, delta);</MASK> } }"
Inversion-Mutation
megadiff
"public ThermoData generateThermoData() throws FailGenerateThermoDataException { TDGenerator gen = null; ChemGraph thermo_graph = null; try { thermo_graph = ChemGraph.copy(this); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical(e.getMessage()); System.exit(0); } thermo_graph.determineAromaticityAndWriteBBonds(); if (thermo_graph.isAromatic){ this.isAromatic = true; } //System.out.println(thermo_graph.toString()); if (TDMETHOD.toLowerCase().startsWith("benson")) { gen = new BensonTDGenerator(); } else if (TDMETHOD.toLowerCase().startsWith("qm")) { gen = new QMForCyclicsGenerator(); } else {// default method is hybrid gen = new HybridTDGenerator(); } thermoData = gen.generateThermo(this); if(!this.fromprimarythermolibrary && this.isAromatic) { thermoData = gen.generateThermo(thermo_graph); this.thermoComments = thermo_graph.getThermoComments(); // must copy comments since we made a copy of the chemgraph } if(thermo_graph.fromprimarythermolibrary) { this.fromprimarythermolibrary = true;} return thermoData; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "generateThermoData"
"public ThermoData generateThermoData() throws FailGenerateThermoDataException { TDGenerator gen = null; ChemGraph thermo_graph = null; try { thermo_graph = ChemGraph.copy(this); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical(e.getMessage()); System.exit(0); } thermo_graph.determineAromaticityAndWriteBBonds(); if (thermo_graph.isAromatic){ this.isAromatic = true; } //System.out.println(thermo_graph.toString()); if (TDMETHOD.toLowerCase().startsWith("benson")) { gen = new BensonTDGenerator(); } else if (TDMETHOD.toLowerCase().startsWith("qm")) { gen = new QMForCyclicsGenerator(); } else {// default method is hybrid gen = new HybridTDGenerator(); } thermoData = gen.generateThermo(this); if(!this.fromprimarythermolibrary && this.isAromatic) { thermoData = gen.generateThermo(thermo_graph); } if(thermo_graph.fromprimarythermolibrary) { this.fromprimarythermolibrary = true;} <MASK>this.thermoComments = thermo_graph.getThermoComments(); // must copy comments since we made a copy of the chemgraph</MASK> return thermoData; }"
Inversion-Mutation
megadiff
"public XMLObject unmarshall(Element domElement) throws UnmarshallingException { if (log.isDebugEnabled()) { log.debug("Starting to unmarshall DOM element " + XMLHelper.getNodeQName(domElement)); } checkElementIsTarget(domElement); XMLObject xmlObject = buildXMLObject(domElement); if (log.isDebugEnabled()) { log.debug("Unmarshalling attributes of DOM Element " + XMLHelper.getNodeQName(domElement)); } NamedNodeMap attributes = domElement.getAttributes(); Node attribute; for (int i = 0; i < attributes.getLength(); i++) { attribute = attributes.item(i); // These should allows be attribute nodes, but just in case... if (attribute.getNodeType() == Node.ATTRIBUTE_NODE) { unmarshallAttribute(xmlObject, (Attr) attribute); } } if (log.isDebugEnabled()) { log.debug("Unmarshalling other child nodes of DOM Element " + XMLHelper.getNodeQName(domElement)); } NodeList childNodes = domElement.getChildNodes(); Node childNode; for (int i = 0; i < childNodes.getLength(); i++) { childNode = childNodes.item(i); if (childNode.getNodeType() == Node.ATTRIBUTE_NODE) { unmarshallAttribute(xmlObject, (Attr) childNode); } else if (childNode.getNodeType() == Node.ELEMENT_NODE) { unmarshallChildElement(xmlObject, (Element) childNode); } else if (childNode.getNodeType() == Node.TEXT_NODE) { unmarshallTextContent(xmlObject, (Text) childNode); } } xmlObject.setDOM(domElement); return xmlObject; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "unmarshall"
"public XMLObject unmarshall(Element domElement) throws UnmarshallingException { if (log.isDebugEnabled()) { log.debug("Starting to unmarshall DOM element " + XMLHelper.getNodeQName(domElement)); } checkElementIsTarget(domElement); XMLObject xmlObject = buildXMLObject(domElement); <MASK>xmlObject.setDOM(domElement);</MASK> if (log.isDebugEnabled()) { log.debug("Unmarshalling attributes of DOM Element " + XMLHelper.getNodeQName(domElement)); } NamedNodeMap attributes = domElement.getAttributes(); Node attribute; for (int i = 0; i < attributes.getLength(); i++) { attribute = attributes.item(i); // These should allows be attribute nodes, but just in case... if (attribute.getNodeType() == Node.ATTRIBUTE_NODE) { unmarshallAttribute(xmlObject, (Attr) attribute); } } if (log.isDebugEnabled()) { log.debug("Unmarshalling other child nodes of DOM Element " + XMLHelper.getNodeQName(domElement)); } NodeList childNodes = domElement.getChildNodes(); Node childNode; for (int i = 0; i < childNodes.getLength(); i++) { childNode = childNodes.item(i); if (childNode.getNodeType() == Node.ATTRIBUTE_NODE) { unmarshallAttribute(xmlObject, (Attr) childNode); } else if (childNode.getNodeType() == Node.ELEMENT_NODE) { unmarshallChildElement(xmlObject, (Element) childNode); } else if (childNode.getNodeType() == Node.TEXT_NODE) { unmarshallTextContent(xmlObject, (Text) childNode); } } return xmlObject; }"
Inversion-Mutation
megadiff
"public boolean isBaseLevelForKey(Slice userKey) { // Maybe use binary search to find right entry instead of linear search? UserComparator userComparator = inputVersion.getInternalKeyComparator().getUserComparator(); for (int level = this.level + 2; level < NUM_LEVELS; level++) { List<FileMetaData> files = inputVersion.getFiles(level); while (levelPointers[level] < files.size()) { FileMetaData f = files.get(levelPointers[level]); if (userComparator.compare(userKey, f.getLargest().getUserKey()) <= 0) { // We've advanced far enough if (userComparator.compare(userKey, f.getSmallest().getUserKey()) >= 0) { // Key falls in this file's range, so definitely not base level return false; } break; } levelPointers[level]++; } } return true; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "isBaseLevelForKey"
"public boolean isBaseLevelForKey(Slice userKey) { // Maybe use binary search to find right entry instead of linear search? UserComparator userComparator = inputVersion.getInternalKeyComparator().getUserComparator(); for (int level = this.level + 2; level < NUM_LEVELS; level++) { List<FileMetaData> files = inputVersion.getFiles(level); while (levelPointers[level] < files.size()) { FileMetaData f = files.get(levelPointers[level]); if (userComparator.compare(userKey, f.getLargest().getUserKey()) <= 0) { // We've advanced far enough if (userComparator.compare(userKey, f.getSmallest().getUserKey()) >= 0) { // Key falls in this file's range, so definitely not base level return false; } break; } } <MASK>levelPointers[level]++;</MASK> } return true; }"
Inversion-Mutation
megadiff
"@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); /* * Setup view and adapter. */ setContentView(R.layout.realtime); realtimeList = new RealtimeAdapter(this); /* * Load instance state */ if (savedInstanceState == null) { station = getIntent().getParcelableExtra(SearchStationData.PARCELABLE); load(); } else { station = savedInstanceState.getParcelable(SearchStationData.PARCELABLE); final ArrayList<RealtimeData> list = savedInstanceState.getParcelableArrayList(RealtimeAdapter.KEY_REALTIMELIST); realtimeList.setList(list); } setTitle("Trafikanten - " + station.stopName); registerForContextMenu(getListView()); setListAdapter(realtimeList); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCreate"
"@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); /* * Setup view and adapter. */ setContentView(R.layout.realtime); realtimeList = new RealtimeAdapter(this); /* * Load instance state */ if (savedInstanceState == null) { station = getIntent().getParcelableExtra(SearchStationData.PARCELABLE); load(); } else { station = savedInstanceState.getParcelable(SearchStationData.PARCELABLE); final ArrayList<RealtimeData> list = savedInstanceState.getParcelableArrayList(RealtimeAdapter.KEY_REALTIMELIST); realtimeList.setList(list); <MASK>setListAdapter(realtimeList);</MASK> } setTitle("Trafikanten - " + station.stopName); registerForContextMenu(getListView()); }"
Inversion-Mutation
megadiff
"@Override protected int modify(IDocument document, AcceleoSourceContent content, int offset, int length) throws BadLocationException { String text = document.get(); int b = offset; int e = offset + length; while (b < e && Character.isWhitespace(text.charAt(b))) { b++; } while (e > b && Character.isWhitespace(text.charAt(e - 1))) { e--; } String paramName = "e"; //$NON-NLS-1$ CSTNode currentNode = content.getCSTNode(b, e); if (currentNode instanceof ModuleElement) { paramName = getCurrentVariableName(currentNode, paramName); } else if (currentNode != null) { currentNode = content.getCSTParent(currentNode, ModuleElement.class); if (currentNode instanceof ModuleElement) { paramName = getCurrentVariableName(currentNode, paramName); } } if (b == e) { while (b > 0 && text.charAt(b - 1) != '\n') { b--; } while (e < text.length() && text.charAt(e) != '\r' && text.charAt(e) != '\n') { e++; } } try { String prefix = "[protected]\n"; //$NON-NLS-1$ String suffix = "\n[/protected]\n"; //$NON-NLS-1$ document.replace(e, 0, suffix); document.replace(b, 0, prefix); return b + prefix.length(); } catch (BadLocationException ex) { return offset; } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "modify"
"@Override protected int modify(IDocument document, AcceleoSourceContent content, int offset, int length) throws BadLocationException { String text = document.get(); int b = offset; int e = offset + length; while (b < e && Character.isWhitespace(text.charAt(b))) { b++; } while (e > b && Character.isWhitespace(text.charAt(e - 1))) { e--; } String paramName = "e"; //$NON-NLS-1$ CSTNode currentNode = content.getCSTNode(b, e); if (currentNode instanceof ModuleElement) { paramName = getCurrentVariableName(currentNode, paramName); } else if (currentNode != null) { currentNode = content.getCSTParent(currentNode, ModuleElement.class); if (currentNode instanceof ModuleElement) { paramName = getCurrentVariableName(currentNode, paramName); } } if (b == e) { while (b > 0 && text.charAt(b - 1) != '\n') { b--; } while (e < text.length() && text.charAt(e) != '\r' && text.charAt(e) != '\n') { e++; } } try { String prefix = "[protected]\n"; //$NON-NLS-1$ String suffix = "\n[/protected]\n"; //$NON-NLS-1$ <MASK>document.replace(b, 0, prefix);</MASK> document.replace(e, 0, suffix); return b + prefix.length(); } catch (BadLocationException ex) { return offset; } }"
Inversion-Mutation
megadiff
"public static void main(String[] args) { settings = new Settings(); try { // Configure log system (overwrite if already exists) FileOutputStream logFile = new FileOutputStream("log.txt"); logStream = new PrintStream(logFile); LogSystem.out = logStream; LogSystem.consoleEcho = true; LogSystem logSystem = new LogSystem(); Log.setLogSystem(logSystem); // Create game game = new Game(title); // Create canvas canvas = new CanvasGameContainer2(game); canvas.setSize(defaultScreenWidth, defaultScreenHeight); canvas.setTopExceptionListener(new TopExceptionListener()); // Configure game container GameContainer gc = canvas.getGameContainer(); gc.setTargetFrameRate(settings.getTargetFramerate()); gc.setVSync(settings.isUseVSync()); gc.setSmoothDeltas(settings.isSmoothDeltasEnabled()); gc.setUpdateOnlyWhenVisible(true); // Create main window gameFrame = new JFrame(); gameFrame.setTitle(title); gameFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); gameFrame.addWindowListener(new MainFrameListener()); gameFrame.setVisible(true); // Note : frame borders are not available before the frame is shown // Setting frame size with content sized to default dimensions gameFrame.setSize( defaultScreenWidth + gameFrame.getInsets().left + gameFrame.getInsets().right, defaultScreenHeight + gameFrame.getInsets().top + gameFrame.getInsets().bottom); gameFrame.setLocationRelativeTo(null); // Add canvas to the content pane contentPane = gameFrame.getContentPane(); contentPane.addComponentListener(new MainComponentListener()); contentPane.add(canvas); canvas.start(); // Start the game } catch (Throwable t) { t.printStackTrace(); onCrash(t); } // FIXME on game close : "AL lib: alc_cleanup: 1 device not closed" (serious or not?) }"
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) { settings = new Settings(); try { // Configure log system (overwrite if already exists) FileOutputStream logFile = new FileOutputStream("log.txt"); logStream = new PrintStream(logFile); LogSystem.out = logStream; LogSystem.consoleEcho = true; LogSystem logSystem = new LogSystem(); Log.setLogSystem(logSystem); // Create game game = new Game(title); // Create canvas canvas = new CanvasGameContainer2(game); canvas.setSize(defaultScreenWidth, defaultScreenHeight); canvas.setTopExceptionListener(new TopExceptionListener()); // Configure game container GameContainer gc = canvas.getGameContainer(); gc.setTargetFrameRate(settings.getTargetFramerate()); gc.setVSync(settings.isUseVSync()); gc.setSmoothDeltas(settings.isSmoothDeltasEnabled()); gc.setUpdateOnlyWhenVisible(true); // Create main window gameFrame = new JFrame(); gameFrame.setTitle(title); gameFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); <MASK>gameFrame.setLocationRelativeTo(null);</MASK> gameFrame.addWindowListener(new MainFrameListener()); gameFrame.setVisible(true); // Note : frame borders are not available before the frame is shown // Setting frame size with content sized to default dimensions gameFrame.setSize( defaultScreenWidth + gameFrame.getInsets().left + gameFrame.getInsets().right, defaultScreenHeight + gameFrame.getInsets().top + gameFrame.getInsets().bottom); // Add canvas to the content pane contentPane = gameFrame.getContentPane(); contentPane.addComponentListener(new MainComponentListener()); contentPane.add(canvas); canvas.start(); // Start the game } catch (Throwable t) { t.printStackTrace(); onCrash(t); } // FIXME on game close : "AL lib: alc_cleanup: 1 device not closed" (serious or not?) }"
Inversion-Mutation
megadiff
"public void refresh() { try { update(); gui_.suspendLiveMode(); for (int i=0; i<propList_.size(); i++){ PropertyItem item = propList_.get(i); if (showDevice(flags_, item.device)) { item.setValueFromCoreString(core_.getProperty(item.device, item.name)); } } gui_.resumeLiveMode(); this.fireTableDataChanged(); } catch (Exception e) { handleException(e); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "refresh"
"public void refresh() { try { <MASK>gui_.suspendLiveMode();</MASK> update(); for (int i=0; i<propList_.size(); i++){ PropertyItem item = propList_.get(i); if (showDevice(flags_, item.device)) { item.setValueFromCoreString(core_.getProperty(item.device, item.name)); } } gui_.resumeLiveMode(); this.fireTableDataChanged(); } catch (Exception e) { handleException(e); } }"
Inversion-Mutation
megadiff
"@Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { mDrawerLayout.closeDrawer(mDrawerList); switch (((DrawerItem) parent.getItemAtPosition(position)).action) { default: case ACTION_LIBRARY: // If we are already on the library, pop the whole stack. Acts like an "up" button if (currentDisplayMode == DisplayMode.MODE_LIBRARY) { final int fmStackCount = fragmentManager.getBackStackEntryCount(); if (fmStackCount > 0) { fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); } } switchMode(DisplayMode.MODE_LIBRARY); break; case ACTION_NOWPLAYING: switchMode(DisplayMode.MODE_NOWPLAYING); break; case ACTION_OUTPUTS: mDrawerList.setItemChecked(oldDrawerPosition, true); final Intent i = new Intent(MainMenuActivity.this, SettingsActivity.class); i.putExtra(SettingsActivity.OPEN_OUTPUT, true); startActivityForResult(i, SETTINGS); break; } oldDrawerPosition = position; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onItemClick"
"@Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { mDrawerLayout.closeDrawer(mDrawerList); switch (((DrawerItem) parent.getItemAtPosition(position)).action) { default: case ACTION_LIBRARY: <MASK>switchMode(DisplayMode.MODE_LIBRARY);</MASK> // If we are already on the library, pop the whole stack. Acts like an "up" button if (currentDisplayMode == DisplayMode.MODE_LIBRARY) { final int fmStackCount = fragmentManager.getBackStackEntryCount(); if (fmStackCount > 0) { fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); } } break; case ACTION_NOWPLAYING: switchMode(DisplayMode.MODE_NOWPLAYING); break; case ACTION_OUTPUTS: mDrawerList.setItemChecked(oldDrawerPosition, true); final Intent i = new Intent(MainMenuActivity.this, SettingsActivity.class); i.putExtra(SettingsActivity.OPEN_OUTPUT, true); startActivityForResult(i, SETTINGS); break; } oldDrawerPosition = position; }"
Inversion-Mutation
megadiff
"private void stopCurrentDecorating() { if (currentDecorateTimer != null) { currentDecorateTimer.stop(); currentDecorateTimer = null; } removeDecoration(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "stopCurrentDecorating"
"private void stopCurrentDecorating() { if (currentDecorateTimer != null) { currentDecorateTimer.stop(); currentDecorateTimer = null; <MASK>removeDecoration();</MASK> } }"
Inversion-Mutation
megadiff
"public void actionPerformed(final ActionEvent e) { final String styleName = JOptionPane.showInputDialog(TextUtils.getText("enter_new_style_name")); if (styleName == null) { return; } final Controller controller = Controller.getCurrentController(); final NodeModel selectedNode = controller.getSelection().getSelected(); final MapModel map = controller.getMap(); final MapStyleModel styleModel = MapStyleModel.getExtension(map); final MapModel styleMap = styleModel.getStyleMap(); final IStyle newStyle = StyleFactory.create(styleName); if (null != styleModel.getStyleNode(newStyle)) { UITools.errorMessage(TextUtils.getText("style_already_exists")); return; } final MMapController mapController = (MMapController) Controller.getCurrentModeController().getMapController(); final NodeModel newNode = new NodeModel(styleMap); newNode.setUserObject(newStyle); final LogicalStyleController styleController = LogicalStyleController.getController(); final ArrayList<IStyle> styles = new ArrayList<IStyle>(styleController.getStyles(selectedNode)); for(int i = styles.size() - 1; i >= 0; i--){ IStyle style = styles.get(i); if(MapStyleModel.DEFAULT_STYLE.equals(style)){ continue; } final NodeModel styleNode = styleModel.getStyleNode(style); if(styleNode == null){ continue; } Controller.getCurrentModeController().copyExtensions(LogicalStyleKeys.NODE_STYLE, styleNode, newNode); } Controller.getCurrentModeController().copyExtensions(LogicalStyleKeys.NODE_STYLE, selectedNode, newNode); Controller.getCurrentModeController().copyExtensions(Keys.ICONS, selectedNode, newNode); mapController.insertNode(newNode, styleModel.getUserStyleParentNode(styleMap), false, false, true); mapController.select(newNode); final IActor actor = new IActor() { public void undo() { styleModel.removeStyleNode(newNode); styleController.refreshMap(map); } public String getDescription() { return "NewStyle"; } public void act() { styleModel.addStyleNode(newNode); styleController.refreshMap(map); } }; Controller.getCurrentModeController().execute(actor, styleMap); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "actionPerformed"
"public void actionPerformed(final ActionEvent e) { final String styleName = JOptionPane.showInputDialog(TextUtils.getText("enter_new_style_name")); if (styleName == null) { return; } final Controller controller = Controller.getCurrentController(); final NodeModel selectedNode = controller.getSelection().getSelected(); final MapModel map = controller.getMap(); final MapStyleModel styleModel = MapStyleModel.getExtension(map); final MapModel styleMap = styleModel.getStyleMap(); final IStyle newStyle = StyleFactory.create(styleName); if (null != styleModel.getStyleNode(newStyle)) { UITools.errorMessage(TextUtils.getText("style_already_exists")); return; } final MMapController mapController = (MMapController) Controller.getCurrentModeController().getMapController(); final NodeModel newNode = new NodeModel(styleMap); newNode.setUserObject(newStyle); final LogicalStyleController styleController = LogicalStyleController.getController(); final ArrayList<IStyle> styles = new ArrayList<IStyle>(styleController.getStyles(selectedNode)); for(int i = styles.size() - 1; i >= 0; i--){ IStyle style = styles.get(i); if(MapStyleModel.DEFAULT_STYLE.equals(style)){ continue; } final NodeModel styleNode = styleModel.getStyleNode(style); <MASK>Controller.getCurrentModeController().copyExtensions(LogicalStyleKeys.NODE_STYLE, styleNode, newNode);</MASK> if(styleNode == null){ continue; } } Controller.getCurrentModeController().copyExtensions(LogicalStyleKeys.NODE_STYLE, selectedNode, newNode); Controller.getCurrentModeController().copyExtensions(Keys.ICONS, selectedNode, newNode); mapController.insertNode(newNode, styleModel.getUserStyleParentNode(styleMap), false, false, true); mapController.select(newNode); final IActor actor = new IActor() { public void undo() { styleModel.removeStyleNode(newNode); styleController.refreshMap(map); } public String getDescription() { return "NewStyle"; } public void act() { styleModel.addStyleNode(newNode); styleController.refreshMap(map); } }; Controller.getCurrentModeController().execute(actor, styleMap); }"
Inversion-Mutation
megadiff
"protected void handleEvent(NuxeoWebappLoader loader, LifecycleEvent event) { try { ClassLoader cl = loader.getClassLoader(); boolean devMode = cl instanceof NuxeoDevWebappClassLoader; String type = event.getType(); if (type == Lifecycle.START_EVENT) { File homeDir = resolveHomeDirectory(loader); if (devMode) { bootstrap = new DevFrameworkBootstrap( (MutableClassLoader) cl, homeDir); MBeanServer server = ManagementFactory.getPlatformMBeanServer(); server.registerMBean(bootstrap, new ObjectName(DEV_BUNDLES_NAME)); server.registerMBean(cl, new ObjectName(WEB_RESOURCES_NAME)); ( (NuxeoDevWebappClassLoader)cl).setHome(new File(getHome())); } else { bootstrap = new FrameworkBootstrap( (MutableClassLoader) cl, homeDir); } bootstrap.setHostName("Tomcat"); bootstrap.setHostVersion("6.0.20"); bootstrap.initialize(); } else if (type == Lifecycle.AFTER_START_EVENT) { bootstrap.start(); } else if (type == Lifecycle.STOP_EVENT) { bootstrap.stop(); if (devMode) { MBeanServer server = ManagementFactory.getPlatformMBeanServer(); server.unregisterMBean(new ObjectName(DEV_BUNDLES_NAME)); server.unregisterMBean(new ObjectName(WEB_RESOURCES_NAME)); } } } catch (Throwable e) { log.error("Failed to handle event", e); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handleEvent"
"protected void handleEvent(NuxeoWebappLoader loader, LifecycleEvent event) { try { ClassLoader cl = loader.getClassLoader(); boolean devMode = cl instanceof NuxeoDevWebappClassLoader; String type = event.getType(); if (type == Lifecycle.START_EVENT) { File homeDir = resolveHomeDirectory(loader); if (devMode) { bootstrap = new DevFrameworkBootstrap( (MutableClassLoader) cl, homeDir); MBeanServer server = ManagementFactory.getPlatformMBeanServer(); server.registerMBean(bootstrap, new ObjectName(DEV_BUNDLES_NAME)); server.registerMBean(cl, new ObjectName(WEB_RESOURCES_NAME)); } else { bootstrap = new FrameworkBootstrap( (MutableClassLoader) cl, homeDir); } bootstrap.setHostName("Tomcat"); bootstrap.setHostVersion("6.0.20"); bootstrap.initialize(); <MASK>( (NuxeoDevWebappClassLoader)cl).setHome(new File(getHome()));</MASK> } else if (type == Lifecycle.AFTER_START_EVENT) { bootstrap.start(); } else if (type == Lifecycle.STOP_EVENT) { bootstrap.stop(); if (devMode) { MBeanServer server = ManagementFactory.getPlatformMBeanServer(); server.unregisterMBean(new ObjectName(DEV_BUNDLES_NAME)); server.unregisterMBean(new ObjectName(WEB_RESOURCES_NAME)); } } } catch (Throwable e) { log.error("Failed to handle event", e); } }"
Inversion-Mutation
megadiff
"protected String _downloadData() { try { URI uri = _getUri(); if (Log.isEnabled) { Log.debug("downloading page " + uri); } AndroidHttpClient client = AndroidHttpClient.newInstance("Android Munin Client"); HttpGet request = _getRequest(uri); BasicHttpResponse response = (BasicHttpResponse)client.execute(request); String body = EntityUtils.toString(response.getEntity(), "utf8"); client.close(); if (Log.isEnabled) { Log.debug("downloaded: " + body.length()); } return body; } catch (Exception e) { if (Log.isEnabled) { Log.error("failed to download", e); } return null; } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "_downloadData"
"protected String _downloadData() { try { URI uri = _getUri(); if (Log.isEnabled) { Log.debug("downloading page " + uri); } AndroidHttpClient client = AndroidHttpClient.newInstance("Android Munin Client"); HttpGet request = _getRequest(uri); BasicHttpResponse response = (BasicHttpResponse)client.execute(request); <MASK>client.close();</MASK> String body = EntityUtils.toString(response.getEntity(), "utf8"); if (Log.isEnabled) { Log.debug("downloaded: " + body.length()); } return body; } catch (Exception e) { if (Log.isEnabled) { Log.error("failed to download", e); } return null; } }"
Inversion-Mutation
megadiff
"@Before public void setup() { File files = new File("a", "b", "src/c.h", "src/c.cc", "src/d.cc"); editorList = new EditorList(); stackList = new StackList(); fileSystem = new InMemoryFileSystem(); fuzzyFinder = new Finder(files); fuzzyListener = mock(Finder.Listener.class); repo = new InMemoryRepository(); highlightState = new HighlightState(); minibuffer = new Minibuffer(); focusManager = new FocusManager(editorList, stackList); viewportTracker = new ViewportTracker(focusManager); register = new Register(); editorFactory = new EditorFactory(highlightState, register, viewportTracker); FuzzyFinderDriver fileFinderDriver = new FuzzyFinderDriver(files); Finder finder = new Finder(files); editorOpener = new EditorOpener(editorFactory, focusManager, editorList, stackList, fileSystem, finder); commandExecutor = new CommandExecutor(editorOpener, focusManager); minibufferSubsystem = new MinibufferSubsystem(minibuffer, commandExecutor, focusManager); controller = new Controller(editorList, fileSystem, fuzzyFinder, repo, highlightState, stackList, minibufferSubsystem, commandExecutor, null, fileFinderDriver, focusManager, editorOpener); fileSystem.insertFile("a", "aaa"); fileSystem.insertFile("b", "bbb"); fileSystem.insertFile("src/c.cc", "ccc"); fileSystem.insertFile("src/c.h", "chc"); fileSystem.insertFile("src/d.cc", "ddd"); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setup"
"@Before public void setup() { File files = new File("a", "b", "src/c.h", "src/c.cc", "src/d.cc"); editorList = new EditorList(); stackList = new StackList(); fileSystem = new InMemoryFileSystem(); fuzzyFinder = new Finder(files); fuzzyListener = mock(Finder.Listener.class); repo = new InMemoryRepository(); highlightState = new HighlightState(); minibuffer = new Minibuffer(); focusManager = new FocusManager(editorList, stackList); <MASK>minibufferSubsystem = new MinibufferSubsystem(minibuffer, commandExecutor, focusManager);</MASK> viewportTracker = new ViewportTracker(focusManager); register = new Register(); editorFactory = new EditorFactory(highlightState, register, viewportTracker); FuzzyFinderDriver fileFinderDriver = new FuzzyFinderDriver(files); Finder finder = new Finder(files); editorOpener = new EditorOpener(editorFactory, focusManager, editorList, stackList, fileSystem, finder); commandExecutor = new CommandExecutor(editorOpener, focusManager); controller = new Controller(editorList, fileSystem, fuzzyFinder, repo, highlightState, stackList, minibufferSubsystem, commandExecutor, null, fileFinderDriver, focusManager, editorOpener); fileSystem.insertFile("a", "aaa"); fileSystem.insertFile("b", "bbb"); fileSystem.insertFile("src/c.cc", "ccc"); fileSystem.insertFile("src/c.h", "chc"); fileSystem.insertFile("src/d.cc", "ddd"); }"
Inversion-Mutation
megadiff
"public void addLine(BufferLine m) { addLineNoNotify(m); if (m.getVisible()) numUnread++; notifyObservers(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addLine"
"public void addLine(BufferLine m) { addLineNoNotify(m); <MASK>notifyObservers();</MASK> if (m.getVisible()) numUnread++; }"
Inversion-Mutation
megadiff
"private void setNewFeed(Feed result) { if (result != null) { if ( isLeafEntry(result) ) { showItemPopup(result); } else { adapter.setFeed(result); getSherlockActivity().supportInvalidateOptionsMenu(); getSherlockActivity().getSupportActionBar().setTitle(result.getTitle()); } waitDialog.hide(); } else { waitDialog.hide(); Toast.makeText(getActivity(), R.string.feed_failed, Toast.LENGTH_LONG).show(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setNewFeed"
"private void setNewFeed(Feed result) { if (result != null) { if ( isLeafEntry(result) ) { showItemPopup(result); } else { getSherlockActivity().supportInvalidateOptionsMenu(); getSherlockActivity().getSupportActionBar().setTitle(result.getTitle()); <MASK>adapter.setFeed(result);</MASK> } waitDialog.hide(); } else { waitDialog.hide(); Toast.makeText(getActivity(), R.string.feed_failed, Toast.LENGTH_LONG).show(); } }"
Inversion-Mutation
megadiff
"protected int outputStreamData(OutputStream stream) throws IOException { int length = 0; byte[] p = "stream\n".getBytes(); stream.write(p); length += p.length; _data.outputStreamData(stream); length += _data.getSize(); _data.close(); p = "\nendstream\n".getBytes(); stream.write(p); length += p.length; return length; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "outputStreamData"
"protected int outputStreamData(OutputStream stream) throws IOException { int length = 0; byte[] p = "stream\n".getBytes(); stream.write(p); length += p.length; _data.outputStreamData(stream); <MASK>_data.close();</MASK> length += _data.getSize(); p = "\nendstream\n".getBytes(); stream.write(p); length += p.length; return length; }"
Inversion-Mutation
megadiff
"protected Map<Object, Object> findEntityRelationships(JavaClass entity, Map<Object, Object> context) { List<String> entityNames = new ArrayList<String>(); List<String> entityClasses = new ArrayList<String>(); List<String> ccEntityClasses = new ArrayList<String>(); for ( Field<?> field : entity.getFields()) { if (field.hasAnnotation(OneToOne.class) || field.hasAnnotation(OneToMany.class) || field.hasAnnotation(ManyToOne.class) || field.hasAnnotation(ManyToMany.class)) { String name = field.getName(); entityNames.add(name); String clazz = new String(); if (field.hasAnnotation(OneToMany.class) || field.hasAnnotation(ManyToMany.class)) { clazz = field.getStringInitializer(); int firstIndexOf = clazz.indexOf("<"); int lastIndexOf = clazz.indexOf(">"); clazz = clazz.substring(firstIndexOf + 1, lastIndexOf); } else { clazz = field.getType(); } entityClasses.add(clazz); String ccEntity = StringUtils.camelCase(clazz); ccEntityClasses.add(ccEntity); } } context.put("entityNames", entityNames); context.put("entityClasses", entityClasses); context.put("ccEntityClasses", ccEntityClasses); return context; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "findEntityRelationships"
"protected Map<Object, Object> findEntityRelationships(JavaClass entity, Map<Object, Object> context) { List<String> entityNames = new ArrayList<String>(); List<String> entityClasses = new ArrayList<String>(); List<String> ccEntityClasses = new ArrayList<String>(); for ( Field<?> field : entity.getFields()) { if (field.hasAnnotation(OneToOne.class) || field.hasAnnotation(OneToMany.class) || field.hasAnnotation(ManyToOne.class) || field.hasAnnotation(ManyToMany.class)) { String name = field.getName(); entityNames.add(name); String clazz = new String(); if (field.hasAnnotation(OneToMany.class) || field.hasAnnotation(ManyToMany.class)) { clazz = field.getStringInitializer(); int firstIndexOf = clazz.indexOf("<"); int lastIndexOf = clazz.indexOf(">"); clazz = clazz.substring(firstIndexOf + 1, lastIndexOf); <MASK>entityClasses.add(clazz);</MASK> } else { clazz = field.getType(); } String ccEntity = StringUtils.camelCase(clazz); ccEntityClasses.add(ccEntity); } } context.put("entityNames", entityNames); context.put("entityClasses", entityClasses); context.put("ccEntityClasses", ccEntityClasses); return context; }"
Inversion-Mutation
megadiff
"public SPFInternalResult checkSPF(SPF1Data spfData) throws PermErrorException, NoneException, TempErrorException, NeutralException { String result = SPF1Constants.NEUTRAL; String explanation = null; // Get the raw dns txt entry which contains a spf entry String spfDnsEntry = dnsProbe.getSpfRecord(spfData.getCurrentDomain(), SPF1Constants.SPF_VERSION); // logging log.debug("Start parsing SPF-Record:" + spfDnsEntry); SPF1Record spfRecord = parser.parse(spfDnsEntry); String qualifier = null; boolean hasCommand = false; // get all commands Iterator com = spfRecord.getDirectives().iterator(); while (com.hasNext()) { // if we reach maximum calls we must throw a PermErrorException. See // SPF-RFC Section 10.1. Processing Limits if (spfData.getCurrentDepth() > spfData.getMaxDepth()) { throw new PermErrorException( "Maximum mechanism/modifier calls done: " + spfData.getCurrentDepth()); } hasCommand = true; Directive d = (Directive) com.next(); // logging log.debug("Processing directive: " + d.getQualifier() + d.getMechanism().toString()); qualifier = d.run(spfData); // logging log.debug("Processed directive: " + d.getQualifier() + d.getMechanism().toString() + " returned " + qualifier); if (qualifier != null) { if (qualifier.equals("")) { result = SPF1Constants.PASS; } else { result = qualifier; } spfData.setCurrentResult(result); spfData.setMatch(true); // If we have a match we should break the while loop break; } } Iterator mod = spfRecord.getModifiers().iterator(); while (mod.hasNext()) { spfData.setCurrentDepth(spfData.getCurrentDepth() + 1); // if we reach maximum calls we must throw a PermErrorException. See // SPF-RFC Section 10.1. Processing Limits if (spfData.getCurrentDepth() > spfData.getMaxDepth()) { throw new PermErrorException( "Maximum mechanism/modifiers calls done: " + spfData.getCurrentDepth()); } Modifier m = (Modifier) mod.next(); log.debug("Processing modifier: " + m.toString()); String q = m.run(spfData); log.debug("Processed modifier: " + m.toString() + " resulted in " + q); if (q != null) { qualifier = q; } if (qualifier != null) { result = qualifier; spfData.setCurrentResult(result); spfData.setMatch(true); } } // If no match was found set the result to neutral if (!spfData.isMatch() && (hasCommand == true)) { result = SPF1Constants.NEUTRAL; } if (result.equals(SPF1Constants.FAIL)) { if (spfData.getExplanation()==null || spfData.getExplanation().equals("")) { if(defaultExplanation == null) { try { spfData.setExplanation(new MacroExpand(spfData, log) .expandExplanation(SPF1Utils.DEFAULT_EXPLANATION)); } catch (PermErrorException e) { // Should never happen ! log.debug("Invalid defaulfExplanation: " + SPF1Utils.DEFAULT_EXPLANATION); } } else { try { spfData.setExplanation(new MacroExpand(spfData, log) .expandExplanation(defaultExplanation)); } catch (PermErrorException e) { log.error("Invalid defaultExplanation: " + defaultExplanation); } } } explanation = spfData.getExplanation(); } return new SPFInternalResult(result, explanation); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "checkSPF"
"public SPFInternalResult checkSPF(SPF1Data spfData) throws PermErrorException, NoneException, TempErrorException, NeutralException { String result = SPF1Constants.NEUTRAL; String explanation = null; // Get the raw dns txt entry which contains a spf entry String spfDnsEntry = dnsProbe.getSpfRecord(spfData.getCurrentDomain(), SPF1Constants.SPF_VERSION); // logging log.debug("Start parsing SPF-Record:" + spfDnsEntry); SPF1Record spfRecord = parser.parse(spfDnsEntry); String qualifier = null; boolean hasCommand = false; // get all commands Iterator com = spfRecord.getDirectives().iterator(); while (com.hasNext()) { // if we reach maximum calls we must throw a PermErrorException. See // SPF-RFC Section 10.1. Processing Limits if (spfData.getCurrentDepth() > spfData.getMaxDepth()) { throw new PermErrorException( "Maximum mechanism/modifier calls done: " + spfData.getCurrentDepth()); } hasCommand = true; Directive d = (Directive) com.next(); // logging log.debug("Processing directive: " + d.getQualifier() + d.getMechanism().toString()); qualifier = d.run(spfData); // logging log.debug("Processed directive: " + d.getQualifier() + d.getMechanism().toString() + " returned " + qualifier); if (qualifier != null) { if (qualifier.equals("")) { result = SPF1Constants.PASS; } else { result = qualifier; } spfData.setCurrentResult(result); spfData.setMatch(true); // If we have a match we should break the while loop break; } } Iterator mod = spfRecord.getModifiers().iterator(); while (mod.hasNext()) { spfData.setCurrentDepth(spfData.getCurrentDepth() + 1); // if we reach maximum calls we must throw a PermErrorException. See // SPF-RFC Section 10.1. Processing Limits if (spfData.getCurrentDepth() > spfData.getMaxDepth()) { throw new PermErrorException( "Maximum mechanism/modifiers calls done: " + spfData.getCurrentDepth()); } Modifier m = (Modifier) mod.next(); log.debug("Processing modifier: " + m.toString()); String q = m.run(spfData); log.debug("Processed modifier: " + m.toString() + " resulted in " + q); if (q != null) { qualifier = q; } if (qualifier != null) { result = qualifier; spfData.setCurrentResult(result); spfData.setMatch(true); } } // If no match was found set the result to neutral if (!spfData.isMatch() && (hasCommand == true)) { result = SPF1Constants.NEUTRAL; } if (result.equals(SPF1Constants.FAIL)) { if (spfData.getExplanation()==null || spfData.getExplanation().equals("")) { if(defaultExplanation == null) { try { spfData.setExplanation(new MacroExpand(spfData, log) .expandExplanation(SPF1Utils.DEFAULT_EXPLANATION)); } catch (PermErrorException e) { // Should never happen ! log.debug("Invalid defaulfExplanation: " + SPF1Utils.DEFAULT_EXPLANATION); } } else { try { spfData.setExplanation(new MacroExpand(spfData, log) .expandExplanation(defaultExplanation)); } catch (PermErrorException e) { log.error("Invalid defaultExplanation: " + defaultExplanation); } } <MASK>explanation = spfData.getExplanation();</MASK> } } return new SPFInternalResult(result, explanation); }"
Inversion-Mutation
megadiff
"@Override public void kill() { if (Platform.isRunning() && MylarMonitorUiPlugin.getDefault() != null) { timerThread.kill(); MylarMonitorUiPlugin.getDefault().removeInteractionListener(this); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "kill"
"@Override public void kill() { <MASK>timerThread.kill();</MASK> if (Platform.isRunning() && MylarMonitorUiPlugin.getDefault() != null) { MylarMonitorUiPlugin.getDefault().removeInteractionListener(this); } }"
Inversion-Mutation
megadiff
"public <T> void processAnnotatedType(@Observes final ProcessAnnotatedType<T> event, BeanManager manager) { AnnotatedTypeBuilder<T> modifiedType = null; for (AnnotatedField<? super T> field : event.getAnnotatedType().getFields()) { boolean bootstrapped = false; if (field.isAnnotationPresent(PersistenceUnit.class) && field.isAnnotationPresent(Produces.class) && !EnvironmentUtils.isEEEnvironment()) { bootstrapped = true; final String unitName = field.getAnnotation(PersistenceUnit.class).unitName(); final Set<Annotation> qualifiers = Beans.getQualifiers(manager, field.getAnnotations()); if (qualifiers.isEmpty()) { qualifiers.add(DefaultLiteral.INSTANCE); } qualifiers.add(AnyLiteral.INSTANCE); beans.add(createEMFBean(unitName, qualifiers, event.getAnnotatedType(), manager)); } // look for a seam managed persistence unit declaration on EE resource // producer fields if (field.isAnnotationPresent(SeamManaged.class) && (field.isAnnotationPresent(PersistenceUnit.class) || field.isAnnotationPresent(Resource.class)) && field.isAnnotationPresent(Produces.class) && EntityManagerFactory.class.isAssignableFrom(field.getJavaMember().getType())) { if (modifiedType == null) { modifiedType = new AnnotatedTypeBuilder().readFromType(event.getAnnotatedType()); } Set<Annotation> qualifiers = new HashSet<Annotation>(); Class<? extends Annotation> scope = Dependent.class; // get the qualifier and scope for the new bean for (Annotation annotation : field.getAnnotations()) { if (manager.isQualifier(annotation.annotationType())) { qualifiers.add(annotation); } else if (manager.isScope(annotation.annotationType())) { scope = annotation.annotationType(); } } if (qualifiers.isEmpty()) { qualifiers.add(new DefaultLiteral()); } qualifiers.add(AnyLiteral.INSTANCE); // we need to remove the scope, they are not nessesarily supported // on producer fields if (scope != Dependent.class) { modifiedType.removeFromField(field.getJavaMember(), scope); } if (bootstrapped) { modifiedType.removeFromField(field.getJavaMember(), Produces.class); } registerManagedPersistenceContext(qualifiers, scope, field.isAnnotationPresent(Alternative.class), manager, event.getAnnotatedType().getJavaClass().getClassLoader(), field, event.getAnnotatedType().getJavaClass()); log.info("Configuring Seam Managed Persistence Context from producer field " + event.getAnnotatedType().getJavaClass().getName() + "." + field.getJavaMember().getName() + " with qualifiers " + qualifiers); } // now look for producer methods that produce an EntityManagerFactory. // This allows the user to manually configure an EntityManagerFactory // and return it from a producer method } // now look for SMPC's that are configured programatically via a producer // method. This looks for both EMF's and SessionFactories // The producer method has its scope changes to application scoped // this allows for programatic config of the SMPC for (AnnotatedMethod<? super T> method : event.getAnnotatedType().getMethods()) { if (method.isAnnotationPresent(SeamManaged.class) && method.isAnnotationPresent(Produces.class) && EntityManagerFactory.class.isAssignableFrom(method.getJavaMember().getReturnType())) { if (modifiedType == null) { modifiedType = new AnnotatedTypeBuilder().readFromType(event.getAnnotatedType()); } Set<Annotation> qualifiers = new HashSet<Annotation>(); Class<? extends Annotation> scope = Dependent.class; // get the qualifier and scope for the new bean for (Annotation annotation : method.getAnnotations()) { if (manager.isQualifier(annotation.annotationType())) { qualifiers.add(annotation); } else if (manager.isScope(annotation.annotationType())) { scope = annotation.annotationType(); } } if (qualifiers.isEmpty()) { qualifiers.add(new DefaultLiteral()); } qualifiers.add(AnyLiteral.INSTANCE); // we need to change the scope to application scoped modifiedType.removeFromMethod(method.getJavaMember(), scope); modifiedType.addToMethod(method.getJavaMember(), ApplicationScopedLiteral.INSTANCE); registerManagedPersistenceContext(qualifiers, scope, method.isAnnotationPresent(Alternative.class), manager, event.getAnnotatedType().getJavaClass().getClassLoader(), method, event.getAnnotatedType().getJavaClass()); log.info("Configuring Seam Managed Persistence Context from producer method " + event.getAnnotatedType().getJavaClass().getName() + "." + method.getJavaMember().getName() + " with qualifiers " + qualifiers); } } if (modifiedType != null) { event.setAnnotatedType(modifiedType.create()); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "processAnnotatedType"
"public <T> void processAnnotatedType(@Observes final ProcessAnnotatedType<T> event, BeanManager manager) { AnnotatedTypeBuilder<T> modifiedType = null; <MASK>boolean bootstrapped = false;</MASK> for (AnnotatedField<? super T> field : event.getAnnotatedType().getFields()) { if (field.isAnnotationPresent(PersistenceUnit.class) && field.isAnnotationPresent(Produces.class) && !EnvironmentUtils.isEEEnvironment()) { bootstrapped = true; final String unitName = field.getAnnotation(PersistenceUnit.class).unitName(); final Set<Annotation> qualifiers = Beans.getQualifiers(manager, field.getAnnotations()); if (qualifiers.isEmpty()) { qualifiers.add(DefaultLiteral.INSTANCE); } qualifiers.add(AnyLiteral.INSTANCE); beans.add(createEMFBean(unitName, qualifiers, event.getAnnotatedType(), manager)); } // look for a seam managed persistence unit declaration on EE resource // producer fields if (field.isAnnotationPresent(SeamManaged.class) && (field.isAnnotationPresent(PersistenceUnit.class) || field.isAnnotationPresent(Resource.class)) && field.isAnnotationPresent(Produces.class) && EntityManagerFactory.class.isAssignableFrom(field.getJavaMember().getType())) { if (modifiedType == null) { modifiedType = new AnnotatedTypeBuilder().readFromType(event.getAnnotatedType()); } Set<Annotation> qualifiers = new HashSet<Annotation>(); Class<? extends Annotation> scope = Dependent.class; // get the qualifier and scope for the new bean for (Annotation annotation : field.getAnnotations()) { if (manager.isQualifier(annotation.annotationType())) { qualifiers.add(annotation); } else if (manager.isScope(annotation.annotationType())) { scope = annotation.annotationType(); } } if (qualifiers.isEmpty()) { qualifiers.add(new DefaultLiteral()); } qualifiers.add(AnyLiteral.INSTANCE); // we need to remove the scope, they are not nessesarily supported // on producer fields if (scope != Dependent.class) { modifiedType.removeFromField(field.getJavaMember(), scope); } if (bootstrapped) { modifiedType.removeFromField(field.getJavaMember(), Produces.class); } registerManagedPersistenceContext(qualifiers, scope, field.isAnnotationPresent(Alternative.class), manager, event.getAnnotatedType().getJavaClass().getClassLoader(), field, event.getAnnotatedType().getJavaClass()); log.info("Configuring Seam Managed Persistence Context from producer field " + event.getAnnotatedType().getJavaClass().getName() + "." + field.getJavaMember().getName() + " with qualifiers " + qualifiers); } // now look for producer methods that produce an EntityManagerFactory. // This allows the user to manually configure an EntityManagerFactory // and return it from a producer method } // now look for SMPC's that are configured programatically via a producer // method. This looks for both EMF's and SessionFactories // The producer method has its scope changes to application scoped // this allows for programatic config of the SMPC for (AnnotatedMethod<? super T> method : event.getAnnotatedType().getMethods()) { if (method.isAnnotationPresent(SeamManaged.class) && method.isAnnotationPresent(Produces.class) && EntityManagerFactory.class.isAssignableFrom(method.getJavaMember().getReturnType())) { if (modifiedType == null) { modifiedType = new AnnotatedTypeBuilder().readFromType(event.getAnnotatedType()); } Set<Annotation> qualifiers = new HashSet<Annotation>(); Class<? extends Annotation> scope = Dependent.class; // get the qualifier and scope for the new bean for (Annotation annotation : method.getAnnotations()) { if (manager.isQualifier(annotation.annotationType())) { qualifiers.add(annotation); } else if (manager.isScope(annotation.annotationType())) { scope = annotation.annotationType(); } } if (qualifiers.isEmpty()) { qualifiers.add(new DefaultLiteral()); } qualifiers.add(AnyLiteral.INSTANCE); // we need to change the scope to application scoped modifiedType.removeFromMethod(method.getJavaMember(), scope); modifiedType.addToMethod(method.getJavaMember(), ApplicationScopedLiteral.INSTANCE); registerManagedPersistenceContext(qualifiers, scope, method.isAnnotationPresent(Alternative.class), manager, event.getAnnotatedType().getJavaClass().getClassLoader(), method, event.getAnnotatedType().getJavaClass()); log.info("Configuring Seam Managed Persistence Context from producer method " + event.getAnnotatedType().getJavaClass().getName() + "." + method.getJavaMember().getName() + " with qualifiers " + qualifiers); } } if (modifiedType != null) { event.setAnnotatedType(modifiedType.create()); } }"
Inversion-Mutation
megadiff
"@Override public void startAcquiringSynchronously() throws Exception { int countBefore = getArrayCounter_RBV(); startAcquiring(); while (getStatus() != Detector.IDLE && getStatus() != Detector.FAULT) { Sleep.sleep(100); if( getAcquireState()==0) throw new Exception("Camera is not acquiring but putListener has not been called"); } if (getStatus() == Detector.FAULT) { logger.debug("detector in a fault state"); } int countAfter = getArrayCounter_RBV(); if( countAfter==countBefore) throw new Exception("Acquire completed but counter did not increment"); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "startAcquiringSynchronously"
"@Override public void startAcquiringSynchronously() throws Exception { int countBefore = getArrayCounter_RBV(); startAcquiring(); while (getStatus() != Detector.IDLE && getStatus() != Detector.FAULT) { if( getAcquireState()==0) throw new Exception("Camera is not acquiring but putListener has not been called"); <MASK>Sleep.sleep(100);</MASK> } if (getStatus() == Detector.FAULT) { logger.debug("detector in a fault state"); } int countAfter = getArrayCounter_RBV(); if( countAfter==countBefore) throw new Exception("Acquire completed but counter did not increment"); }"
Inversion-Mutation
megadiff
"public void __sceSasCore(Processor processor) { CpuState cpu = processor.cpu; // New-Style Processor // Processor cpu = processor; // Old-Style Processor int sasCore = cpu.gpr[4]; //int unk1 = cpu.gpr[5]; // looks like a heap address, bss, 0x40 aligned // 99% sure there are no more parameters Modules.log.debug("IGNORING:__sceSasCore " + makeLogParams(cpu)); if (isSasHandleGood(sasCore, "__sceSasCore", cpu)) { // noxa/pspplayer blocks in __sceSasCore // some games protect __sceSasCore with locks, suggesting it may context switch. // Games seems to run better when delaying the thread instead of just yielding. cpu.gpr[2] = 0; ThreadMan.getInstance().hleKernelDelayThread(1000000, false); // ThreadMan.getInstance().yieldCurrentThread(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "__sceSasCore"
"public void __sceSasCore(Processor processor) { CpuState cpu = processor.cpu; // New-Style Processor // Processor cpu = processor; // Old-Style Processor int sasCore = cpu.gpr[4]; //int unk1 = cpu.gpr[5]; // looks like a heap address, bss, 0x40 aligned // 99% sure there are no more parameters Modules.log.debug("IGNORING:__sceSasCore " + makeLogParams(cpu)); if (isSasHandleGood(sasCore, "__sceSasCore", cpu)) { // noxa/pspplayer blocks in __sceSasCore // some games protect __sceSasCore with locks, suggesting it may context switch. // Games seems to run better when delaying the thread instead of just yielding. ThreadMan.getInstance().hleKernelDelayThread(1000000, false); // ThreadMan.getInstance().yieldCurrentThread(); <MASK>cpu.gpr[2] = 0;</MASK> } }"
Inversion-Mutation
megadiff
"private ColumnFamily getTopLevelColumns(QueryFilter filter, int gcBefore) { // we are querying top-level columns, do a merging fetch with indexes. List<IColumnIterator> iterators = new ArrayList<IColumnIterator>(); final ColumnFamily returnCF = ColumnFamily.create(metadata); try { IColumnIterator iter; int sstablesToIterate = 0; DataTracker.View currentView = data.getView(); /* add the current memtable */ iter = filter.getMemtableColumnIterator(currentView.memtable, getComparator()); if (iter != null) { returnCF.delete(iter.getColumnFamily()); iterators.add(iter); } /* add the memtables being flushed */ for (Memtable memtable : currentView.memtablesPendingFlush) { iter = filter.getMemtableColumnIterator(memtable, getComparator()); if (iter != null) { returnCF.delete(iter.getColumnFamily()); iterators.add(iter); } } /* add the SSTables on disk */ for (SSTableReader sstable : currentView.sstables) { iter = filter.getSSTableColumnIterator(sstable); if (iter.getColumnFamily() != null) { returnCF.delete(iter.getColumnFamily()); iterators.add(iter); sstablesToIterate++; } } recentSSTablesPerRead.add(sstablesToIterate); sstablesPerRead.add(sstablesToIterate); Comparator<IColumn> comparator = filter.filter.getColumnComparator(getComparator()); Iterator collated = IteratorUtils.collatedIterator(comparator, iterators); filter.collectCollatedColumns(returnCF, collated, gcBefore); // Caller is responsible for final removeDeletedCF. This is important for cacheRow to work correctly: // we need to distinguish between "there is no data at all for this row" (BF will let us rebuild that efficiently) // and "there used to be data, but it's gone now" (we should cache the empty CF so we don't need to rebuild that slower) return returnCF; } catch (IOException e) { throw new IOError(e); } finally { /* close all cursors */ for (IColumnIterator ci : iterators) { try { ci.close(); } catch (Throwable th) { logger.error("error closing " + ci, th); } } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getTopLevelColumns"
"private ColumnFamily getTopLevelColumns(QueryFilter filter, int gcBefore) { // we are querying top-level columns, do a merging fetch with indexes. List<IColumnIterator> iterators = new ArrayList<IColumnIterator>(); final ColumnFamily returnCF = ColumnFamily.create(metadata); try { IColumnIterator iter; int sstablesToIterate = 0; DataTracker.View currentView = data.getView(); /* add the current memtable */ iter = filter.getMemtableColumnIterator(currentView.memtable, getComparator()); if (iter != null) { returnCF.delete(iter.getColumnFamily()); iterators.add(iter); } /* add the memtables being flushed */ for (Memtable memtable : currentView.memtablesPendingFlush) { iter = filter.getMemtableColumnIterator(memtable, getComparator()); if (iter != null) { returnCF.delete(iter.getColumnFamily()); iterators.add(iter); } } /* add the SSTables on disk */ for (SSTableReader sstable : currentView.sstables) { iter = filter.getSSTableColumnIterator(sstable); if (iter.getColumnFamily() != null) { returnCF.delete(iter.getColumnFamily()); iterators.add(iter); } <MASK>sstablesToIterate++;</MASK> } recentSSTablesPerRead.add(sstablesToIterate); sstablesPerRead.add(sstablesToIterate); Comparator<IColumn> comparator = filter.filter.getColumnComparator(getComparator()); Iterator collated = IteratorUtils.collatedIterator(comparator, iterators); filter.collectCollatedColumns(returnCF, collated, gcBefore); // Caller is responsible for final removeDeletedCF. This is important for cacheRow to work correctly: // we need to distinguish between "there is no data at all for this row" (BF will let us rebuild that efficiently) // and "there used to be data, but it's gone now" (we should cache the empty CF so we don't need to rebuild that slower) return returnCF; } catch (IOException e) { throw new IOError(e); } finally { /* close all cursors */ for (IColumnIterator ci : iterators) { try { ci.close(); } catch (Throwable th) { logger.error("error closing " + ci, th); } } } }"
Inversion-Mutation
megadiff
"@Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { if (loadedImage != null) { ImageView imageView = (ImageView) view; boolean firstDisplay = !displayedImages.contains(imageUri); if (firstDisplay) { FadeInBitmapDisplayer.animate(imageView, 500); displayedImages.add(imageUri); } else { imageView.setImageBitmap(loadedImage); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onLoadingComplete"
"@Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { if (loadedImage != null) { ImageView imageView = (ImageView) view; boolean firstDisplay = !displayedImages.contains(imageUri); if (firstDisplay) { FadeInBitmapDisplayer.animate(imageView, 500); } else { imageView.setImageBitmap(loadedImage); } <MASK>displayedImages.add(imageUri);</MASK> } }"
Inversion-Mutation
megadiff
"@Override final public void configure(OrccProcess process, IProgressMonitor monitor, boolean debugMode) { this.state = SimulatorState.IDLE; this.process = process; this.monitor = monitor; this.debugMode = debugMode; try { // Parse XDF file, do some transformations and return the // graph corresponding to the flat network instantiation. DirectedGraph<Vertex, Connection> graph = getGraphFromNetwork(); // Instantiate simulator actors from the graph instantiateNetwork(graph); // Build the network according to the specified topology. connectNetwork(graph); initializeNetwork(); } catch (OrccException e) { throw new OrccRuntimeException(e.getMessage()); } catch (FileNotFoundException e) { throw new OrccRuntimeException(e.getMessage()); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "configure"
"@Override final public void configure(OrccProcess process, IProgressMonitor monitor, boolean debugMode) { this.state = SimulatorState.IDLE; this.process = process; this.monitor = monitor; this.debugMode = debugMode; try { // Parse XDF file, do some transformations and return the // graph corresponding to the flat network instantiation. DirectedGraph<Vertex, Connection> graph = getGraphFromNetwork(); // Instantiate simulator actors from the graph instantiateNetwork(graph); // Build the network according to the specified topology. <MASK>initializeNetwork();</MASK> connectNetwork(graph); } catch (OrccException e) { throw new OrccRuntimeException(e.getMessage()); } catch (FileNotFoundException e) { throw new OrccRuntimeException(e.getMessage()); } }"
Inversion-Mutation
megadiff
"@Override public boolean onCommand(CommandSender sender, Command command, String cmdlabel, String[] vars) { Player p; if (sender instanceof Player) { p = (Player) sender; if (cmdlabel.equalsIgnoreCase("bank") || cmdlabel.equalsIgnoreCase("bc")) { if (vars.length == 0) { sendHelp(p); return true; } if (vars.length == 1) { if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.help"))) { sendHelp(p); return true; } if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balance")) && (Bankcraft.perms.has(p, "bankcraft.command.balance") || Bankcraft.perms.has(p, "bankcraft.command"))) { return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName()); } if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balancexp")) && (Bankcraft.perms.has(p, "bankcraft.command.balancexp") || Bankcraft.perms.has(p, "bankcraft.command"))) { return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName()); } if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.interesttimer")) && (Bankcraft.perms.has(p, "bankcraft.command.interesttimer") || Bankcraft.perms.has(p, "bankcraft.command"))) { return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName()); } if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.rankstats")) && (Bankcraft.perms.has(p, "bankcraft.command.rankstats") || Bankcraft.perms.has(p, "bankcraft.command"))) { return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName()); } if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.rankstatsxp")) && (Bankcraft.perms.has(p, "bankcraft.command.rankstatsxp") || Bankcraft.perms.has(p, "bankcraft.command"))) { return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName()); } } if (vars.length == 2) { if (Util.isPositive(vars[1]) || vars[1].equalsIgnoreCase("all")) { if (vars[0].equalsIgnoreCase("add") && (Bankcraft.perms.has(p, "bankcraft.admin"))) { Block signblock = p.getTargetBlock(null, 50); if (signblock.getType() == Material.WALL_SIGN) { Sign sign = (Sign) signblock.getState(); if (sign.getLine(0).contains("[Bank]")) { Integer typsign = -1; try { typsign = bankcraft.getSignDatabaseInterface().getType(signblock.getX(), signblock.getY(), signblock.getZ(), signblock.getWorld()); } catch (Exception e) { e.printStackTrace(); } if (typsign == 1 || typsign == 2 || typsign == 3 || typsign == 4 || typsign == 6 || typsign == 7 || typsign == 8 || typsign == 9 || typsign == 12 || typsign == 13 || typsign == 14 || typsign == 15) { Integer x = signblock.getX(); Integer y = signblock.getY(); Integer z = signblock.getZ(); World w = signblock.getWorld(); Integer newType; Integer currentType = bankcraft.getSignDatabaseInterface().getType(x, y, z, w); if (currentType == 1 || currentType == 2 || currentType == 6 || currentType == 7|| currentType == 12|| currentType == 13) { newType = currentType +2; bankcraft.getSignDatabaseInterface().changeType(x, y, z, newType, w); } bankcraft.getSignDatabaseInterface().addAmount(x, y, z, w, vars[1]); coHa.printMessage(p, "message.amountAddedSuccessfullyToSign", vars[1], p.getName()); bankcraft.getSignHandler().updateSign(signblock,0); return true; } } } } else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balance")) && (Bankcraft.perms.has(p, "bankcraft.command.balance.other") || Bankcraft.perms.has(p, "bankcraft.command"))) { return bankcraft.getInteractionHandler().interact(vars[0], "", p, vars[1]); } else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balancexp")) && (Bankcraft.perms.has(p, "bankcraft.command.balancexp.other") || Bankcraft.perms.has(p, "bankcraft.command"))) { return bankcraft.getInteractionHandler().interact(vars[0], "", p, vars[1]); } else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.deposit")) && (Bankcraft.perms.has(p, "bankcraft.command.deposit") || Bankcraft.perms.has(p, "bankcraft.command"))) { return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName()); } else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.withdraw")) && (Bankcraft.perms.has(p, "bankcraft.command.withdraw") || Bankcraft.perms.has(p, "bankcraft.command"))) { return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName()); } else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.depositxp")) && (Bankcraft.perms.has(p, "bankcraft.command.depositxp") || Bankcraft.perms.has(p, "bankcraft.command"))) { return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName()); } else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.withdrawxp")) && (Bankcraft.perms.has(p, "bankcraft.command.withdrawxp") || Bankcraft.perms.has(p, "bankcraft.command"))) { return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName()); } else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.exchange")) && (Bankcraft.perms.has(p, "bankcraft.command.exchange") || Bankcraft.perms.has(p, "bankcraft.command"))) { return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName()); } else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.exchangexp")) && (Bankcraft.perms.has(p, "bankcraft.command.exchangexp") || Bankcraft.perms.has(p, "bankcraft.command"))) { return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName()); } else { p.sendMessage(ChatColor.RED + coHa.getString("chat.prefix") + "Wrong Syntax or missing permissions! Please see /bank help for more information!"); } } else { if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balance")) && (Bankcraft.perms.has(p, "bankcraft.command.balance.other") || Bankcraft.perms.has(p, "bankcraft.command"))) { return bankcraft.getInteractionHandler().interact(vars[0], null, p, vars[1]); } else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balancexp")) && (Bankcraft.perms.has(p, "bankcraft.command.balancexp.other") || Bankcraft.perms.has(p, "bankcraft.command"))) { return bankcraft.getInteractionHandler().interact(vars[0], null, p, vars[1]); } } } if (vars.length == 3) { if (Util.isPositive(vars[2]) || vars[2].equalsIgnoreCase("all")) { if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.transfer")) && (Bankcraft.perms.has(p, "bankcraft.command.transfer") || Bankcraft.perms.has(p, "bankcraft.command"))) { double amount; if (vars[2].equalsIgnoreCase("all")) { amount = bankcraft.getMoneyDatabaseInterface().getBalance(p.getName()); } else { amount = Double.parseDouble(vars[2]); } ((MoneyBankingHandler)bankcraft.getBankingHandlers()[0]).transferFromAccountToAccount(p.getName(), vars[1], amount,p); return true; } else { if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.transferxp")) && (Bankcraft.perms.has(p, "bankcraft.command.transferxp") || Bankcraft.perms.has(p, "bankcraft.command"))) { int amount; if (vars[2].equalsIgnoreCase("all")) { amount = bankcraft.getExperienceDatabaseInterface().getBalance(p.getName()); } else { amount = Integer.parseInt(vars[2]); } ((ExperienceBankingHandler)bankcraft.getBankingHandlers()[0]).transferFromAccountToAccount(p.getName(), vars[1], amount,p); return true; } } } } else { p.sendMessage(ChatColor.RED + coHa.getString("chat.prefix") + "Wrong Syntax or missing permissions! Please see /bank help for more information!"); return true; } } else { if (cmdlabel.equalsIgnoreCase("bankadmin") || cmdlabel.equalsIgnoreCase("bcadmin")) { if (vars.length == 0) { sendAdminHelp(p); return true; } else if (vars.length == 1) { if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.help"))) { sendAdminHelp(p); return true; } if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.reloadconfig")) && (Bankcraft.perms.has(p, "bankcraft.command.reloadconfig") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) { bankcraft.reloadConfig(); p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Config reloaded!"); return true; } } else if (vars.length == 2) { if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.clear")) && (Bankcraft.perms.has(p, "bankcraft.command.clear") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) { bankcraft.getMoneyDatabaseInterface().setBalance(vars[1], 0D); p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Account cleared!"); return true; } if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.clearxp")) && (Bankcraft.perms.has(p, "bankcraft.command.clearxp") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) { bankcraft.getExperienceDatabaseInterface().setBalance(vars[1], 0); p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "XP-Account cleared!"); return true; } } else if (vars.length == 3) { if (Util.isDouble(vars[2])) { if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.set")) && (Bankcraft.perms.has(p, "bankcraft.command.set") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) { bankcraft.getMoneyDatabaseInterface().setBalance(vars[1], Double.parseDouble(vars[2])); p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Account set!"); return true; } if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.setxp")) && (Bankcraft.perms.has(p, "bankcraft.command.setxp") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) { bankcraft.getExperienceDatabaseInterface().setBalance(vars[1], Integer.parseInt(vars[2])); p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "XP-Account set!"); return true; } if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.grant")) && (Bankcraft.perms.has(p, "bankcraft.command.grant") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) { bankcraft.getMoneyDatabaseInterface().addToAccount(vars[1], Double.parseDouble(vars[2])); p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Granted "+vars[2]+" Money to "+vars[1]+"!"); return true; } if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.grantxp")) && (Bankcraft.perms.has(p, "bankcraft.command.grantxp") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) { bankcraft.getExperienceDatabaseInterface().addToAccount(vars[1], Integer.parseInt(vars[2])); p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Granted "+vars[2]+" Experience to "+vars[1]+"!"); return true; } } else { if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.databaseimport")) && (Bankcraft.perms.has(p, "bankcraft.command.databaseimport") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) { p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Importing..."); DatabaseManagerInterface loadDataMan = null; AccountDatabaseInterface <Double> loadDataMoney = null; AccountDatabaseInterface <Integer> loadDataXp = null; SignDatabaseInterface loadDataSign = null; DatabaseManagerInterface saveDataMan = null; AccountDatabaseInterface <Double> saveDataMoney = null; AccountDatabaseInterface <Integer> saveDataXp = null; SignDatabaseInterface saveDataSign = null; if (vars[1].equalsIgnoreCase("flatfile")) { //Load flatFile p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Importing from flatfile..."); loadDataMan = new DatabaseManagerFlatFile(bankcraft); loadDataMoney = new MoneyFlatFileInterface(bankcraft); loadDataXp = new ExperienceFlatFileInterface(bankcraft); loadDataSign = new SignFlatFileInterface(bankcraft); } if (vars[1].equalsIgnoreCase("mysql")) { //Load mysql p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Importing from mysql..."); loadDataMan = new DatabaseManagerMysql(bankcraft); loadDataMoney = new MoneyMysqlInterface(bankcraft); loadDataXp = new ExperienceMysqlInterface(bankcraft); loadDataSign = new SignMysqlInterface(bankcraft); } if (vars[2].equalsIgnoreCase("flatfile")) { //Load flatFile p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Exporting to flatfile..."); saveDataMan = new DatabaseManagerFlatFile(bankcraft); saveDataMoney = new MoneyFlatFileInterface(bankcraft); saveDataXp = new ExperienceFlatFileInterface(bankcraft); saveDataSign = new SignFlatFileInterface(bankcraft); } if (vars[2].equalsIgnoreCase("mysql")) { //Load mysql p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Exporting to mysql..."); saveDataMan = new DatabaseManagerMysql(bankcraft); saveDataMoney = new MoneyMysqlInterface(bankcraft); saveDataXp = new ExperienceMysqlInterface(bankcraft); saveDataSign = new SignMysqlInterface(bankcraft); } //get them ready loadDataMan.setupDatabase(); saveDataMan.setupDatabase(); //move money data for (String accountName: loadDataMoney.getAccounts()) { saveDataMoney.setBalance(accountName, loadDataMoney.getBalance(accountName)); } //move xp data for (String accountName: loadDataXp.getAccounts()) { saveDataXp.setBalance(accountName, loadDataXp.getBalance(accountName)); } //move sign data String amounts; String[] amountsArray; int type; for (Location location: loadDataSign.getLocations(-1, null)) { //Get amounts amountsArray = loadDataSign.getAmounts((int)location.getX(), (int)location.getY(), (int)location.getZ(), location.getWorld()); amounts = amountsArray[0]; for (int i = 1; i< amountsArray.length; i++) { amounts+=":"+amountsArray[i]; } //Get type type = loadDataSign.getType((int)location.getX(), (int)location.getY(), (int)location.getZ(), location.getWorld()); //Create new sign in save database saveDataSign.createNewSign((int)location.getX(), (int)location.getY(), (int)location.getZ(), location.getWorld(), type, amounts); } //close databases loadDataMan.closeDatabase(); saveDataMan.closeDatabase(); //Send success message p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Moved all data from "+vars[1]+" to "+vars[2]+"!"); return true; } } } else { p.sendMessage(ChatColor.RED + coHa.getString("chat.prefix") + "Wrong Syntax or missing permissions! Please see /bank help for more information!"); } return true; } } } else { Bankcraft.log.info("[Bankcraft] Please use this ingame!"); } return false; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCommand"
"@Override public boolean onCommand(CommandSender sender, Command command, String cmdlabel, String[] vars) { Player p; if (sender instanceof Player) { p = (Player) sender; if (cmdlabel.equalsIgnoreCase("bank") || cmdlabel.equalsIgnoreCase("bc")) { if (vars.length == 0) { sendHelp(p); return true; <MASK>}</MASK> if (vars.length == 1) { if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.help"))) { sendHelp(p); return true; <MASK>}</MASK> if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balance")) && (Bankcraft.perms.has(p, "bankcraft.command.balance") || Bankcraft.perms.has(p, "bankcraft.command"))) { return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName()); <MASK>}</MASK> if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balancexp")) && (Bankcraft.perms.has(p, "bankcraft.command.balancexp") || Bankcraft.perms.has(p, "bankcraft.command"))) { return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName()); <MASK>}</MASK> if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.interesttimer")) && (Bankcraft.perms.has(p, "bankcraft.command.interesttimer") || Bankcraft.perms.has(p, "bankcraft.command"))) { return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName()); <MASK>}</MASK> if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.rankstats")) && (Bankcraft.perms.has(p, "bankcraft.command.rankstats") || Bankcraft.perms.has(p, "bankcraft.command"))) { return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName()); <MASK>}</MASK> if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.rankstatsxp")) && (Bankcraft.perms.has(p, "bankcraft.command.rankstatsxp") || Bankcraft.perms.has(p, "bankcraft.command"))) { return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName()); <MASK>}</MASK> <MASK>}</MASK> if (vars.length == 2) { if (Util.isPositive(vars[1]) || vars[1].equalsIgnoreCase("all")) { if (vars[0].equalsIgnoreCase("add") && (Bankcraft.perms.has(p, "bankcraft.admin"))) { Block signblock = p.getTargetBlock(null, 50); if (signblock.getType() == Material.WALL_SIGN) { Sign sign = (Sign) signblock.getState(); if (sign.getLine(0).contains("[Bank]")) { Integer typsign = -1; try { typsign = bankcraft.getSignDatabaseInterface().getType(signblock.getX(), signblock.getY(), signblock.getZ(), signblock.getWorld()); <MASK>}</MASK> catch (Exception e) { e.printStackTrace(); <MASK>}</MASK> if (typsign == 1 || typsign == 2 || typsign == 3 || typsign == 4 || typsign == 6 || typsign == 7 || typsign == 8 || typsign == 9 || typsign == 12 || typsign == 13 || typsign == 14 || typsign == 15) { Integer x = signblock.getX(); Integer y = signblock.getY(); Integer z = signblock.getZ(); World w = signblock.getWorld(); Integer newType; Integer currentType = bankcraft.getSignDatabaseInterface().getType(x, y, z, w); if (currentType == 1 || currentType == 2 || currentType == 6 || currentType == 7|| currentType == 12|| currentType == 13) { newType = currentType +2; bankcraft.getSignDatabaseInterface().changeType(x, y, z, newType, w); <MASK>}</MASK> bankcraft.getSignDatabaseInterface().addAmount(x, y, z, w, vars[1]); coHa.printMessage(p, "message.amountAddedSuccessfullyToSign", vars[1], p.getName()); bankcraft.getSignHandler().updateSign(signblock,0); return true; <MASK>}</MASK> <MASK>}</MASK> <MASK>}</MASK> <MASK>}</MASK> else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balance")) && (Bankcraft.perms.has(p, "bankcraft.command.balance.other") || Bankcraft.perms.has(p, "bankcraft.command"))) { return bankcraft.getInteractionHandler().interact(vars[0], "", p, vars[1]); <MASK>}</MASK> else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balancexp")) && (Bankcraft.perms.has(p, "bankcraft.command.balancexp.other") || Bankcraft.perms.has(p, "bankcraft.command"))) { return bankcraft.getInteractionHandler().interact(vars[0], "", p, vars[1]); <MASK>}</MASK> else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.deposit")) && (Bankcraft.perms.has(p, "bankcraft.command.deposit") || Bankcraft.perms.has(p, "bankcraft.command"))) { return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName()); <MASK>}</MASK> else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.withdraw")) && (Bankcraft.perms.has(p, "bankcraft.command.withdraw") || Bankcraft.perms.has(p, "bankcraft.command"))) { return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName()); <MASK>}</MASK> else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.depositxp")) && (Bankcraft.perms.has(p, "bankcraft.command.depositxp") || Bankcraft.perms.has(p, "bankcraft.command"))) { return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName()); <MASK>}</MASK> else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.withdrawxp")) && (Bankcraft.perms.has(p, "bankcraft.command.withdrawxp") || Bankcraft.perms.has(p, "bankcraft.command"))) { return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName()); <MASK>}</MASK> else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.exchange")) && (Bankcraft.perms.has(p, "bankcraft.command.exchange") || Bankcraft.perms.has(p, "bankcraft.command"))) { return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName()); <MASK>}</MASK> else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.exchangexp")) && (Bankcraft.perms.has(p, "bankcraft.command.exchangexp") || Bankcraft.perms.has(p, "bankcraft.command"))) { return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName()); <MASK>}</MASK> else { p.sendMessage(ChatColor.RED + coHa.getString("chat.prefix") + "Wrong Syntax or missing permissions! Please see /bank help for more information!"); <MASK>}</MASK> <MASK>}</MASK> else { if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balance")) && (Bankcraft.perms.has(p, "bankcraft.command.balance.other") || Bankcraft.perms.has(p, "bankcraft.command"))) { return bankcraft.getInteractionHandler().interact(vars[0], null, p, vars[1]); <MASK>}</MASK> else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balancexp")) && (Bankcraft.perms.has(p, "bankcraft.command.balancexp.other") || Bankcraft.perms.has(p, "bankcraft.command"))) { return bankcraft.getInteractionHandler().interact(vars[0], null, p, vars[1]); <MASK>}</MASK> <MASK>}</MASK> <MASK>}</MASK> if (vars.length == 3) { if (Util.isPositive(vars[2]) || vars[2].equalsIgnoreCase("all")) { if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.transfer")) && (Bankcraft.perms.has(p, "bankcraft.command.transfer") || Bankcraft.perms.has(p, "bankcraft.command"))) { double amount; if (vars[2].equalsIgnoreCase("all")) { amount = bankcraft.getMoneyDatabaseInterface().getBalance(p.getName()); <MASK>}</MASK> else { amount = Double.parseDouble(vars[2]); <MASK>}</MASK> ((MoneyBankingHandler)bankcraft.getBankingHandlers()[0]).transferFromAccountToAccount(p.getName(), vars[1], amount,p); return true; <MASK>}</MASK> <MASK>}</MASK> else { if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.transferxp")) && (Bankcraft.perms.has(p, "bankcraft.command.transferxp") || Bankcraft.perms.has(p, "bankcraft.command"))) { int amount; if (vars[2].equalsIgnoreCase("all")) { amount = bankcraft.getExperienceDatabaseInterface().getBalance(p.getName()); <MASK>}</MASK> else { amount = Integer.parseInt(vars[2]); <MASK>}</MASK> ((ExperienceBankingHandler)bankcraft.getBankingHandlers()[0]).transferFromAccountToAccount(p.getName(), vars[1], amount,p); return true; <MASK>}</MASK> <MASK>}</MASK> <MASK>}</MASK> else { p.sendMessage(ChatColor.RED + coHa.getString("chat.prefix") + "Wrong Syntax or missing permissions! Please see /bank help for more information!"); return true; <MASK>}</MASK> <MASK>}</MASK> else { if (cmdlabel.equalsIgnoreCase("bankadmin") || cmdlabel.equalsIgnoreCase("bcadmin")) { if (vars.length == 0) { sendAdminHelp(p); return true; <MASK>}</MASK> else if (vars.length == 1) { if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.help"))) { sendAdminHelp(p); return true; <MASK>}</MASK> if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.reloadconfig")) && (Bankcraft.perms.has(p, "bankcraft.command.reloadconfig") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) { bankcraft.reloadConfig(); p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Config reloaded!"); return true; <MASK>}</MASK> <MASK>}</MASK> else if (vars.length == 2) { if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.clear")) && (Bankcraft.perms.has(p, "bankcraft.command.clear") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) { bankcraft.getMoneyDatabaseInterface().setBalance(vars[1], 0D); p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Account cleared!"); return true; <MASK>}</MASK> if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.clearxp")) && (Bankcraft.perms.has(p, "bankcraft.command.clearxp") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) { bankcraft.getExperienceDatabaseInterface().setBalance(vars[1], 0); p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "XP-Account cleared!"); return true; <MASK>}</MASK> <MASK>}</MASK> else if (vars.length == 3) { if (Util.isDouble(vars[2])) { if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.set")) && (Bankcraft.perms.has(p, "bankcraft.command.set") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) { bankcraft.getMoneyDatabaseInterface().setBalance(vars[1], Double.parseDouble(vars[2])); p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Account set!"); return true; <MASK>}</MASK> if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.setxp")) && (Bankcraft.perms.has(p, "bankcraft.command.setxp") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) { bankcraft.getExperienceDatabaseInterface().setBalance(vars[1], Integer.parseInt(vars[2])); p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "XP-Account set!"); return true; <MASK>}</MASK> if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.grant")) && (Bankcraft.perms.has(p, "bankcraft.command.grant") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) { bankcraft.getMoneyDatabaseInterface().addToAccount(vars[1], Double.parseDouble(vars[2])); p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Granted "+vars[2]+" Money to "+vars[1]+"!"); return true; <MASK>}</MASK> if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.grantxp")) && (Bankcraft.perms.has(p, "bankcraft.command.grantxp") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) { bankcraft.getExperienceDatabaseInterface().addToAccount(vars[1], Integer.parseInt(vars[2])); p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Granted "+vars[2]+" Experience to "+vars[1]+"!"); return true; <MASK>}</MASK> <MASK>}</MASK> else { if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.databaseimport")) && (Bankcraft.perms.has(p, "bankcraft.command.databaseimport") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) { p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Importing..."); DatabaseManagerInterface loadDataMan = null; AccountDatabaseInterface <Double> loadDataMoney = null; AccountDatabaseInterface <Integer> loadDataXp = null; SignDatabaseInterface loadDataSign = null; DatabaseManagerInterface saveDataMan = null; AccountDatabaseInterface <Double> saveDataMoney = null; AccountDatabaseInterface <Integer> saveDataXp = null; SignDatabaseInterface saveDataSign = null; if (vars[1].equalsIgnoreCase("flatfile")) { //Load flatFile p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Importing from flatfile..."); loadDataMan = new DatabaseManagerFlatFile(bankcraft); loadDataMoney = new MoneyFlatFileInterface(bankcraft); loadDataXp = new ExperienceFlatFileInterface(bankcraft); loadDataSign = new SignFlatFileInterface(bankcraft); <MASK>}</MASK> if (vars[1].equalsIgnoreCase("mysql")) { //Load mysql p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Importing from mysql..."); loadDataMan = new DatabaseManagerMysql(bankcraft); loadDataMoney = new MoneyMysqlInterface(bankcraft); loadDataXp = new ExperienceMysqlInterface(bankcraft); loadDataSign = new SignMysqlInterface(bankcraft); <MASK>}</MASK> if (vars[2].equalsIgnoreCase("flatfile")) { //Load flatFile p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Exporting to flatfile..."); saveDataMan = new DatabaseManagerFlatFile(bankcraft); saveDataMoney = new MoneyFlatFileInterface(bankcraft); saveDataXp = new ExperienceFlatFileInterface(bankcraft); saveDataSign = new SignFlatFileInterface(bankcraft); <MASK>}</MASK> if (vars[2].equalsIgnoreCase("mysql")) { //Load mysql p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Exporting to mysql..."); saveDataMan = new DatabaseManagerMysql(bankcraft); saveDataMoney = new MoneyMysqlInterface(bankcraft); saveDataXp = new ExperienceMysqlInterface(bankcraft); saveDataSign = new SignMysqlInterface(bankcraft); <MASK>}</MASK> //get them ready loadDataMan.setupDatabase(); saveDataMan.setupDatabase(); //move money data for (String accountName: loadDataMoney.getAccounts()) { saveDataMoney.setBalance(accountName, loadDataMoney.getBalance(accountName)); <MASK>}</MASK> //move xp data for (String accountName: loadDataXp.getAccounts()) { saveDataXp.setBalance(accountName, loadDataXp.getBalance(accountName)); <MASK>}</MASK> //move sign data String amounts; String[] amountsArray; int type; for (Location location: loadDataSign.getLocations(-1, null)) { //Get amounts amountsArray = loadDataSign.getAmounts((int)location.getX(), (int)location.getY(), (int)location.getZ(), location.getWorld()); amounts = amountsArray[0]; for (int i = 1; i< amountsArray.length; i++) { amounts+=":"+amountsArray[i]; <MASK>}</MASK> //Get type type = loadDataSign.getType((int)location.getX(), (int)location.getY(), (int)location.getZ(), location.getWorld()); //Create new sign in save database saveDataSign.createNewSign((int)location.getX(), (int)location.getY(), (int)location.getZ(), location.getWorld(), type, amounts); <MASK>}</MASK> //close databases loadDataMan.closeDatabase(); saveDataMan.closeDatabase(); //Send success message p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Moved all data from "+vars[1]+" to "+vars[2]+"!"); return true; <MASK>}</MASK> <MASK>}</MASK> <MASK>}</MASK> else { p.sendMessage(ChatColor.RED + coHa.getString("chat.prefix") + "Wrong Syntax or missing permissions! Please see /bank help for more information!"); <MASK>}</MASK> return true; <MASK>}</MASK> <MASK>}</MASK> <MASK>}</MASK> else { Bankcraft.log.info("[Bankcraft] Please use this ingame!"); <MASK>}</MASK> return false; <MASK>}</MASK>"
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 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
"protected void addActorSprite (Actor actor) { addPreloads(actor); int id = actor.getId(); int timestamp = _records.get(_records.size() - 1).getTimestamp(); if (actor instanceof Prespawnable && ((Prespawnable)actor).getClientOid() == _ctx.getClient().getClientOid()) { ActorSprite sprite = _actorSprites.remove(-actor.getCreated()); if (sprite != null) { _actorSprites.put(id, sprite); sprite.reinit(timestamp, actor); return; } } ActorSprite sprite = new ActorSprite(_ctx, this, timestamp, actor); _actorSprites.put(id, sprite); if (id == _ctrl.getControlledId()) { _controlledSprite = sprite; _ctrl.controlledActorAdded(timestamp, actor); } if (id == _ctrl.getTargetId()) { _targetSprite = sprite; } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addActorSprite"
"protected void addActorSprite (Actor actor) { addPreloads(actor); int id = actor.getId(); int timestamp = _records.get(_records.size() - 1).getTimestamp(); if (actor instanceof Prespawnable && ((Prespawnable)actor).getClientOid() == _ctx.getClient().getClientOid()) { ActorSprite sprite = _actorSprites.remove(-actor.getCreated()); if (sprite != null) { _actorSprites.put(id, sprite); sprite.reinit(timestamp, actor); } <MASK>return;</MASK> } ActorSprite sprite = new ActorSprite(_ctx, this, timestamp, actor); _actorSprites.put(id, sprite); if (id == _ctrl.getControlledId()) { _controlledSprite = sprite; _ctrl.controlledActorAdded(timestamp, actor); } if (id == _ctrl.getTargetId()) { _targetSprite = sprite; } }"
Inversion-Mutation
megadiff
"public void dispose() { try { myEventBroadcaster.removeListener(myUserAddedCallbackListener); myUserMonitorThread.shutdown(); } catch (Throwable e) { LOG.info(e); } final P2PServer p2PServer = myP2PServer; if (p2PServer != null) { try { p2PServer.shutdown(); } catch (Throwable e) { LOG.info(e); } } myOnlineUsers.clear(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "dispose"
"public void dispose() { <MASK>myEventBroadcaster.removeListener(myUserAddedCallbackListener);</MASK> try { myUserMonitorThread.shutdown(); } catch (Throwable e) { LOG.info(e); } final P2PServer p2PServer = myP2PServer; if (p2PServer != null) { try { p2PServer.shutdown(); } catch (Throwable e) { LOG.info(e); } } myOnlineUsers.clear(); }"
Inversion-Mutation
megadiff
"@EventHandler public void tickCalcsAndLegacy(VehicleUpdateEvent event) { // start vehicleupdate mechs Vehicle vehicle = event.getVehicle(); Entity passenger = vehicle.getPassenger(); Boolean driven = true; if (passenger == null || !(vehicle instanceof Minecart)) { return; } if (!(passenger instanceof Player)) { while (!(passenger instanceof Player) && passenger.getPassenger() != null) { passenger = passenger.getPassenger(); } if (!(passenger instanceof Player)) { driven = false; } } if(!driven){ return; //Forget extra physics, takes too much strain with extra entities } if(!(event instanceof ucarUpdateEvent)){ if(vehicle.hasMetadata("car.vec")){ ucarUpdateEvent evt = (ucarUpdateEvent) vehicle.getMetadata("car.vec").get(0).value(); evt.player = ((Player)passenger); //Make sure player is correct ucars.plugin.getServer().getPluginManager().callEvent(evt); return; } } Location under = vehicle.getLocation(); under.setY(vehicle.getLocation().getY() - 1); // Block underunderblock = underblock.getRelative(BlockFace.DOWN); Block normalblock = vehicle.getLocation().getBlock(); /* * if(underblock.getTypeId() == 0 || underblock.getTypeId() == 10 || * underblock.getTypeId() == 11 || underblock.getTypeId() == 8 || * underblock.getTypeId() == 9 && underunderblock.getTypeId() == 0 || * underunderblock.getTypeId() == 10 || underunderblock.getTypeId() == * 11 || underunderblock.getTypeId() == 8 || underunderblock.getTypeId() * == 9){ return; } */ Player player = null; if (driven) { player = (Player) passenger; } if (vehicle instanceof Minecart) { if (!carsEnabled) { return; } Minecart car = (Minecart) vehicle; if (!isACar(car)) { return; } Vector vel = car.getVelocity(); if (car.getVelocity().getY() > 0.1 && !car.hasMetadata("car.falling") && !car.hasMetadata("car.ascending")) { // Fix jumping bug // in most occasions if (car.hasMetadata("car.jumping")) { vel.setY(2.5); car.removeMetadata("car.jumping", plugin); } else if (car.hasMetadata("car.jumpFull")) { // Jumping a full block if (car.getVelocity().getY() > 10) { vel.setY(5); } car.removeMetadata("car.jumpFull", plugin); } else { vel.setY(0); } car.setVelocity(vel); } // Make jumping work when not moving // Calculate jumping gravity if (car.hasMetadata("car.falling")) { List<MetadataValue> falling = car.getMetadata("car.falling"); StatValue val = null; for (MetadataValue fall : falling) { if (fall instanceof StatValue) { val = (StatValue) fall; } } if (val != null) { if (!car.hasMetadata("car.fallingPause")) { double gravity = (Double) val.getValue(); double newGravity = gravity + (gravity * (gravity / 6)); car.removeMetadata("car.falling", val.getOwningPlugin()); if (!(gravity > 0.35)) { car.setMetadata("car.falling", new StatValue( newGravity, ucars.plugin)); vel.setY(-(gravity * 1.333 + 0.2d)); car.setVelocity(vel); } } else { car.removeMetadata("car.fallingPause", plugin); } } } /* * Material carBlock = car.getLocation().getBlock().getType(); if * (carBlock == Material.WOOD_STAIRS || carBlock == * Material.COBBLESTONE_STAIRS || carBlock == Material.BRICK_STAIRS * || carBlock == Material.SMOOTH_STAIRS || carBlock == * Material.NETHER_BRICK_STAIRS || carBlock == * Material.SANDSTONE_STAIRS || carBlock == * Material.SPRUCE_WOOD_STAIRS || carBlock == * Material.BIRCH_WOOD_STAIRS || carBlock == * Material.JUNGLE_WOOD_STAIRS || carBlock == * Material.QUARTZ_STAIRS) { Vector vel = car.getVelocity(); * vel.setY(0.5); car.setVelocity(vel); } */ final Minecart cart = car; Runnable onDeath = new Runnable() { // @Override public void run() { plugin.getServer().getPluginManager() .callEvent(new ucarDeathEvent(cart)); } }; CarHealthData health = new CarHealthData( defaultHealth, onDeath, plugin); Boolean recalculateHealth = false; // It is a valid car! // START ON TICK CALCULATIONS if (car.hasMetadata("carhealth")) { List<MetadataValue> vals = car.getMetadata("carhealth"); for (MetadataValue val : vals) { if (val instanceof CarHealthData) { health = (CarHealthData) val; } } } // Calculate health based on location if (normalblock.getType().equals(Material.WATER) || normalblock.getType().equals(Material.STATIONARY_WATER)) { double damage = damage_water; if (damage > 0) { if (driven) { double max = defaultHealth; double left = health.getHealth() - damage; ChatColor color = ChatColor.YELLOW; if (left > (max * 0.66)) { color = ChatColor.GREEN; } if (left < (max * 0.33)) { color = ChatColor.RED; } player.sendMessage(ChatColor.RED + "-" + damage + "[" + Material.WATER.name().toLowerCase() + "]" + color + " (" + left + ")"); } health.damage(damage); recalculateHealth = true; } } if (normalblock.getType().equals(Material.LAVA) || normalblock.getType().equals(Material.STATIONARY_LAVA)) { double damage = damage_lava; if (damage > 0) { if (driven) { double max = defaultHealth; double left = health.getHealth() - damage; ChatColor color = ChatColor.YELLOW; if (left > (max * 0.66)) { color = ChatColor.GREEN; } if (left < (max * 0.33)) { color = ChatColor.RED; } player.sendMessage(ChatColor.RED + "-" + damage + "[" + Material.LAVA.name().toLowerCase() + "]" + color + " (" + left + ")"); } health.damage(damage); recalculateHealth = true; } } if (recalculateHealth) { if (car.hasMetadata("carhealth")) { car.removeMetadata("carhealth", plugin); } car.setMetadata("carhealth", health); } // End health calculations if (!driven) { return; } // Do calculations for when driven // END ON TICK CALCULATIONS // end vehicleupdate mechs // start legacy controls if (plugin.protocolLib) { return; } // Attempt pre-1.6 controls Vector playerVelocity = car.getPassenger().getVelocity(); ucarUpdateEvent ucarupdate = new ucarUpdateEvent(car, playerVelocity, player); plugin.getServer().getPluginManager().callEvent(ucarupdate); return; } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "tickCalcsAndLegacy"
"@EventHandler public void tickCalcsAndLegacy(VehicleUpdateEvent event) { // start vehicleupdate mechs Vehicle vehicle = event.getVehicle(); Entity passenger = vehicle.getPassenger(); Boolean driven = true; if (passenger == null || !(vehicle instanceof Minecart)) { <MASK>return;</MASK> } if (!(passenger instanceof Player)) { while (!(passenger instanceof Player) && passenger.getPassenger() != null) { passenger = passenger.getPassenger(); } if (!(passenger instanceof Player)) { driven = false; } } if(!driven){ <MASK>return;</MASK> //Forget extra physics, takes too much strain with extra entities } if(!(event instanceof ucarUpdateEvent)){ if(vehicle.hasMetadata("car.vec")){ ucarUpdateEvent evt = (ucarUpdateEvent) vehicle.getMetadata("car.vec").get(0).value(); evt.player = ((Player)passenger); //Make sure player is correct ucars.plugin.getServer().getPluginManager().callEvent(evt); } <MASK>return;</MASK> } Location under = vehicle.getLocation(); under.setY(vehicle.getLocation().getY() - 1); // Block underunderblock = underblock.getRelative(BlockFace.DOWN); Block normalblock = vehicle.getLocation().getBlock(); /* * if(underblock.getTypeId() == 0 || underblock.getTypeId() == 10 || * underblock.getTypeId() == 11 || underblock.getTypeId() == 8 || * underblock.getTypeId() == 9 && underunderblock.getTypeId() == 0 || * underunderblock.getTypeId() == 10 || underunderblock.getTypeId() == * 11 || underunderblock.getTypeId() == 8 || underunderblock.getTypeId() * == 9){ <MASK>return;</MASK> } */ Player player = null; if (driven) { player = (Player) passenger; } if (vehicle instanceof Minecart) { if (!carsEnabled) { <MASK>return;</MASK> } Minecart car = (Minecart) vehicle; if (!isACar(car)) { <MASK>return;</MASK> } Vector vel = car.getVelocity(); if (car.getVelocity().getY() > 0.1 && !car.hasMetadata("car.falling") && !car.hasMetadata("car.ascending")) { // Fix jumping bug // in most occasions if (car.hasMetadata("car.jumping")) { vel.setY(2.5); car.removeMetadata("car.jumping", plugin); } else if (car.hasMetadata("car.jumpFull")) { // Jumping a full block if (car.getVelocity().getY() > 10) { vel.setY(5); } car.removeMetadata("car.jumpFull", plugin); } else { vel.setY(0); } car.setVelocity(vel); } // Make jumping work when not moving // Calculate jumping gravity if (car.hasMetadata("car.falling")) { List<MetadataValue> falling = car.getMetadata("car.falling"); StatValue val = null; for (MetadataValue fall : falling) { if (fall instanceof StatValue) { val = (StatValue) fall; } } if (val != null) { if (!car.hasMetadata("car.fallingPause")) { double gravity = (Double) val.getValue(); double newGravity = gravity + (gravity * (gravity / 6)); car.removeMetadata("car.falling", val.getOwningPlugin()); if (!(gravity > 0.35)) { car.setMetadata("car.falling", new StatValue( newGravity, ucars.plugin)); vel.setY(-(gravity * 1.333 + 0.2d)); car.setVelocity(vel); } } else { car.removeMetadata("car.fallingPause", plugin); } } } /* * Material carBlock = car.getLocation().getBlock().getType(); if * (carBlock == Material.WOOD_STAIRS || carBlock == * Material.COBBLESTONE_STAIRS || carBlock == Material.BRICK_STAIRS * || carBlock == Material.SMOOTH_STAIRS || carBlock == * Material.NETHER_BRICK_STAIRS || carBlock == * Material.SANDSTONE_STAIRS || carBlock == * Material.SPRUCE_WOOD_STAIRS || carBlock == * Material.BIRCH_WOOD_STAIRS || carBlock == * Material.JUNGLE_WOOD_STAIRS || carBlock == * Material.QUARTZ_STAIRS) { Vector vel = car.getVelocity(); * vel.setY(0.5); car.setVelocity(vel); } */ final Minecart cart = car; Runnable onDeath = new Runnable() { // @Override public void run() { plugin.getServer().getPluginManager() .callEvent(new ucarDeathEvent(cart)); } }; CarHealthData health = new CarHealthData( defaultHealth, onDeath, plugin); Boolean recalculateHealth = false; // It is a valid car! // START ON TICK CALCULATIONS if (car.hasMetadata("carhealth")) { List<MetadataValue> vals = car.getMetadata("carhealth"); for (MetadataValue val : vals) { if (val instanceof CarHealthData) { health = (CarHealthData) val; } } } // Calculate health based on location if (normalblock.getType().equals(Material.WATER) || normalblock.getType().equals(Material.STATIONARY_WATER)) { double damage = damage_water; if (damage > 0) { if (driven) { double max = defaultHealth; double left = health.getHealth() - damage; ChatColor color = ChatColor.YELLOW; if (left > (max * 0.66)) { color = ChatColor.GREEN; } if (left < (max * 0.33)) { color = ChatColor.RED; } player.sendMessage(ChatColor.RED + "-" + damage + "[" + Material.WATER.name().toLowerCase() + "]" + color + " (" + left + ")"); } health.damage(damage); recalculateHealth = true; } } if (normalblock.getType().equals(Material.LAVA) || normalblock.getType().equals(Material.STATIONARY_LAVA)) { double damage = damage_lava; if (damage > 0) { if (driven) { double max = defaultHealth; double left = health.getHealth() - damage; ChatColor color = ChatColor.YELLOW; if (left > (max * 0.66)) { color = ChatColor.GREEN; } if (left < (max * 0.33)) { color = ChatColor.RED; } player.sendMessage(ChatColor.RED + "-" + damage + "[" + Material.LAVA.name().toLowerCase() + "]" + color + " (" + left + ")"); } health.damage(damage); recalculateHealth = true; } } if (recalculateHealth) { if (car.hasMetadata("carhealth")) { car.removeMetadata("carhealth", plugin); } car.setMetadata("carhealth", health); } // End health calculations if (!driven) { <MASK>return;</MASK> } // Do calculations for when driven // END ON TICK CALCULATIONS // end vehicleupdate mechs // start legacy controls if (plugin.protocolLib) { <MASK>return;</MASK> } // Attempt pre-1.6 controls Vector playerVelocity = car.getPassenger().getVelocity(); ucarUpdateEvent ucarupdate = new ucarUpdateEvent(car, playerVelocity, player); plugin.getServer().getPluginManager().callEvent(ucarupdate); <MASK>return;</MASK> } }"
Inversion-Mutation
megadiff
"@Override public void handle(HttpExchange exchange) throws IOException { try (final InputStream is = exchange.getRequestBody(); final InputStreamReader sr = new InputStreamReader(is); final BufferedReader br = new BufferedReader(sr);) { // read body content final String postBody = br.readLine(); if (postBody == null) { reply(exchange, vfs.get(VirtualFileSystem.Error.BAD_REQUEST), false); return; } // format for form content is 'fieldname=value' final int idx = postBody.indexOf('=') + 1; if (idx == -1 || postBody.length() - idx < 3) { reply(exchange, vfs.get(VirtualFileSystem.Error.BAD_REQUEST), false); return; } // Parse string into Uri final Uri uri = Uri.create(postBody.substring(idx), true); if (uri == null) { reply(exchange, vfs.get(VirtualFileSystem.Error.BAD_REQUEST), false); return; } // Refuse banned if (vfs.isBanned(uri)) { logger.warn("banned: " + uri + " - " + exchange.getRemoteAddress().getHostName()); reply(exchange, vfs.get(VirtualFileSystem.Error.FORBIDDEN_PHISHING), false); return; } // hash Uri final byte[] hashedUri = vfs.add(uri); if (hashedUri == null) { reply(exchange, vfs.get(VirtualFileSystem.Error.BAD_REQUEST), false); return; } reply(exchange, new NormalResponse(hashedUri), false); } catch (IOException e) { reply(exchange, vfs.get(VirtualFileSystem.Error.BAD_REQUEST), false); return; } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handle"
"@Override public void handle(HttpExchange exchange) throws IOException { try (final InputStream is = exchange.getRequestBody(); final InputStreamReader sr = new InputStreamReader(is); final BufferedReader br = new BufferedReader(sr);) { // read body content final String postBody = br.readLine(); if (postBody == null) { reply(exchange, vfs.get(VirtualFileSystem.Error.BAD_REQUEST), false); return; } // format for form content is 'fieldname=value' final int idx = postBody.indexOf('=') + 1; if (idx == -1 || postBody.length() - idx < 3) { reply(exchange, vfs.get(VirtualFileSystem.Error.BAD_REQUEST), false); return; } // Parse string into Uri final Uri uri = Uri.create(postBody.substring(idx), true); if (uri == null) { <MASK>logger.warn("banned: " + uri + " - " + exchange.getRemoteAddress().getHostName());</MASK> reply(exchange, vfs.get(VirtualFileSystem.Error.BAD_REQUEST), false); return; } // Refuse banned if (vfs.isBanned(uri)) { reply(exchange, vfs.get(VirtualFileSystem.Error.FORBIDDEN_PHISHING), false); return; } // hash Uri final byte[] hashedUri = vfs.add(uri); if (hashedUri == null) { reply(exchange, vfs.get(VirtualFileSystem.Error.BAD_REQUEST), false); return; } reply(exchange, new NormalResponse(hashedUri), false); } catch (IOException e) { reply(exchange, vfs.get(VirtualFileSystem.Error.BAD_REQUEST), false); return; } }"