type
stringclasses
1 value
dataset
stringclasses
1 value
input
stringlengths
75
160k
instruction
stringlengths
117
171
output
stringlengths
88
168k
Inversion-Mutation
megadiff
"@Before @Transactional public void clearDownDb() { LOGGER.info("STARTING CLEAR DOWN DB"); // this should have all the tables in - extend when necessary // importer tables jdbcTemplate.execute("delete from centre"); jdbcTemplate.execute("delete from patient"); jdbcTemplate.execute("delete from testresult"); jdbcTemplate.execute("delete from letter"); jdbcTemplate.execute("delete from diagnosis"); jdbcTemplate.execute("delete from medicine"); // user tables jdbcTemplate.execute("delete from usermapping"); jdbcTemplate.execute("delete from tenancyuserrole"); jdbcTemplate.execute("delete from user"); jdbcTemplate.execute("delete from tenancy"); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "clearDownDb"
"@Before @Transactional public void clearDownDb() { LOGGER.info("STARTING CLEAR DOWN DB"); // this should have all the tables in - extend when necessary // importer tables jdbcTemplate.execute("delete from centre"); jdbcTemplate.execute("delete from patient"); jdbcTemplate.execute("delete from testresult"); jdbcTemplate.execute("delete from letter"); jdbcTemplate.execute("delete from diagnosis"); jdbcTemplate.execute("delete from medicine"); // user tables jdbcTemplate.execute("delete from usermapping"); <MASK>jdbcTemplate.execute("delete from user");</MASK> jdbcTemplate.execute("delete from tenancyuserrole"); jdbcTemplate.execute("delete from tenancy"); }"
Inversion-Mutation
megadiff
"public File saveBuild(Jar jar) throws Exception { try { String bsn = jar.getName(); File f = getOutputFile(bsn); String msg = ""; if (!f.exists() || f.lastModified() < jar.lastModified()) { reportNewer(f.lastModified(), jar); f.delete(); if (!f.getParentFile().isDirectory()) f.getParentFile().mkdirs(); jar.write(f); getWorkspace().changedFile(f); } else { msg = "(not modified since " + new Date(f.lastModified()) + ")"; } trace(jar.getName() + " (" + f.getName() + ") " + jar.getResources().size() + " " + msg); return f; } finally { jar.close(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "saveBuild"
"public File saveBuild(Jar jar) throws Exception { try { String bsn = jar.getName(); File f = getOutputFile(bsn); String msg = ""; if (!f.exists() || f.lastModified() < jar.lastModified()) { reportNewer(f.lastModified(), jar); f.delete(); <MASK>jar.write(f);</MASK> if (!f.getParentFile().isDirectory()) f.getParentFile().mkdirs(); getWorkspace().changedFile(f); } else { msg = "(not modified since " + new Date(f.lastModified()) + ")"; } trace(jar.getName() + " (" + f.getName() + ") " + jar.getResources().size() + " " + msg); return f; } finally { jar.close(); } }"
Inversion-Mutation
megadiff
"@Override protected void processUnsolicited (Parcel p) { Object ret; int dataPosition = p.dataPosition(); // save off position within the Parcel int response = p.readInt(); switch(response) { case RIL_UNSOL_RIL_CONNECTED: // Fix for NV/RUIM setting on CDMA SIM devices // skip getcdmascriptionsource as if qualcomm handles it in the ril binary ret = responseInts(p); setRadioPower(false, null); setPreferredNetworkType(mPreferredNetworkType, null); notifyRegistrantsRilConnectionChanged(((int[])ret)[0]); isGSM = (mPhoneType != RILConstants.CDMA_PHONE); samsungDriverCall = (needsOldRilFeature("newDriverCall") && !isGSM) || mRilVersion < 7 ? false : true; break; case RIL_UNSOL_NITZ_TIME_RECEIVED: handleNitzTimeReceived(p); break; default: // Rewind the Parcel p.setDataPosition(dataPosition); // Forward responses that we are not overriding to the super class super.processUnsolicited(p); return; } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "processUnsolicited"
"@Override protected void processUnsolicited (Parcel p) { Object ret; int dataPosition = p.dataPosition(); // save off position within the Parcel int response = p.readInt(); switch(response) { case RIL_UNSOL_RIL_CONNECTED: // Fix for NV/RUIM setting on CDMA SIM devices // skip getcdmascriptionsource as if qualcomm handles it in the ril binary ret = responseInts(p); setRadioPower(false, null); setPreferredNetworkType(mPreferredNetworkType, null); notifyRegistrantsRilConnectionChanged(((int[])ret)[0]); <MASK>samsungDriverCall = (needsOldRilFeature("newDriverCall") && !isGSM) || mRilVersion < 7 ? false : true;</MASK> isGSM = (mPhoneType != RILConstants.CDMA_PHONE); break; case RIL_UNSOL_NITZ_TIME_RECEIVED: handleNitzTimeReceived(p); break; default: // Rewind the Parcel p.setDataPosition(dataPosition); // Forward responses that we are not overriding to the super class super.processUnsolicited(p); return; } }"
Inversion-Mutation
megadiff
"public void profileRETI(long cycles) { if (servicedInterrupt > -1) { interruptTime[servicedInterrupt] += cycles - lastInterruptTime[servicedInterrupt]; interruptCount[servicedInterrupt]++; } newIRQ = false; if (logger != null && !hideIRQ) { logger.println("----- Interrupt vector " + servicedInterrupt + " returned - elapsed: " + (cycles - lastInterruptTime[servicedInterrupt])); } interruptLevel = 0; /* what if interrupt from interrupt ? */ servicedInterrupt = -1; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "profileRETI"
"public void profileRETI(long cycles) { if (servicedInterrupt > -1) { interruptTime[servicedInterrupt] += cycles - lastInterruptTime[servicedInterrupt]; interruptCount[servicedInterrupt]++; } newIRQ = false; if (logger != null && !hideIRQ) { logger.println("----- Interrupt vector " + servicedInterrupt + " returned - elapsed: " + (cycles - lastInterruptTime[servicedInterrupt])); <MASK>interruptLevel = 0;</MASK> } /* what if interrupt from interrupt ? */ servicedInterrupt = -1; }"
Inversion-Mutation
megadiff
"private void storeIcon(Bitmap icon) { // Do this first in case the download failed. if (mTab != null) { // Remove the touch icon loader from the BrowserActivity. mTab.mTouchIconLoader = null; } if (icon == null || mCursor == null || isCancelled()) { return; } if (mCursor.moveToFirst()) { final ByteArrayOutputStream os = new ByteArrayOutputStream(); icon.compress(Bitmap.CompressFormat.PNG, 100, os); ContentValues values = new ContentValues(); values.put(Images.TOUCH_ICON, os.toByteArray()); do { values.put(Images.URL, mCursor.getString(0)); mContentResolver.update(Images.CONTENT_URI, values, null, null); } while (mCursor.moveToNext()); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "storeIcon"
"private void storeIcon(Bitmap icon) { // Do this first in case the download failed. if (mTab != null) { // Remove the touch icon loader from the BrowserActivity. mTab.mTouchIconLoader = null; } if (icon == null || mCursor == null || isCancelled()) { return; } if (mCursor.moveToFirst()) { final ByteArrayOutputStream os = new ByteArrayOutputStream(); icon.compress(Bitmap.CompressFormat.PNG, 100, os); ContentValues values = new ContentValues(); values.put(Images.TOUCH_ICON, os.toByteArray()); <MASK>values.put(Images.URL, mCursor.getString(0));</MASK> do { mContentResolver.update(Images.CONTENT_URI, values, null, null); } while (mCursor.moveToNext()); } }"
Inversion-Mutation
megadiff
"private BranchGroup createSceneGraph(Canvas3D cv) { int n = 5; /* root */ BranchGroup root = new BranchGroup(); bounds = new BoundingSphere(); /* testTransform */ Transform3D tr = new Transform3D(); tr.setTranslation(new Vector3f(0.1f, 0.1f, 0.1f)); TransformGroup testTransform = new TransformGroup(tr); testTransform.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); // rotere enkelte objekter /*testTransform.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); testTransform.setCapability(TransformGroup.ALLOW_TRANSFORM_READ); MouseRotate rotator1 = new MouseRotate(testTransform); BoundingSphere bounds = new BoundingSphere(); rotator1.setSchedulingBounds(bounds); testTransform.addChild(rotator1); */ PickRotateBehavior rotatorObjekt = new PickRotateBehavior(root, cv, bounds, PickTool.GEOMETRY); root.addChild(rotatorObjekt); //Spin root.addChild(testTransform); Alpha alpha = new Alpha(0, 8000); RotationInterpolator rotator = new RotationInterpolator(alpha, testTransform); rotator.setSchedulingBounds(bounds); testTransform.addChild(rotator); /* background and lights */ Background background = new Background(1.0f, 1.0f, 1.0f); //Background background = new Background(0f, 0f, 0f); background.setApplicationBounds(bounds); root.addChild(background); AmbientLight light = new AmbientLight(true, new Color3f(Color.white)); light.setInfluencingBounds(bounds); root.addChild(light); PointLight ptlight = new PointLight(new Color3f(Color.WHITE), new Point3f(3f, 3f, 3f), new Point3f(1f, 0f, 0f)); ptlight.setInfluencingBounds(bounds); root.addChild(ptlight); /* Material */ material = new Material(); // temp material.setAmbientColor(new Color3f(0f,0f,0f)); material.setDiffuseColor(new Color3f(0.15f,0.15f,0.25f)); /* Making shapes from 0 to n */ // Make arrays shapeMove = new TransformGroup[n]; shapes = new Primitive[n]; rotPosScale = new RotPosScalePathInterpolator[n]; appearance = new Appearance[n]; behave = new CaseBehavior[n]; behaveRotating = new ArrayList<rotationBehave>(); // Make shapes for (int i = 0; i < n; i++) { makeShapes(i); testTransform.addChild(shapeMove[i]); root.addChild(behave[i]); } // Webcam box TransformGroup wbTransform = new TransformGroup(); Transform3D webTr = new Transform3D(); webTr.setTranslation(new Vector3d(-0.5,0.5,0)); wbTransform.setTransform(webTr); webcamBox = makeCamShape(); TransformGroup rotatorCam = new TransformGroup(); rotatorCam.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); rotatorCam.addChild(webcamBox); wbTransform.addChild(rotatorCam); camBehave = new CamBehavior(webcamBox, rotatorCam); camBehave.setSchedulingBounds(bounds); root.addChild(camBehave); testTransform.addChild(wbTransform); /* SharedGroup sg = new SharedGroup(); // object for (int i = 0; i < n; i++) { Transform3D tr1 = new Transform3D(); tr1.setRotation(new AxisAngle4d(0, 1, 0, 2 * Math.PI * ((double) i / n))); TransformGroup tgNew = new TransformGroup(tr1); Link link = new Link(); link.setSharedGroup(sg); tgNew.addChild(link); tg.addChild(tgNew); }*/ /* Shape3D torus1 = new Torus(0.1, 0.7); Appearance ap = new Appearance(); ap.setMaterial(new Material()); torus1.setAppearance(ap); tg.addChild(torus1); Shape3D torus2 = new Torus(0.1, 0.4); ap = new Appearance(); ap.setMaterial(new Material()); ap.setTransparencyAttributes(new TransparencyAttributes( TransparencyAttributes.BLENDED, 0.0f)); torus2.setAppearance(ap); Transform3D tr2 = new Transform3D(); tr2.setRotation(new AxisAngle4d(1, 0, 0, Math.PI / 2)); tr2.setTranslation(new Vector3d(0.8, 0, 0)); TransformGroup tg2 = new TransformGroup(tr2); tg2.addChild(torus2); */ // SharedGroup /* sg.addChild(tg2); Alpha alpha = new Alpha(0, 8000); RotationInterpolator rotator = new RotationInterpolator(alpha, spin); rotator.setSchedulingBounds(bounds); spin.addChild(rotator); */ return root; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createSceneGraph"
"private BranchGroup createSceneGraph(Canvas3D cv) { int n = 5; /* root */ BranchGroup root = new BranchGroup(); bounds = new BoundingSphere(); /* testTransform */ Transform3D tr = new Transform3D(); tr.setTranslation(new Vector3f(0.1f, 0.1f, 0.1f)); TransformGroup testTransform = new TransformGroup(tr); testTransform.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); // rotere enkelte objekter /*testTransform.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); testTransform.setCapability(TransformGroup.ALLOW_TRANSFORM_READ); MouseRotate rotator1 = new MouseRotate(testTransform); BoundingSphere bounds = new BoundingSphere(); rotator1.setSchedulingBounds(bounds); testTransform.addChild(rotator1); */ PickRotateBehavior rotatorObjekt = new PickRotateBehavior(root, cv, bounds, PickTool.GEOMETRY); root.addChild(rotatorObjekt); //Spin root.addChild(testTransform); Alpha alpha = new Alpha(0, 8000); RotationInterpolator rotator = new RotationInterpolator(alpha, testTransform); rotator.setSchedulingBounds(bounds); testTransform.addChild(rotator); /* background and lights */ Background background = new Background(1.0f, 1.0f, 1.0f); //Background background = new Background(0f, 0f, 0f); background.setApplicationBounds(bounds); root.addChild(background); AmbientLight light = new AmbientLight(true, new Color3f(Color.white)); light.setInfluencingBounds(bounds); root.addChild(light); PointLight ptlight = new PointLight(new Color3f(Color.WHITE), new Point3f(3f, 3f, 3f), new Point3f(1f, 0f, 0f)); ptlight.setInfluencingBounds(bounds); root.addChild(ptlight); /* Material */ material = new Material(); // temp material.setAmbientColor(new Color3f(0f,0f,0f)); material.setDiffuseColor(new Color3f(0.15f,0.15f,0.25f)); /* Making shapes from 0 to n */ // Make arrays shapeMove = new TransformGroup[n]; shapes = new Primitive[n]; rotPosScale = new RotPosScalePathInterpolator[n]; appearance = new Appearance[n]; behave = new CaseBehavior[n]; behaveRotating = new ArrayList<rotationBehave>(); // Make shapes for (int i = 0; i < n; i++) { makeShapes(i); testTransform.addChild(shapeMove[i]); root.addChild(behave[i]); } // Webcam box TransformGroup wbTransform = new TransformGroup(); Transform3D webTr = new Transform3D(); webTr.setTranslation(new Vector3d(-0.5,0.5,0)); wbTransform.setTransform(webTr); webcamBox = makeCamShape(); <MASK>root.addChild(camBehave);</MASK> TransformGroup rotatorCam = new TransformGroup(); rotatorCam.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); rotatorCam.addChild(webcamBox); wbTransform.addChild(rotatorCam); camBehave = new CamBehavior(webcamBox, rotatorCam); camBehave.setSchedulingBounds(bounds); testTransform.addChild(wbTransform); /* SharedGroup sg = new SharedGroup(); // object for (int i = 0; i < n; i++) { Transform3D tr1 = new Transform3D(); tr1.setRotation(new AxisAngle4d(0, 1, 0, 2 * Math.PI * ((double) i / n))); TransformGroup tgNew = new TransformGroup(tr1); Link link = new Link(); link.setSharedGroup(sg); tgNew.addChild(link); tg.addChild(tgNew); }*/ /* Shape3D torus1 = new Torus(0.1, 0.7); Appearance ap = new Appearance(); ap.setMaterial(new Material()); torus1.setAppearance(ap); tg.addChild(torus1); Shape3D torus2 = new Torus(0.1, 0.4); ap = new Appearance(); ap.setMaterial(new Material()); ap.setTransparencyAttributes(new TransparencyAttributes( TransparencyAttributes.BLENDED, 0.0f)); torus2.setAppearance(ap); Transform3D tr2 = new Transform3D(); tr2.setRotation(new AxisAngle4d(1, 0, 0, Math.PI / 2)); tr2.setTranslation(new Vector3d(0.8, 0, 0)); TransformGroup tg2 = new TransformGroup(tr2); tg2.addChild(torus2); */ // SharedGroup /* sg.addChild(tg2); Alpha alpha = new Alpha(0, 8000); RotationInterpolator rotator = new RotationInterpolator(alpha, spin); rotator.setSchedulingBounds(bounds); spin.addChild(rotator); */ return root; }"
Inversion-Mutation
megadiff
"public void process(Tag tag) { if (firstChildIsHeader) { if (!tag.getName().equalsIgnoreCase("p")) { final CustomTag customTag; // http://jira.opensymphony.com/browse/SIM-202 if (tag.getAttributeCount() == 0) { customTag = new CustomTag(tag.getName(), tag.getType()); } else { customTag = new CustomTag(tag); } customTag.addAttribute("class", "FirstChild"); tag = customTag; } firstChildIsHeader = false; } tag.writeTo(currentBuffer()); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "process"
"public void process(Tag tag) { if (firstChildIsHeader) { if (!tag.getName().equalsIgnoreCase("p")) { final CustomTag customTag; // http://jira.opensymphony.com/browse/SIM-202 if (tag.getAttributeCount() == 0) { customTag = new CustomTag(tag.getName(), tag.getType()); } else { customTag = new CustomTag(tag); <MASK>customTag.addAttribute("class", "FirstChild");</MASK> } tag = customTag; } firstChildIsHeader = false; } tag.writeTo(currentBuffer()); }"
Inversion-Mutation
megadiff
"public void moveUnits(int units){ getFirstTerritory().setNbrOfUnits(getFirstTerritory().getNbrOfUnits()+getSecondTerritory().getNbrOfUnits() - units); getSecondTerritory().setNbrOfUnits(units); model.changed(); this.resetTerritories(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "moveUnits"
"public void moveUnits(int units){ getFirstTerritory().setNbrOfUnits(getFirstTerritory().getNbrOfUnits()+getSecondTerritory().getNbrOfUnits() - units); getSecondTerritory().setNbrOfUnits(units); <MASK>this.resetTerritories();</MASK> model.changed(); }"
Inversion-Mutation
megadiff
"public void applyFormatAction(PyEdit pyEdit, PySelection ps, IRegion[] regionsToFormat, boolean throwSyntaxError) throws BadLocationException, SyntaxErrorException { final IFormatter participant = getFormatter(); final IDocument doc = ps.getDoc(); final SelectionKeeper selectionKeeper = new SelectionKeeper(ps); DocumentRewriteSession session = null; try{ if (regionsToFormat == null || regionsToFormat.length == 0) { if(doc instanceof IDocumentExtension4){ IDocumentExtension4 ext = (IDocumentExtension4) doc; session = ext.startRewriteSession(DocumentRewriteSessionType.STRICTLY_SEQUENTIAL); } participant.formatAll(doc, pyEdit, true, throwSyntaxError); } else { if(doc instanceof IDocumentExtension4){ IDocumentExtension4 ext = (IDocumentExtension4) doc; session = ext.startRewriteSession(DocumentRewriteSessionType.SEQUENTIAL); } participant.formatSelection(doc, regionsToFormat, pyEdit, ps); } //To finish, no matter what kind of formatting was done, check the end of line. FormatStd std = getFormat(); if(std.addNewLineAtEndOfFile){ try { int len = doc.getLength(); if(len > 0){ char lastChar = doc.getChar(len-1); if(lastChar != '\r' && lastChar != '\n'){ doc.replace(len, 0, PySelection.getDelimiter(doc)); } } } catch (Throwable e) { Log.log(e); } } }finally{ if(session != null){ ((IDocumentExtension4)doc).stopRewriteSession(session); } } selectionKeeper.restoreSelection(pyEdit.getSelectionProvider(), doc); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "applyFormatAction"
"public void applyFormatAction(PyEdit pyEdit, PySelection ps, IRegion[] regionsToFormat, boolean throwSyntaxError) throws BadLocationException, SyntaxErrorException { final IFormatter participant = getFormatter(); final IDocument doc = ps.getDoc(); final SelectionKeeper selectionKeeper = new SelectionKeeper(ps); DocumentRewriteSession session = null; try{ if (regionsToFormat == null || regionsToFormat.length == 0) { if(doc instanceof IDocumentExtension4){ IDocumentExtension4 ext = (IDocumentExtension4) doc; session = ext.startRewriteSession(DocumentRewriteSessionType.STRICTLY_SEQUENTIAL); } participant.formatAll(doc, pyEdit, true, throwSyntaxError); } else { if(doc instanceof IDocumentExtension4){ IDocumentExtension4 ext = (IDocumentExtension4) doc; session = ext.startRewriteSession(DocumentRewriteSessionType.SEQUENTIAL); } participant.formatSelection(doc, regionsToFormat, pyEdit, ps); } //To finish, no matter what kind of formatting was done, check the end of line. FormatStd std = getFormat(); if(std.addNewLineAtEndOfFile){ try { int len = doc.getLength(); <MASK>char lastChar = doc.getChar(len-1);</MASK> if(len > 0){ if(lastChar != '\r' && lastChar != '\n'){ doc.replace(len, 0, PySelection.getDelimiter(doc)); } } } catch (Throwable e) { Log.log(e); } } }finally{ if(session != null){ ((IDocumentExtension4)doc).stopRewriteSession(session); } } selectionKeeper.restoreSelection(pyEdit.getSelectionProvider(), doc); }"
Inversion-Mutation
megadiff
"@Override public void synchronize(final IProject project, SyncConfig syncConfig, IResourceDelta delta, IProgressMonitor monitor, EnumSet<SyncFlag> syncFlags) throws CoreException { RecursiveSubMonitor subMon = RecursiveSubMonitor.convert(monitor, 1000); // On first sync, place .gitignore in directories. This is useful for folders that are already present and thus are never // captured by a resource add or change event. (This can happen for projects converted to sync projects.) if (!hasBeenSynced) { hasBeenSynced = true; project.accept(new IResourceVisitor() { @Override public boolean visit(IResource resource) throws CoreException { if (irrelevantPath(project, resource)) { return false; } if (resource.getType() == IResource.FOLDER) { IFile emptyFile = project.getFile(resource.getProjectRelativePath().addTrailingSeparator() + ".gitignore"); //$NON-NLS-1$ try { if (!(emptyFile.exists())) { emptyFile.create(new ByteArrayInputStream("".getBytes()), false, null); //$NON-NLS-1$ } } catch (CoreException e) { // Nothing to do. Can happen if another thread creates the file between the check and creation. } } return true; } }); } // Make a visitor that explores the delta. At the moment, this visitor is responsible for two tasks (the list may grow in // the future): // 1) Find out if there are any "relevant" resource changes (changes that need to be mirrored remotely) // 2) Add an empty ".gitignore" file to new directories so that Git will sync them class SyncResourceDeltaVisitor implements IResourceDeltaVisitor { private boolean relevantChangeFound = false; public boolean isRelevant() { return relevantChangeFound; } @Override public boolean visit(IResourceDelta delta) throws CoreException { if (irrelevantPath(project, delta.getResource())) { return false; } else { if ((delta.getAffectedChildren().length == 0) && (delta.getFlags() != IResourceDelta.MARKERS)) { relevantChangeFound = true; } } // Add .gitignore to empty directories if (delta.getResource().getType() == IResource.FOLDER && (delta.getKind() == IResourceDelta.ADDED || delta.getKind() == IResourceDelta.CHANGED)) { IFile emptyFile = project.getFile(delta.getResource().getProjectRelativePath().addTrailingSeparator() + ".gitignore"); //$NON-NLS-1$ try { if (!(emptyFile.exists())) { emptyFile.create(new ByteArrayInputStream("".getBytes()), false, null); //$NON-NLS-1$ } } catch (CoreException e) { // Nothing to do. Can happen if another thread creates the file between the check and creation. } } return true; } } // Explore delta only if it is not null boolean hasRelevantChangedResources = false; if (delta != null) { SyncResourceDeltaVisitor visitor = new SyncResourceDeltaVisitor(); delta.accept(visitor); hasRelevantChangedResources = visitor.isRelevant(); } try { /* * A synchronize with SyncFlag.FORCE guarantees that both directories are in sync. * * More precise: it guarantees that all changes written to disk at the moment of the call are guaranteed to be * synchronized between both directories. No guarantees are given for changes occurring during the synchronize call. * * To satisfy this guarantee, this call needs to make sure that both the current delta and all outstanding sync requests * finish before this call returns. * * Example: Why sync if current delta is empty? The RemoteMakeBuilder forces a sync before and after building. In some * cases, we want to ensure repos are synchronized regardless of the passed delta, which can be set to null. */ // TODO: We are not using the individual "sync to local" and "sync to remote" flags yet. if (syncFlags.contains(SyncFlag.DISABLE_SYNC)) { return; } if ((syncFlags == SyncFlag.NO_FORCE) && (!(hasRelevantChangedResources))) { return; } int mySyncTaskId; synchronized (syncTaskId) { syncTaskId++; mySyncTaskId = syncTaskId; // suggestion for Deltas: add delta to list of deltas } synchronized (fWaitingThreadsCount) { if (fWaitingThreadsCount > 0 && syncFlags == SyncFlag.NO_FORCE) { return; // the queued thread will do the work for us. And we don't have to wait because of NO_FORCE } else { fWaitingThreadsCount++; } } // lock syncLock. interruptible by progress monitor try { while (!syncLock.tryLock(50, TimeUnit.MILLISECONDS)) { if (subMon.isCanceled()) { throw new CoreException(new Status(IStatus.CANCEL, Activator.PLUGIN_ID, Messages.GitServiceProvider_1)); } } } catch (InterruptedException e1) { throw new CoreException(new Status(IStatus.CANCEL, Activator.PLUGIN_ID, Messages.GitServiceProvider_2)); } finally { synchronized (fWaitingThreadsCount) { fWaitingThreadsCount--; } } try { // Do not sync if there are merge conflicts. // This check must be done after acquiring the sync lock. Otherwise, the merge may trigger a sync that sees no // conflicting files and proceeds to sync again - depending on how quickly the first sync records the data. if (!(this.getMergeConflictFiles(project, syncConfig).isEmpty())) { throw new RemoteSyncMergeConflictException(Messages.GitServiceProvider_4); } if (mySyncTaskId <= finishedSyncTaskId) { // some other thread has already done the work for us return; } if (syncConfig == null) { throw new RuntimeException(Messages.GitServiceProvider_3 + project.getName()); } subMon.subTask(Messages.GitServiceProvider_7); GitRemoteSyncConnection fSyncConnection = this.getSyncConnection(project, syncConfig, subMon.newChild(98)); if (fSyncConnection == null) { // Should never happen if (syncConfig.getSyncProviderId() == null) { throw new RemoteSyncException(Messages.GitServiceProvider_5); // Happens whenever connection does not exist } else { return; } } // This synchronization operation will include all tasks up to current syncTaskId // syncTaskId can be larger than mySyncTaskId (than we do also the work for other threads) // we might synchronize even more than that if a file is already saved but syncTaskId wasn't increased yet // thus we cannot guarantee a maximum but we can guarantee syncTaskId as a minimum // suggestion for Deltas: make local copy of list of deltas, remove list of deltas int willFinishTaskId; synchronized (syncTaskId) { willFinishTaskId = syncTaskId; } try { subMon.subTask(Messages.GitServiceProvider_8); fSyncConnection.sync(subMon.newChild(900), true); // Unlike other exceptions, we need to do some post-sync activities after a merge exception. // TODO: Refactor code to get rid of duplication of post-sync activities. } catch (RemoteSyncMergeConflictException e) { subMon.subTask(Messages.GitServiceProvider_9); project.refreshLocal(IResource.DEPTH_INFINITE, subMon.newChild(1)); throw e; } finishedSyncTaskId = willFinishTaskId; // TODO: review exception handling } finally { syncLock.unlock(); } // Sync successful - re-enable error messages. This is really UI code, but there is no way at the moment to notify UI // of a successful sync. SyncManager.setShowErrors(project, true); // Refresh after sync to display changes subMon.subTask(Messages.GitServiceProvider_10); project.refreshLocal(IResource.DEPTH_INFINITE, subMon.newChild(1)); } finally { if (monitor != null) { monitor.done(); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "synchronize"
"@Override public void synchronize(final IProject project, SyncConfig syncConfig, IResourceDelta delta, IProgressMonitor monitor, EnumSet<SyncFlag> syncFlags) throws CoreException { RecursiveSubMonitor subMon = RecursiveSubMonitor.convert(monitor, 1000); // On first sync, place .gitignore in directories. This is useful for folders that are already present and thus are never // captured by a resource add or change event. (This can happen for projects converted to sync projects.) if (!hasBeenSynced) { project.accept(new IResourceVisitor() { @Override public boolean visit(IResource resource) throws CoreException { if (irrelevantPath(project, resource)) { return false; } if (resource.getType() == IResource.FOLDER) { IFile emptyFile = project.getFile(resource.getProjectRelativePath().addTrailingSeparator() + ".gitignore"); //$NON-NLS-1$ try { if (!(emptyFile.exists())) { emptyFile.create(new ByteArrayInputStream("".getBytes()), false, null); //$NON-NLS-1$ } } catch (CoreException e) { // Nothing to do. Can happen if another thread creates the file between the check and creation. } } return true; } }); } <MASK>hasBeenSynced = true;</MASK> // Make a visitor that explores the delta. At the moment, this visitor is responsible for two tasks (the list may grow in // the future): // 1) Find out if there are any "relevant" resource changes (changes that need to be mirrored remotely) // 2) Add an empty ".gitignore" file to new directories so that Git will sync them class SyncResourceDeltaVisitor implements IResourceDeltaVisitor { private boolean relevantChangeFound = false; public boolean isRelevant() { return relevantChangeFound; } @Override public boolean visit(IResourceDelta delta) throws CoreException { if (irrelevantPath(project, delta.getResource())) { return false; } else { if ((delta.getAffectedChildren().length == 0) && (delta.getFlags() != IResourceDelta.MARKERS)) { relevantChangeFound = true; } } // Add .gitignore to empty directories if (delta.getResource().getType() == IResource.FOLDER && (delta.getKind() == IResourceDelta.ADDED || delta.getKind() == IResourceDelta.CHANGED)) { IFile emptyFile = project.getFile(delta.getResource().getProjectRelativePath().addTrailingSeparator() + ".gitignore"); //$NON-NLS-1$ try { if (!(emptyFile.exists())) { emptyFile.create(new ByteArrayInputStream("".getBytes()), false, null); //$NON-NLS-1$ } } catch (CoreException e) { // Nothing to do. Can happen if another thread creates the file between the check and creation. } } return true; } } // Explore delta only if it is not null boolean hasRelevantChangedResources = false; if (delta != null) { SyncResourceDeltaVisitor visitor = new SyncResourceDeltaVisitor(); delta.accept(visitor); hasRelevantChangedResources = visitor.isRelevant(); } try { /* * A synchronize with SyncFlag.FORCE guarantees that both directories are in sync. * * More precise: it guarantees that all changes written to disk at the moment of the call are guaranteed to be * synchronized between both directories. No guarantees are given for changes occurring during the synchronize call. * * To satisfy this guarantee, this call needs to make sure that both the current delta and all outstanding sync requests * finish before this call returns. * * Example: Why sync if current delta is empty? The RemoteMakeBuilder forces a sync before and after building. In some * cases, we want to ensure repos are synchronized regardless of the passed delta, which can be set to null. */ // TODO: We are not using the individual "sync to local" and "sync to remote" flags yet. if (syncFlags.contains(SyncFlag.DISABLE_SYNC)) { return; } if ((syncFlags == SyncFlag.NO_FORCE) && (!(hasRelevantChangedResources))) { return; } int mySyncTaskId; synchronized (syncTaskId) { syncTaskId++; mySyncTaskId = syncTaskId; // suggestion for Deltas: add delta to list of deltas } synchronized (fWaitingThreadsCount) { if (fWaitingThreadsCount > 0 && syncFlags == SyncFlag.NO_FORCE) { return; // the queued thread will do the work for us. And we don't have to wait because of NO_FORCE } else { fWaitingThreadsCount++; } } // lock syncLock. interruptible by progress monitor try { while (!syncLock.tryLock(50, TimeUnit.MILLISECONDS)) { if (subMon.isCanceled()) { throw new CoreException(new Status(IStatus.CANCEL, Activator.PLUGIN_ID, Messages.GitServiceProvider_1)); } } } catch (InterruptedException e1) { throw new CoreException(new Status(IStatus.CANCEL, Activator.PLUGIN_ID, Messages.GitServiceProvider_2)); } finally { synchronized (fWaitingThreadsCount) { fWaitingThreadsCount--; } } try { // Do not sync if there are merge conflicts. // This check must be done after acquiring the sync lock. Otherwise, the merge may trigger a sync that sees no // conflicting files and proceeds to sync again - depending on how quickly the first sync records the data. if (!(this.getMergeConflictFiles(project, syncConfig).isEmpty())) { throw new RemoteSyncMergeConflictException(Messages.GitServiceProvider_4); } if (mySyncTaskId <= finishedSyncTaskId) { // some other thread has already done the work for us return; } if (syncConfig == null) { throw new RuntimeException(Messages.GitServiceProvider_3 + project.getName()); } subMon.subTask(Messages.GitServiceProvider_7); GitRemoteSyncConnection fSyncConnection = this.getSyncConnection(project, syncConfig, subMon.newChild(98)); if (fSyncConnection == null) { // Should never happen if (syncConfig.getSyncProviderId() == null) { throw new RemoteSyncException(Messages.GitServiceProvider_5); // Happens whenever connection does not exist } else { return; } } // This synchronization operation will include all tasks up to current syncTaskId // syncTaskId can be larger than mySyncTaskId (than we do also the work for other threads) // we might synchronize even more than that if a file is already saved but syncTaskId wasn't increased yet // thus we cannot guarantee a maximum but we can guarantee syncTaskId as a minimum // suggestion for Deltas: make local copy of list of deltas, remove list of deltas int willFinishTaskId; synchronized (syncTaskId) { willFinishTaskId = syncTaskId; } try { subMon.subTask(Messages.GitServiceProvider_8); fSyncConnection.sync(subMon.newChild(900), true); // Unlike other exceptions, we need to do some post-sync activities after a merge exception. // TODO: Refactor code to get rid of duplication of post-sync activities. } catch (RemoteSyncMergeConflictException e) { subMon.subTask(Messages.GitServiceProvider_9); project.refreshLocal(IResource.DEPTH_INFINITE, subMon.newChild(1)); throw e; } finishedSyncTaskId = willFinishTaskId; // TODO: review exception handling } finally { syncLock.unlock(); } // Sync successful - re-enable error messages. This is really UI code, but there is no way at the moment to notify UI // of a successful sync. SyncManager.setShowErrors(project, true); // Refresh after sync to display changes subMon.subTask(Messages.GitServiceProvider_10); project.refreshLocal(IResource.DEPTH_INFINITE, subMon.newChild(1)); } finally { if (monitor != null) { monitor.done(); } } }"
Inversion-Mutation
megadiff
"@Override public boolean put(ObjectId commitId, ImmutableList<ObjectId> parentIds) { boolean updated = false; try { // See if it already exists Vertex commitNode = getOrAddNode(commitId); if (parentIds.isEmpty()) { if (!commitNode.getEdges(OUT, CommitRelationshipTypes.TOROOT.name()).iterator() .hasNext()) { // Attach this node to the root node commitNode.addEdge(CommitRelationshipTypes.TOROOT.name(), root); updated = true; } } if (!commitNode.getEdges(OUT, CommitRelationshipTypes.PARENT.name()).iterator() .hasNext()) { // Don't make relationships if they have been created already for (ObjectId parent : parentIds) { Vertex parentNode = getOrAddNode(parent); commitNode.addEdge(CommitRelationshipTypes.PARENT.name(), parentNode); updated = true; } } this.commit(); } catch (Exception e) { this.rollback(); throw Throwables.propagate(e); } return updated; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "put"
"@Override public boolean put(ObjectId commitId, ImmutableList<ObjectId> parentIds) { boolean updated = false; try { // See if it already exists Vertex commitNode = getOrAddNode(commitId); if (parentIds.isEmpty()) { if (!commitNode.getEdges(OUT, CommitRelationshipTypes.TOROOT.name()).iterator() .hasNext()) { // Attach this node to the root node commitNode.addEdge(CommitRelationshipTypes.TOROOT.name(), root); <MASK>updated = true;</MASK> } } if (!commitNode.getEdges(OUT, CommitRelationshipTypes.PARENT.name()).iterator() .hasNext()) { // Don't make relationships if they have been created already for (ObjectId parent : parentIds) { Vertex parentNode = getOrAddNode(parent); commitNode.addEdge(CommitRelationshipTypes.PARENT.name(), parentNode); } <MASK>updated = true;</MASK> } this.commit(); } catch (Exception e) { this.rollback(); throw Throwables.propagate(e); } return updated; }"
Inversion-Mutation
megadiff
"public void processToDoListTransaction(final SearchIndexBuilderWorker worker) { long startTime = System.currentTimeMillis(); HibernateCallback callback = new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { int totalDocs = 0; try { IndexWriter indexWrite = null; // Load the list List runtimeToDo = findPending(indexBatchSize, session); totalDocs = runtimeToDo.size(); log.debug("Processing " + totalDocs + " documents"); if (totalDocs > 0) { try { indexStorage.doPreIndexUpdate(); if (indexStorage.indexExists()) { IndexReader indexReader = null; try { indexReader = indexStorage.getIndexReader(); // Open the index for (Iterator tditer = runtimeToDo .iterator(); worker.isRunning() && tditer.hasNext();) { SearchBuilderItem sbi = (SearchBuilderItem) tditer .next(); if (!SearchBuilderItem.STATE_PENDING .equals(sbi.getSearchstate())) { // should only be getting pending // items log .warn(" Found Item that was not pending " + sbi.getName()); continue; } if (SearchBuilderItem.ACTION_UNKNOWN .equals(sbi.getSearchaction())) { sbi .setSearchstate(SearchBuilderItem.STATE_COMPLETED); continue; } // remove document try { indexReader .deleteDocuments(new Term( SearchService.FIELD_REFERENCE, sbi.getName())); if (SearchBuilderItem.ACTION_DELETE .equals(sbi .getSearchaction())) { sbi .setSearchstate(SearchBuilderItem.STATE_COMPLETED); } else { sbi .setSearchstate(SearchBuilderItem.STATE_PENDING_2); } } catch (IOException ex) { log.warn("Failed to delete Page ", ex); } } } finally { if (indexReader != null) { indexReader.close(); indexReader = null; } } if (worker.isRunning()) { indexWrite = indexStorage .getIndexWriter(false); } } else { // create for update if (worker.isRunning()) { indexWrite = indexStorage .getIndexWriter(true); } } for (Iterator tditer = runtimeToDo.iterator(); worker .isRunning() && tditer.hasNext();) { Reader contentReader = null; try { SearchBuilderItem sbi = (SearchBuilderItem) tditer .next(); // only add adds, that have been deleted // sucessfully if (!SearchBuilderItem.STATE_PENDING_2 .equals(sbi.getSearchstate())) { continue; } Reference ref = entityManager .newReference(sbi.getName()); if (ref == null) { log .error("Unrecognised trigger object presented to index builder " + sbi); } try { Entity entity = ref.getEntity(); EntityContentProducer sep = searchIndexBuilder .newEntityContentProducer(ref); if (sep != null && sep.isForIndex(ref) && ref.getContext() != null) { Document doc = new Document(); String container = ref .getContainer(); if (container == null) container = ""; doc .add(new Field( SearchService.DATE_STAMP, String.valueOf(System.currentTimeMillis()), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc .add(new Field( SearchService.FIELD_CONTAINER, container, Field.Store.YES, Field.Index.UN_TOKENIZED)); doc.add(new Field( SearchService.FIELD_ID, ref .getId(), Field.Store.YES, Field.Index.NO)); doc.add(new Field( SearchService.FIELD_TYPE, ref.getType(), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc .add(new Field( SearchService.FIELD_SUBTYPE, ref.getSubType(), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc .add(new Field( SearchService.FIELD_REFERENCE, ref.getReference(), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc .add(new Field( SearchService.FIELD_CONTEXT, sep.getSiteId(ref), Field.Store.YES, Field.Index.UN_TOKENIZED)); if (sep.isContentFromReader(entity)) { contentReader = sep .getContentReader(entity); doc .add(new Field( SearchService.FIELD_CONTENTS, contentReader, Field.TermVector.YES)); } else { doc .add(new Field( SearchService.FIELD_CONTENTS, sep .getContent(entity), Field.Store.YES, Field.Index.TOKENIZED, Field.TermVector.YES)); } doc.add(new Field( SearchService.FIELD_TITLE, sep.getTitle(entity), Field.Store.YES, Field.Index.TOKENIZED, Field.TermVector.YES)); doc.add(new Field( SearchService.FIELD_TOOL, sep.getTool(), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc.add(new Field( SearchService.FIELD_URL, sep.getUrl(entity), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc.add(new Field( SearchService.FIELD_SITEID, sep.getSiteId(ref), Field.Store.YES, Field.Index.UN_TOKENIZED)); // add the custom properties Map m = sep.getCustomProperties(); if (m != null) { for (Iterator cprops = m .keySet().iterator(); cprops .hasNext();) { String key = (String) cprops .next(); Object value = m.get(key); String[] values = null; if (value instanceof String) { values = new String[1]; values[0] = (String) value; } if (value instanceof String[]) { values = (String[]) value; } if (values == null) { log .info("Null Custom Properties value has been suppled by " + sep + " in index " + key); } else { for (int i = 0; i < values.length; i++) { doc .add(new Field( key, values[i], Field.Store.YES, Field.Index.UN_TOKENIZED)); } } } } log.debug("Indexing Document " + doc); indexWrite.addDocument(doc); log.debug("Done Indexing Document " + doc); processRDF(sep); } else { log.debug("Ignored Document " + ref.getId()); } sbi .setSearchstate(SearchBuilderItem.STATE_COMPLETED); } catch (Exception e1) { log .debug(" Failed to index document cause: " + e1.getMessage()); } // update this node lock to indicate its // still alove, no document should // take more than 2 mins to process worker.updateNodeLock(); } finally { if (contentReader != null) { try { contentReader.close(); } catch (IOException ioex) { } } } } } finally { if (indexWrite != null) { indexWrite.close(); indexWrite = null; } } totalDocs = 0; try { for (Iterator tditer = runtimeToDo.iterator(); worker .isRunning() && tditer.hasNext();) { SearchBuilderItem sbi = (SearchBuilderItem) tditer .next(); if (SearchBuilderItem.STATE_COMPLETED .equals(sbi.getSearchstate())) { if (SearchBuilderItem.ACTION_DELETE .equals(sbi.getSearchaction())) { session.delete(sbi); } else { session.saveOrUpdate(sbi); } } } session.flush(); totalDocs = runtimeToDo.size(); } catch (Exception ex) { log .warn("Failed to update state in database due to " + ex.getMessage() + " this will be corrected on the next run of the IndexBuilder, no cause for alarm"); } } return new Integer(totalDocs); } catch (IOException ex) { throw new HibernateException(" Failed to create index ", ex); } } }; int totalDocs = 0; if (worker.isRunning()) { Integer nprocessed = (Integer) getHibernateTemplate().execute( callback); if (nprocessed == null) { return; } totalDocs = nprocessed.intValue(); } try { indexStorage.doPostIndexUpdate(); } catch (IOException e) { log.error("Failed to do Post Index Update", e); } if (worker.isRunning()) { eventTrackingService.post(eventTrackingService.newEvent( SearchService.EVENT_TRIGGER_INDEX_RELOAD, "/searchindexreload", true, NotificationService.PREF_IMMEDIATE)); long endTime = System.currentTimeMillis(); float totalTime = endTime - startTime; float ndocs = totalDocs; if (totalDocs > 0) { float docspersec = 1000 * ndocs / totalTime; log.info("Completed Process List of " + totalDocs + " at " + docspersec + " documents/per second"); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "processToDoListTransaction"
"public void processToDoListTransaction(final SearchIndexBuilderWorker worker) { long startTime = System.currentTimeMillis(); HibernateCallback callback = new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { int totalDocs = 0; try { IndexWriter indexWrite = null; // Load the list List runtimeToDo = findPending(indexBatchSize, session); totalDocs = runtimeToDo.size(); log.debug("Processing " + totalDocs + " documents"); if (totalDocs > 0) { try { indexStorage.doPreIndexUpdate(); if (indexStorage.indexExists()) { IndexReader indexReader = null; try { indexReader = indexStorage.getIndexReader(); // Open the index for (Iterator tditer = runtimeToDo .iterator(); worker.isRunning() && tditer.hasNext();) { SearchBuilderItem sbi = (SearchBuilderItem) tditer .next(); if (!SearchBuilderItem.STATE_PENDING .equals(sbi.getSearchstate())) { // should only be getting pending // items log .warn(" Found Item that was not pending " + sbi.getName()); continue; } if (SearchBuilderItem.ACTION_UNKNOWN .equals(sbi.getSearchaction())) { sbi .setSearchstate(SearchBuilderItem.STATE_COMPLETED); continue; } // remove document try { indexReader .deleteDocuments(new Term( SearchService.FIELD_REFERENCE, sbi.getName())); if (SearchBuilderItem.ACTION_DELETE .equals(sbi .getSearchaction())) { sbi .setSearchstate(SearchBuilderItem.STATE_COMPLETED); } else { sbi .setSearchstate(SearchBuilderItem.STATE_PENDING_2); } } catch (IOException ex) { log.warn("Failed to delete Page ", ex); } } } finally { if (indexReader != null) { indexReader.close(); indexReader = null; } } if (worker.isRunning()) { indexWrite = indexStorage .getIndexWriter(false); } } else { // create for update if (worker.isRunning()) { indexWrite = indexStorage .getIndexWriter(true); } } for (Iterator tditer = runtimeToDo.iterator(); worker .isRunning() && tditer.hasNext();) { Reader contentReader = null; try { SearchBuilderItem sbi = (SearchBuilderItem) tditer .next(); // only add adds, that have been deleted // sucessfully if (!SearchBuilderItem.STATE_PENDING_2 .equals(sbi.getSearchstate())) { continue; } Reference ref = entityManager .newReference(sbi.getName()); if (ref == null) { log .error("Unrecognised trigger object presented to index builder " + sbi); } <MASK>Entity entity = ref.getEntity();</MASK> try { EntityContentProducer sep = searchIndexBuilder .newEntityContentProducer(ref); if (sep != null && sep.isForIndex(ref) && ref.getContext() != null) { Document doc = new Document(); String container = ref .getContainer(); if (container == null) container = ""; doc .add(new Field( SearchService.DATE_STAMP, String.valueOf(System.currentTimeMillis()), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc .add(new Field( SearchService.FIELD_CONTAINER, container, Field.Store.YES, Field.Index.UN_TOKENIZED)); doc.add(new Field( SearchService.FIELD_ID, ref .getId(), Field.Store.YES, Field.Index.NO)); doc.add(new Field( SearchService.FIELD_TYPE, ref.getType(), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc .add(new Field( SearchService.FIELD_SUBTYPE, ref.getSubType(), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc .add(new Field( SearchService.FIELD_REFERENCE, ref.getReference(), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc .add(new Field( SearchService.FIELD_CONTEXT, sep.getSiteId(ref), Field.Store.YES, Field.Index.UN_TOKENIZED)); if (sep.isContentFromReader(entity)) { contentReader = sep .getContentReader(entity); doc .add(new Field( SearchService.FIELD_CONTENTS, contentReader, Field.TermVector.YES)); } else { doc .add(new Field( SearchService.FIELD_CONTENTS, sep .getContent(entity), Field.Store.YES, Field.Index.TOKENIZED, Field.TermVector.YES)); } doc.add(new Field( SearchService.FIELD_TITLE, sep.getTitle(entity), Field.Store.YES, Field.Index.TOKENIZED, Field.TermVector.YES)); doc.add(new Field( SearchService.FIELD_TOOL, sep.getTool(), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc.add(new Field( SearchService.FIELD_URL, sep.getUrl(entity), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc.add(new Field( SearchService.FIELD_SITEID, sep.getSiteId(ref), Field.Store.YES, Field.Index.UN_TOKENIZED)); // add the custom properties Map m = sep.getCustomProperties(); if (m != null) { for (Iterator cprops = m .keySet().iterator(); cprops .hasNext();) { String key = (String) cprops .next(); Object value = m.get(key); String[] values = null; if (value instanceof String) { values = new String[1]; values[0] = (String) value; } if (value instanceof String[]) { values = (String[]) value; } if (values == null) { log .info("Null Custom Properties value has been suppled by " + sep + " in index " + key); } else { for (int i = 0; i < values.length; i++) { doc .add(new Field( key, values[i], Field.Store.YES, Field.Index.UN_TOKENIZED)); } } } } log.debug("Indexing Document " + doc); indexWrite.addDocument(doc); log.debug("Done Indexing Document " + doc); processRDF(sep); } else { log.debug("Ignored Document " + ref.getId()); } sbi .setSearchstate(SearchBuilderItem.STATE_COMPLETED); } catch (Exception e1) { log .debug(" Failed to index document cause: " + e1.getMessage()); } // update this node lock to indicate its // still alove, no document should // take more than 2 mins to process worker.updateNodeLock(); } finally { if (contentReader != null) { try { contentReader.close(); } catch (IOException ioex) { } } } } } finally { if (indexWrite != null) { indexWrite.close(); indexWrite = null; } } totalDocs = 0; try { for (Iterator tditer = runtimeToDo.iterator(); worker .isRunning() && tditer.hasNext();) { SearchBuilderItem sbi = (SearchBuilderItem) tditer .next(); if (SearchBuilderItem.STATE_COMPLETED .equals(sbi.getSearchstate())) { if (SearchBuilderItem.ACTION_DELETE .equals(sbi.getSearchaction())) { session.delete(sbi); } else { session.saveOrUpdate(sbi); } } } session.flush(); totalDocs = runtimeToDo.size(); } catch (Exception ex) { log .warn("Failed to update state in database due to " + ex.getMessage() + " this will be corrected on the next run of the IndexBuilder, no cause for alarm"); } } return new Integer(totalDocs); } catch (IOException ex) { throw new HibernateException(" Failed to create index ", ex); } } }; int totalDocs = 0; if (worker.isRunning()) { Integer nprocessed = (Integer) getHibernateTemplate().execute( callback); if (nprocessed == null) { return; } totalDocs = nprocessed.intValue(); } try { indexStorage.doPostIndexUpdate(); } catch (IOException e) { log.error("Failed to do Post Index Update", e); } if (worker.isRunning()) { eventTrackingService.post(eventTrackingService.newEvent( SearchService.EVENT_TRIGGER_INDEX_RELOAD, "/searchindexreload", true, NotificationService.PREF_IMMEDIATE)); long endTime = System.currentTimeMillis(); float totalTime = endTime - startTime; float ndocs = totalDocs; if (totalDocs > 0) { float docspersec = 1000 * ndocs / totalTime; log.info("Completed Process List of " + totalDocs + " at " + docspersec + " documents/per second"); } } }"
Inversion-Mutation
megadiff
"public Object doInHibernate(Session session) throws HibernateException, SQLException { int totalDocs = 0; try { IndexWriter indexWrite = null; // Load the list List runtimeToDo = findPending(indexBatchSize, session); totalDocs = runtimeToDo.size(); log.debug("Processing " + totalDocs + " documents"); if (totalDocs > 0) { try { indexStorage.doPreIndexUpdate(); if (indexStorage.indexExists()) { IndexReader indexReader = null; try { indexReader = indexStorage.getIndexReader(); // Open the index for (Iterator tditer = runtimeToDo .iterator(); worker.isRunning() && tditer.hasNext();) { SearchBuilderItem sbi = (SearchBuilderItem) tditer .next(); if (!SearchBuilderItem.STATE_PENDING .equals(sbi.getSearchstate())) { // should only be getting pending // items log .warn(" Found Item that was not pending " + sbi.getName()); continue; } if (SearchBuilderItem.ACTION_UNKNOWN .equals(sbi.getSearchaction())) { sbi .setSearchstate(SearchBuilderItem.STATE_COMPLETED); continue; } // remove document try { indexReader .deleteDocuments(new Term( SearchService.FIELD_REFERENCE, sbi.getName())); if (SearchBuilderItem.ACTION_DELETE .equals(sbi .getSearchaction())) { sbi .setSearchstate(SearchBuilderItem.STATE_COMPLETED); } else { sbi .setSearchstate(SearchBuilderItem.STATE_PENDING_2); } } catch (IOException ex) { log.warn("Failed to delete Page ", ex); } } } finally { if (indexReader != null) { indexReader.close(); indexReader = null; } } if (worker.isRunning()) { indexWrite = indexStorage .getIndexWriter(false); } } else { // create for update if (worker.isRunning()) { indexWrite = indexStorage .getIndexWriter(true); } } for (Iterator tditer = runtimeToDo.iterator(); worker .isRunning() && tditer.hasNext();) { Reader contentReader = null; try { SearchBuilderItem sbi = (SearchBuilderItem) tditer .next(); // only add adds, that have been deleted // sucessfully if (!SearchBuilderItem.STATE_PENDING_2 .equals(sbi.getSearchstate())) { continue; } Reference ref = entityManager .newReference(sbi.getName()); if (ref == null) { log .error("Unrecognised trigger object presented to index builder " + sbi); } try { Entity entity = ref.getEntity(); EntityContentProducer sep = searchIndexBuilder .newEntityContentProducer(ref); if (sep != null && sep.isForIndex(ref) && ref.getContext() != null) { Document doc = new Document(); String container = ref .getContainer(); if (container == null) container = ""; doc .add(new Field( SearchService.DATE_STAMP, String.valueOf(System.currentTimeMillis()), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc .add(new Field( SearchService.FIELD_CONTAINER, container, Field.Store.YES, Field.Index.UN_TOKENIZED)); doc.add(new Field( SearchService.FIELD_ID, ref .getId(), Field.Store.YES, Field.Index.NO)); doc.add(new Field( SearchService.FIELD_TYPE, ref.getType(), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc .add(new Field( SearchService.FIELD_SUBTYPE, ref.getSubType(), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc .add(new Field( SearchService.FIELD_REFERENCE, ref.getReference(), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc .add(new Field( SearchService.FIELD_CONTEXT, sep.getSiteId(ref), Field.Store.YES, Field.Index.UN_TOKENIZED)); if (sep.isContentFromReader(entity)) { contentReader = sep .getContentReader(entity); doc .add(new Field( SearchService.FIELD_CONTENTS, contentReader, Field.TermVector.YES)); } else { doc .add(new Field( SearchService.FIELD_CONTENTS, sep .getContent(entity), Field.Store.YES, Field.Index.TOKENIZED, Field.TermVector.YES)); } doc.add(new Field( SearchService.FIELD_TITLE, sep.getTitle(entity), Field.Store.YES, Field.Index.TOKENIZED, Field.TermVector.YES)); doc.add(new Field( SearchService.FIELD_TOOL, sep.getTool(), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc.add(new Field( SearchService.FIELD_URL, sep.getUrl(entity), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc.add(new Field( SearchService.FIELD_SITEID, sep.getSiteId(ref), Field.Store.YES, Field.Index.UN_TOKENIZED)); // add the custom properties Map m = sep.getCustomProperties(); if (m != null) { for (Iterator cprops = m .keySet().iterator(); cprops .hasNext();) { String key = (String) cprops .next(); Object value = m.get(key); String[] values = null; if (value instanceof String) { values = new String[1]; values[0] = (String) value; } if (value instanceof String[]) { values = (String[]) value; } if (values == null) { log .info("Null Custom Properties value has been suppled by " + sep + " in index " + key); } else { for (int i = 0; i < values.length; i++) { doc .add(new Field( key, values[i], Field.Store.YES, Field.Index.UN_TOKENIZED)); } } } } log.debug("Indexing Document " + doc); indexWrite.addDocument(doc); log.debug("Done Indexing Document " + doc); processRDF(sep); } else { log.debug("Ignored Document " + ref.getId()); } sbi .setSearchstate(SearchBuilderItem.STATE_COMPLETED); } catch (Exception e1) { log .debug(" Failed to index document cause: " + e1.getMessage()); } // update this node lock to indicate its // still alove, no document should // take more than 2 mins to process worker.updateNodeLock(); } finally { if (contentReader != null) { try { contentReader.close(); } catch (IOException ioex) { } } } } } finally { if (indexWrite != null) { indexWrite.close(); indexWrite = null; } } totalDocs = 0; try { for (Iterator tditer = runtimeToDo.iterator(); worker .isRunning() && tditer.hasNext();) { SearchBuilderItem sbi = (SearchBuilderItem) tditer .next(); if (SearchBuilderItem.STATE_COMPLETED .equals(sbi.getSearchstate())) { if (SearchBuilderItem.ACTION_DELETE .equals(sbi.getSearchaction())) { session.delete(sbi); } else { session.saveOrUpdate(sbi); } } } session.flush(); totalDocs = runtimeToDo.size(); } catch (Exception ex) { log .warn("Failed to update state in database due to " + ex.getMessage() + " this will be corrected on the next run of the IndexBuilder, no cause for alarm"); } } return new Integer(totalDocs); } catch (IOException ex) { throw new HibernateException(" Failed to create index ", ex); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doInHibernate"
"public Object doInHibernate(Session session) throws HibernateException, SQLException { int totalDocs = 0; try { IndexWriter indexWrite = null; // Load the list List runtimeToDo = findPending(indexBatchSize, session); totalDocs = runtimeToDo.size(); log.debug("Processing " + totalDocs + " documents"); if (totalDocs > 0) { try { indexStorage.doPreIndexUpdate(); if (indexStorage.indexExists()) { IndexReader indexReader = null; try { indexReader = indexStorage.getIndexReader(); // Open the index for (Iterator tditer = runtimeToDo .iterator(); worker.isRunning() && tditer.hasNext();) { SearchBuilderItem sbi = (SearchBuilderItem) tditer .next(); if (!SearchBuilderItem.STATE_PENDING .equals(sbi.getSearchstate())) { // should only be getting pending // items log .warn(" Found Item that was not pending " + sbi.getName()); continue; } if (SearchBuilderItem.ACTION_UNKNOWN .equals(sbi.getSearchaction())) { sbi .setSearchstate(SearchBuilderItem.STATE_COMPLETED); continue; } // remove document try { indexReader .deleteDocuments(new Term( SearchService.FIELD_REFERENCE, sbi.getName())); if (SearchBuilderItem.ACTION_DELETE .equals(sbi .getSearchaction())) { sbi .setSearchstate(SearchBuilderItem.STATE_COMPLETED); } else { sbi .setSearchstate(SearchBuilderItem.STATE_PENDING_2); } } catch (IOException ex) { log.warn("Failed to delete Page ", ex); } } } finally { if (indexReader != null) { indexReader.close(); indexReader = null; } } if (worker.isRunning()) { indexWrite = indexStorage .getIndexWriter(false); } } else { // create for update if (worker.isRunning()) { indexWrite = indexStorage .getIndexWriter(true); } } for (Iterator tditer = runtimeToDo.iterator(); worker .isRunning() && tditer.hasNext();) { Reader contentReader = null; try { SearchBuilderItem sbi = (SearchBuilderItem) tditer .next(); // only add adds, that have been deleted // sucessfully if (!SearchBuilderItem.STATE_PENDING_2 .equals(sbi.getSearchstate())) { continue; } Reference ref = entityManager .newReference(sbi.getName()); if (ref == null) { log .error("Unrecognised trigger object presented to index builder " + sbi); } <MASK>Entity entity = ref.getEntity();</MASK> try { EntityContentProducer sep = searchIndexBuilder .newEntityContentProducer(ref); if (sep != null && sep.isForIndex(ref) && ref.getContext() != null) { Document doc = new Document(); String container = ref .getContainer(); if (container == null) container = ""; doc .add(new Field( SearchService.DATE_STAMP, String.valueOf(System.currentTimeMillis()), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc .add(new Field( SearchService.FIELD_CONTAINER, container, Field.Store.YES, Field.Index.UN_TOKENIZED)); doc.add(new Field( SearchService.FIELD_ID, ref .getId(), Field.Store.YES, Field.Index.NO)); doc.add(new Field( SearchService.FIELD_TYPE, ref.getType(), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc .add(new Field( SearchService.FIELD_SUBTYPE, ref.getSubType(), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc .add(new Field( SearchService.FIELD_REFERENCE, ref.getReference(), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc .add(new Field( SearchService.FIELD_CONTEXT, sep.getSiteId(ref), Field.Store.YES, Field.Index.UN_TOKENIZED)); if (sep.isContentFromReader(entity)) { contentReader = sep .getContentReader(entity); doc .add(new Field( SearchService.FIELD_CONTENTS, contentReader, Field.TermVector.YES)); } else { doc .add(new Field( SearchService.FIELD_CONTENTS, sep .getContent(entity), Field.Store.YES, Field.Index.TOKENIZED, Field.TermVector.YES)); } doc.add(new Field( SearchService.FIELD_TITLE, sep.getTitle(entity), Field.Store.YES, Field.Index.TOKENIZED, Field.TermVector.YES)); doc.add(new Field( SearchService.FIELD_TOOL, sep.getTool(), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc.add(new Field( SearchService.FIELD_URL, sep.getUrl(entity), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc.add(new Field( SearchService.FIELD_SITEID, sep.getSiteId(ref), Field.Store.YES, Field.Index.UN_TOKENIZED)); // add the custom properties Map m = sep.getCustomProperties(); if (m != null) { for (Iterator cprops = m .keySet().iterator(); cprops .hasNext();) { String key = (String) cprops .next(); Object value = m.get(key); String[] values = null; if (value instanceof String) { values = new String[1]; values[0] = (String) value; } if (value instanceof String[]) { values = (String[]) value; } if (values == null) { log .info("Null Custom Properties value has been suppled by " + sep + " in index " + key); } else { for (int i = 0; i < values.length; i++) { doc .add(new Field( key, values[i], Field.Store.YES, Field.Index.UN_TOKENIZED)); } } } } log.debug("Indexing Document " + doc); indexWrite.addDocument(doc); log.debug("Done Indexing Document " + doc); processRDF(sep); } else { log.debug("Ignored Document " + ref.getId()); } sbi .setSearchstate(SearchBuilderItem.STATE_COMPLETED); } catch (Exception e1) { log .debug(" Failed to index document cause: " + e1.getMessage()); } // update this node lock to indicate its // still alove, no document should // take more than 2 mins to process worker.updateNodeLock(); } finally { if (contentReader != null) { try { contentReader.close(); } catch (IOException ioex) { } } } } } finally { if (indexWrite != null) { indexWrite.close(); indexWrite = null; } } totalDocs = 0; try { for (Iterator tditer = runtimeToDo.iterator(); worker .isRunning() && tditer.hasNext();) { SearchBuilderItem sbi = (SearchBuilderItem) tditer .next(); if (SearchBuilderItem.STATE_COMPLETED .equals(sbi.getSearchstate())) { if (SearchBuilderItem.ACTION_DELETE .equals(sbi.getSearchaction())) { session.delete(sbi); } else { session.saveOrUpdate(sbi); } } } session.flush(); totalDocs = runtimeToDo.size(); } catch (Exception ex) { log .warn("Failed to update state in database due to " + ex.getMessage() + " this will be corrected on the next run of the IndexBuilder, no cause for alarm"); } } return new Integer(totalDocs); } catch (IOException ex) { throw new HibernateException(" Failed to create index ", ex); } }"
Inversion-Mutation
megadiff
"public void start(FtpServerContext context) throws Exception { this.context = context; acceptor = new NioSocketAcceptor(Runtime.getRuntime().availableProcessors()); if(getServerAddress() != null) { address = new InetSocketAddress(getServerAddress(), getPort() ); } else { address = new InetSocketAddress( getPort() ); } acceptor.setReuseAddress(true); acceptor.getSessionConfig().setReadBufferSize( 2048 ); acceptor.getSessionConfig().setIdleTime( IdleStatus.BOTH_IDLE, idleTimeout ); // Decrease the default receiver buffer size ((SocketSessionConfig) acceptor.getSessionConfig()).setReceiveBufferSize(512); MdcInjectionFilter mdcFilter = new MdcInjectionFilter(); acceptor.getFilterChain().addLast("mdcFilter", mdcFilter); // add and update the blacklist filter acceptor.getFilterChain().addLast("ipFilter", new BlacklistFilter()); updateBlacklistFilter(); acceptor.getFilterChain().addLast("threadPool", new ExecutorFilter(filterExecutor)); acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new FtpServerProtocolCodecFactory() ) ); acceptor.getFilterChain().addLast("mdcFilter2", mdcFilter); acceptor.getFilterChain().addLast("logger", new FtpLoggingFilter() ); if(isImplicitSsl()) { SslConfiguration ssl = getSslConfiguration(); SslFilter sslFilter = new SslFilter( ssl.getSSLContext() ); if(ssl.getClientAuth() == ClientAuth.NEED) { sslFilter.setNeedClientAuth(true); } else if(ssl.getClientAuth() == ClientAuth.WANT) { sslFilter.setWantClientAuth(true); } if(ssl.getEnabledCipherSuites() != null) { sslFilter.setEnabledCipherSuites(ssl.getEnabledCipherSuites()); } acceptor.getFilterChain().addFirst("sslFilter", sslFilter); } handler.init(context, this); acceptor.setHandler(new FtpHandlerAdapter(context, handler)); acceptor.bind(address); // update the port to the real port bound by the listener setPort(acceptor.getLocalAddress().getPort()); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "start"
"public void start(FtpServerContext context) throws Exception { this.context = context; acceptor = new NioSocketAcceptor(Runtime.getRuntime().availableProcessors()); if(getServerAddress() != null) { address = new InetSocketAddress(getServerAddress(), getPort() ); } else { address = new InetSocketAddress( getPort() ); } acceptor.setReuseAddress(true); acceptor.getSessionConfig().setReadBufferSize( 2048 ); acceptor.getSessionConfig().setIdleTime( IdleStatus.BOTH_IDLE, idleTimeout ); // Decrease the default receiver buffer size ((SocketSessionConfig) acceptor.getSessionConfig()).setReceiveBufferSize(512); MdcInjectionFilter mdcFilter = new MdcInjectionFilter(); acceptor.getFilterChain().addLast("mdcFilter", mdcFilter); // add and update the blacklist filter acceptor.getFilterChain().addLast("ipFilter", new BlacklistFilter()); updateBlacklistFilter(); acceptor.getFilterChain().addLast("threadPool", new ExecutorFilter(filterExecutor)); acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new FtpServerProtocolCodecFactory() ) ); acceptor.getFilterChain().addLast("logger", new FtpLoggingFilter() ); <MASK>acceptor.getFilterChain().addLast("mdcFilter2", mdcFilter);</MASK> if(isImplicitSsl()) { SslConfiguration ssl = getSslConfiguration(); SslFilter sslFilter = new SslFilter( ssl.getSSLContext() ); if(ssl.getClientAuth() == ClientAuth.NEED) { sslFilter.setNeedClientAuth(true); } else if(ssl.getClientAuth() == ClientAuth.WANT) { sslFilter.setWantClientAuth(true); } if(ssl.getEnabledCipherSuites() != null) { sslFilter.setEnabledCipherSuites(ssl.getEnabledCipherSuites()); } acceptor.getFilterChain().addFirst("sslFilter", sslFilter); } handler.init(context, this); acceptor.setHandler(new FtpHandlerAdapter(context, handler)); acceptor.bind(address); // update the port to the real port bound by the listener setPort(acceptor.getLocalAddress().getPort()); }"
Inversion-Mutation
megadiff
"public void doCreateTables(TransactionContext c) throws SQLException, IOException { Statement s = null; try { // Check to see if the table already exists. If it does, then don't // log warnings during startup. // Need to run the scripts anyways since they may contain ALTER // statements that upgrade a previous version // of the table boolean alreadyExists = false; ResultSet rs = null; try { rs = c.getConnection().getMetaData().getTables(null, null, this.statements.getFullMessageTableName(), new String[] { "TABLE" }); alreadyExists = rs.next(); } catch (Throwable ignore) { } finally { close(rs); } s = c.getConnection().createStatement(); String[] createStatments = this.statements.getCreateSchemaStatements(); for (int i = 0; i < createStatments.length; i++) { // This will fail usually since the tables will be // created already. try { LOG.debug("Executing SQL: " + createStatments[i]); s.execute(createStatments[i]); } catch (SQLException e) { if (alreadyExists) { LOG.debug("Could not create JDBC tables; The message table already existed." + " Failure was: " + createStatments[i] + " Message: " + e.getMessage() + " SQLState: " + e.getSQLState() + " Vendor code: " + e.getErrorCode()); } else { LOG.warn("Could not create JDBC tables; they could already exist." + " Failure was: " + createStatments[i] + " Message: " + e.getMessage() + " SQLState: " + e.getSQLState() + " Vendor code: " + e.getErrorCode()); JDBCPersistenceAdapter.log("Failure details: ", e); } } c.getConnection().commit(); } } finally { try { s.close(); } catch (Throwable e) { } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doCreateTables"
"public void doCreateTables(TransactionContext c) throws SQLException, IOException { Statement s = null; try { // Check to see if the table already exists. If it does, then don't // log warnings during startup. // Need to run the scripts anyways since they may contain ALTER // statements that upgrade a previous version // of the table boolean alreadyExists = false; ResultSet rs = null; try { rs = c.getConnection().getMetaData().getTables(null, null, this.statements.getFullMessageTableName(), new String[] { "TABLE" }); alreadyExists = rs.next(); } catch (Throwable ignore) { } finally { close(rs); } s = c.getConnection().createStatement(); String[] createStatments = this.statements.getCreateSchemaStatements(); for (int i = 0; i < createStatments.length; i++) { // This will fail usually since the tables will be // created already. try { LOG.debug("Executing SQL: " + createStatments[i]); s.execute(createStatments[i]); } catch (SQLException e) { if (alreadyExists) { LOG.debug("Could not create JDBC tables; The message table already existed." + " Failure was: " + createStatments[i] + " Message: " + e.getMessage() + " SQLState: " + e.getSQLState() + " Vendor code: " + e.getErrorCode()); } else { LOG.warn("Could not create JDBC tables; they could already exist." + " Failure was: " + createStatments[i] + " Message: " + e.getMessage() + " SQLState: " + e.getSQLState() + " Vendor code: " + e.getErrorCode()); JDBCPersistenceAdapter.log("Failure details: ", e); } } } <MASK>c.getConnection().commit();</MASK> } finally { try { s.close(); } catch (Throwable e) { } } }"
Inversion-Mutation
megadiff
"private final void write_TypeCode (final org.omg.CORBA.TypeCode value, final Hashtable tcMap) { if (value == null) { throw new org.omg.CORBA.BAD_PARAM("TypeCode is null"); } int _kind = value.kind().value(); int _mc; // member count try { if( (value instanceof org.jacorb.orb.TypeCode) && ((org.jacorb.orb.TypeCode)value).is_recursive() && tcMap.containsKey( value.id()) ) { writeRecursiveTypeCode( value, tcMap ); } else { // regular TypeCodes switch( _kind ) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: case 23: case 24: case 25: case 26: write_long( _kind ); break; case TCKind._tk_objref: write_long( _kind ); beginEncapsulation(); write_string( value.id() ); write_string( value.name() ); endEncapsulation(); break; case TCKind._tk_struct: case TCKind._tk_except: if (Environment.indirectionEncoding () && tcMap.containsKey (value.id ())) { writeRecursiveTypeCode( value, tcMap ); } else { write_long( _kind ); tcMap.put( value.id(), new Integer( pos ) ); recursiveTCMap.put( value.id(), value ); beginEncapsulation(); write_string(value.id()); write_string(value.name()); _mc = value.member_count(); write_long(_mc); for( int i = 0; i < _mc; i++) { write_string( value.member_name(i) ); write_TypeCode( value.member_type(i), tcMap ); } endEncapsulation(); } break; case TCKind._tk_enum: if (Environment.indirectionEncoding () && tcMap.containsKey (value.id ())) { writeRecursiveTypeCode( value, tcMap ); } else { write_long( _kind ); tcMap.put( value.id(), new Integer( pos ) ); recursiveTCMap.put( value.id(), value ); beginEncapsulation(); write_string( value.id()); write_string( value.name()); _mc = value.member_count(); write_long(_mc); for( int i = 0; i < _mc; i++) { write_string( value.member_name(i) ); } endEncapsulation(); } break; case TCKind._tk_union: if (Environment.indirectionEncoding () && tcMap.containsKey (value.id ())) { writeRecursiveTypeCode( value, tcMap ); } else { write_long( _kind ); tcMap.put( value.id(), new Integer( pos ) ); recursiveTCMap.put( value.id() , value ); beginEncapsulation(); write_string( value.id() ); write_string( value.name() ); write_TypeCode( value.discriminator_type()); write_long( value.default_index()); _mc = value.member_count(); write_long(_mc); for( int i = 0; i < _mc; i++) { if( i == value.default_index() ) { write_octet((byte)0); } else { value.member_label(i).write_value( this ); } write_string( value.member_name(i)); write_TypeCode( value.member_type(i), tcMap ); } endEncapsulation(); } break; case TCKind._tk_wstring: case TCKind._tk_string: write_long( _kind ); write_long(value.length()); break; case TCKind._tk_fixed: write_long( _kind ); write_ushort( value.fixed_digits() ); write_short( value.fixed_scale() ); break; case TCKind._tk_array: case TCKind._tk_sequence: write_long( _kind ); beginEncapsulation(); // if( ((TypeCode)value.content_type()).is_recursive()) // { // Integer enclosing_tc_pos = (Integer)recursiveTCStack.peek(); // write_long( enclosing_tc_pos.intValue() - pos ); // } // else write_TypeCode( value.content_type(), tcMap); write_long(value.length()); endEncapsulation(); break; case TCKind._tk_alias: if (Environment.indirectionEncoding () && tcMap.containsKey (value.id ())) { writeRecursiveTypeCode( value, tcMap ); } else { write_long( _kind ); tcMap.put( value.id(), new Integer( pos ) ); recursiveTCMap.put( value.id(), value ); beginEncapsulation(); write_string(value.id()); write_string(value.name()); write_TypeCode( value.content_type(), tcMap); endEncapsulation(); } break; case TCKind._tk_value: if (Environment.indirectionEncoding () && tcMap.containsKey (value.id ())) { writeRecursiveTypeCode( value, tcMap ); } else { write_long( _kind ); tcMap.put( value.id(), new Integer( pos ) ); recursiveTCMap.put( value.id(), value ); beginEncapsulation(); write_string(value.id()); write_string(value.name()); write_short( value.type_modifier() ); org.omg.CORBA.TypeCode base = value.concrete_base_type(); if (base != null) write_TypeCode(base, tcMap); else write_long (TCKind._tk_null); _mc = value.member_count(); write_long(_mc); for( int i = 0; i < _mc; i++) { Debug.output(3,"value member name " + value.member_name(i) ); write_string( value.member_name(i) ); write_TypeCode( value.member_type(i), tcMap ); write_short( value.member_visibility(i) ); } endEncapsulation(); } break; case TCKind._tk_value_box: if (Environment.indirectionEncoding () && tcMap.containsKey (value.id ())) { writeRecursiveTypeCode( value, tcMap ); } else { write_long( _kind ); tcMap.put( value.id(), new Integer( pos ) ); recursiveTCMap.put( value.id(), value ); beginEncapsulation(); write_string(value.id()); write_string(value.name()); write_TypeCode( value.content_type(), tcMap); endEncapsulation(); } break; case TCKind._tk_abstract_interface: if (Environment.indirectionEncoding () && tcMap.containsKey (value.id ())) { writeRecursiveTypeCode( value, tcMap ); } else { write_long( _kind ); tcMap.put( value.id(), new Integer( pos ) ); recursiveTCMap.put( value.id(), value ); beginEncapsulation(); write_string(value.id()); write_string(value.name()); endEncapsulation(); } break; default: throw new org.omg.CORBA.MARSHAL ("Cannot handle TypeCode with kind: " + _kind); } } } catch (org.omg.CORBA.TypeCodePackage.BadKind bk) { bk.printStackTrace(); } catch (org.omg.CORBA.TypeCodePackage.Bounds b) { b.printStackTrace(); } catch (java.io.IOException ioe) { ioe.printStackTrace(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "write_TypeCode"
"private final void write_TypeCode (final org.omg.CORBA.TypeCode value, final Hashtable tcMap) { if (value == null) { throw new org.omg.CORBA.BAD_PARAM("TypeCode is null"); } int _kind = value.kind().value(); int _mc; // member count try { if( (value instanceof org.jacorb.orb.TypeCode) && ((org.jacorb.orb.TypeCode)value).is_recursive() && tcMap.containsKey( value.id()) ) { writeRecursiveTypeCode( value, tcMap ); } else { // regular TypeCodes switch( _kind ) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: case 23: case 24: case 25: case 26: write_long( _kind ); <MASK>break;</MASK> case TCKind._tk_objref: write_long( _kind ); beginEncapsulation(); write_string( value.id() ); write_string( value.name() ); endEncapsulation(); <MASK>break;</MASK> case TCKind._tk_struct: case TCKind._tk_except: if (Environment.indirectionEncoding () && tcMap.containsKey (value.id ())) { writeRecursiveTypeCode( value, tcMap ); } else { write_long( _kind ); tcMap.put( value.id(), new Integer( pos ) ); recursiveTCMap.put( value.id(), value ); beginEncapsulation(); write_string(value.id()); write_string(value.name()); _mc = value.member_count(); write_long(_mc); for( int i = 0; i < _mc; i++) { write_string( value.member_name(i) ); write_TypeCode( value.member_type(i), tcMap ); } endEncapsulation(); } <MASK>break;</MASK> case TCKind._tk_enum: if (Environment.indirectionEncoding () && tcMap.containsKey (value.id ())) { writeRecursiveTypeCode( value, tcMap ); } else { write_long( _kind ); tcMap.put( value.id(), new Integer( pos ) ); recursiveTCMap.put( value.id(), value ); beginEncapsulation(); write_string( value.id()); write_string( value.name()); _mc = value.member_count(); write_long(_mc); for( int i = 0; i < _mc; i++) { write_string( value.member_name(i) ); } endEncapsulation(); <MASK>break;</MASK> } case TCKind._tk_union: if (Environment.indirectionEncoding () && tcMap.containsKey (value.id ())) { writeRecursiveTypeCode( value, tcMap ); } else { write_long( _kind ); tcMap.put( value.id(), new Integer( pos ) ); recursiveTCMap.put( value.id() , value ); beginEncapsulation(); write_string( value.id() ); write_string( value.name() ); write_TypeCode( value.discriminator_type()); write_long( value.default_index()); _mc = value.member_count(); write_long(_mc); for( int i = 0; i < _mc; i++) { if( i == value.default_index() ) { write_octet((byte)0); } else { value.member_label(i).write_value( this ); } write_string( value.member_name(i)); write_TypeCode( value.member_type(i), tcMap ); } endEncapsulation(); } <MASK>break;</MASK> case TCKind._tk_wstring: case TCKind._tk_string: write_long( _kind ); write_long(value.length()); <MASK>break;</MASK> case TCKind._tk_fixed: write_long( _kind ); write_ushort( value.fixed_digits() ); write_short( value.fixed_scale() ); <MASK>break;</MASK> case TCKind._tk_array: case TCKind._tk_sequence: write_long( _kind ); beginEncapsulation(); // if( ((TypeCode)value.content_type()).is_recursive()) // { // Integer enclosing_tc_pos = (Integer)recursiveTCStack.peek(); // write_long( enclosing_tc_pos.intValue() - pos ); // } // else write_TypeCode( value.content_type(), tcMap); write_long(value.length()); endEncapsulation(); <MASK>break;</MASK> case TCKind._tk_alias: if (Environment.indirectionEncoding () && tcMap.containsKey (value.id ())) { writeRecursiveTypeCode( value, tcMap ); } else { write_long( _kind ); tcMap.put( value.id(), new Integer( pos ) ); recursiveTCMap.put( value.id(), value ); beginEncapsulation(); write_string(value.id()); write_string(value.name()); write_TypeCode( value.content_type(), tcMap); endEncapsulation(); } <MASK>break;</MASK> case TCKind._tk_value: if (Environment.indirectionEncoding () && tcMap.containsKey (value.id ())) { writeRecursiveTypeCode( value, tcMap ); } else { write_long( _kind ); tcMap.put( value.id(), new Integer( pos ) ); recursiveTCMap.put( value.id(), value ); beginEncapsulation(); write_string(value.id()); write_string(value.name()); write_short( value.type_modifier() ); org.omg.CORBA.TypeCode base = value.concrete_base_type(); if (base != null) write_TypeCode(base, tcMap); else write_long (TCKind._tk_null); _mc = value.member_count(); write_long(_mc); for( int i = 0; i < _mc; i++) { Debug.output(3,"value member name " + value.member_name(i) ); write_string( value.member_name(i) ); write_TypeCode( value.member_type(i), tcMap ); write_short( value.member_visibility(i) ); } endEncapsulation(); } <MASK>break;</MASK> case TCKind._tk_value_box: if (Environment.indirectionEncoding () && tcMap.containsKey (value.id ())) { writeRecursiveTypeCode( value, tcMap ); } else { write_long( _kind ); tcMap.put( value.id(), new Integer( pos ) ); recursiveTCMap.put( value.id(), value ); beginEncapsulation(); write_string(value.id()); write_string(value.name()); write_TypeCode( value.content_type(), tcMap); endEncapsulation(); } <MASK>break;</MASK> case TCKind._tk_abstract_interface: if (Environment.indirectionEncoding () && tcMap.containsKey (value.id ())) { writeRecursiveTypeCode( value, tcMap ); } else { write_long( _kind ); tcMap.put( value.id(), new Integer( pos ) ); recursiveTCMap.put( value.id(), value ); beginEncapsulation(); write_string(value.id()); write_string(value.name()); endEncapsulation(); } <MASK>break;</MASK> default: throw new org.omg.CORBA.MARSHAL ("Cannot handle TypeCode with kind: " + _kind); } } } catch (org.omg.CORBA.TypeCodePackage.BadKind bk) { bk.printStackTrace(); } catch (org.omg.CORBA.TypeCodePackage.Bounds b) { b.printStackTrace(); } catch (java.io.IOException ioe) { ioe.printStackTrace(); } }"
Inversion-Mutation
megadiff
"@Override public void run() { try { Play.detectChanges(); setContextClassLoader(Play.classloader); LocalVariablesNamesTracer.enterMethod(); JPA.startTx(false); execute(); JPA.closeTx(false); } catch (Throwable e) { JPA.closeTx(true); if(e instanceof PlayException) { throw (PlayException)e; } throw new UnexpectedException(e); } finally { DB.close(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"@Override public void run() { try { Play.detectChanges(); setContextClassLoader(Play.classloader); LocalVariablesNamesTracer.enterMethod(); JPA.startTx(false); execute(); } catch (Throwable e) { JPA.closeTx(true); if(e instanceof PlayException) { throw (PlayException)e; } throw new UnexpectedException(e); } finally { <MASK>JPA.closeTx(false);</MASK> DB.close(); } }"
Inversion-Mutation
megadiff
"private void functionDecl(final Ann ann) throws QueryException { final InputInfo ii = info(); final QNm name = eQName(FUNCNAME, sc.funcNS); if(sc.xquery3() && keyword(name)) throw error(RESERVED, name.local()); wsCheck(PAR1); if(module != null && !eq(name.uri(), module.uri())) throw error(MODNS, name); pushVarContext(null); final Var[] args = paramList(); wsCheck(PAR2); final SeqType tp = optAsType(); if(ann.contains(Ann.Q_UPDATING)) ctx.updating(false); final Expr body = wsConsumeWs(EXTERNAL) ? null : enclosed(NOFUNBODY); final VarScope scope = popVarContext(); funcs.add(ctx.funcs.declare(ann, name, args, tp, body, sc, scope, currDoc.toString(), ii)); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "functionDecl"
"private void functionDecl(final Ann ann) throws QueryException { final InputInfo ii = info(); final QNm name = eQName(FUNCNAME, sc.funcNS); if(sc.xquery3() && keyword(name)) throw error(RESERVED, name.local()); if(module != null && !eq(name.uri(), module.uri())) throw error(MODNS, name); <MASK>wsCheck(PAR1);</MASK> pushVarContext(null); final Var[] args = paramList(); wsCheck(PAR2); final SeqType tp = optAsType(); if(ann.contains(Ann.Q_UPDATING)) ctx.updating(false); final Expr body = wsConsumeWs(EXTERNAL) ? null : enclosed(NOFUNBODY); final VarScope scope = popVarContext(); funcs.add(ctx.funcs.declare(ann, name, args, tp, body, sc, scope, currDoc.toString(), ii)); }"
Inversion-Mutation
megadiff
"@Override public void encodeEnd(FacesContext context, UIComponent component) throws IOException { LightBox lb = (LightBox) component; encodeScript(context, lb); encodeMarkup(context, lb); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "encodeEnd"
"@Override public void encodeEnd(FacesContext context, UIComponent component) throws IOException { LightBox lb = (LightBox) component; <MASK>encodeMarkup(context, lb);</MASK> encodeScript(context, lb); }"
Inversion-Mutation
megadiff
"public String processForm(IncomingMessageForm form) { Object result = null; MethodSignature mSig; String formattedResult = ""; if(form.getMessageFormStatus() != IncMessageFormStatus.VALID) return "Invalid form"; SimpleDateFormat dFormat = new SimpleDateFormat(defaultDateFormat); dFormat.setLenient(true); if (getServiceMethods().containsKey(form.getIncomingMsgFormDefinition().getFormCode().toUpperCase())) { mSig = getServiceMethods().get(form.getIncomingMsgFormDefinition().getFormCode().toUpperCase()); } else { return form.getMessageFormStatus().toString(); } String methodName = mSig.getMethodName(); Class[] paramTypes = new Class[mSig.getMethodParams().size()]; Object[] paramObjs = new Object[mSig.getMethodParams().size()]; int idx = 0; try { for (Entry<String, Class> e : mSig.getMethodParams().entrySet()) { logger.debug("Param: "+e.getKey()+" Class:"+e.getValue()); paramTypes[idx] = e.getValue(); if (form.getIncomingMsgFormParameters().containsKey(e.getKey().toLowerCase())) { if(form.getIncomingMsgFormParameters().get(e.getKey().toLowerCase()).getValue().isEmpty()){ paramObjs[idx] = null; } else if (e.getValue().equals(Date.class)) { paramObjs[idx] = dFormat.parse(form.getIncomingMsgFormParameters().get(e.getKey().toLowerCase()).getValue()); } else if (e.getValue().isEnum()) { paramObjs[idx] = Enum.valueOf(e.getValue(), form.getIncomingMsgFormParameters().get(e.getKey().toLowerCase()).getValue()); } else if (e.getValue().equals(String.class)) { paramObjs[idx] = form.getIncomingMsgFormParameters().get(e.getKey().toLowerCase()).getValue(); } else if (e.getValue().isArray()) { String[] a = form.getIncomingMsgFormParameters().get(e.getKey().toLowerCase()).getValue().split(" "); Class baseType = e.getValue().getComponentType(); Object arrayObj = Array.newInstance(baseType, a.length); for (int i = 0; i < a.length; i++) { Constructor constr = baseType.getConstructor(String.class); Object val = constr.newInstance(a[i]); Array.set(arrayObj, i, val); } paramObjs[idx] = arrayObj; } else { Constructor constr = e.getValue().getConstructor(String.class); paramObjs[idx] = constr.newInstance(form.getIncomingMsgFormParameters().get(e.getKey().toLowerCase()).getValue()); } } else { paramObjs[idx] = null; } idx++; } Method method = regWS.getClass().getDeclaredMethod(methodName, paramTypes); result = method.invoke(regWS, paramObjs); form.setMessageFormStatus(IncMessageFormStatus.SERVER_VALID); } catch (NoSuchMethodException ex) { form.setMessageFormStatus(IncMessageFormStatus.SERVER_INVALID); logger.fatal("Could not find web service method " + methodName, ex); } catch (SecurityException ex) { form.setMessageFormStatus(IncMessageFormStatus.SERVER_INVALID); logger.fatal("Could not access method " + methodName + " due to SecurityException", ex); } catch (IllegalAccessException ex) { form.setMessageFormStatus(IncMessageFormStatus.SERVER_INVALID); logger.fatal("Could not invoke method " + methodName + " due to IllegalAccessException", ex); } catch (InvocationTargetException ex) { form.setMessageFormStatus(IncMessageFormStatus.SERVER_INVALID); if (ex.getCause().getClass().equals(ValidationException.class)) { parseValidationErrors(form, (ValidationException) ex.getCause()); } else { logger.fatal("Could not invoke method " + methodName + " due to InvocationTargetException", ex); } } catch (Exception ex) { logger.error("Form could not be processed on server", ex); form.setMessageFormStatus(IncMessageFormStatus.SERVER_INVALID); return "An error occurred on the server"; } if (mSig.getCallback() == null) { return (result == null) ? null : String.valueOf(result); } return executeCallback(mSig.getCallback(), result); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "processForm"
"public String processForm(IncomingMessageForm form) { Object result = null; MethodSignature mSig; String formattedResult = ""; if(form.getMessageFormStatus() != IncMessageFormStatus.VALID) return "Invalid form"; SimpleDateFormat dFormat = new SimpleDateFormat(defaultDateFormat); dFormat.setLenient(true); if (getServiceMethods().containsKey(form.getIncomingMsgFormDefinition().getFormCode().toUpperCase())) { mSig = getServiceMethods().get(form.getIncomingMsgFormDefinition().getFormCode().toUpperCase()); } else { return form.getMessageFormStatus().toString(); } String methodName = mSig.getMethodName(); Class[] paramTypes = new Class[mSig.getMethodParams().size()]; Object[] paramObjs = new Object[mSig.getMethodParams().size()]; int idx = 0; try { for (Entry<String, Class> e : mSig.getMethodParams().entrySet()) { logger.debug("Param: "+e.getKey()+" Class:"+e.getValue()); paramTypes[idx] = e.getValue(); if (form.getIncomingMsgFormParameters().containsKey(e.getKey().toLowerCase())) { if(form.getIncomingMsgFormParameters().get(e.getKey().toLowerCase()).getValue().isEmpty()){ paramObjs[idx] = null; } else if (e.getValue().equals(Date.class)) { paramObjs[idx] = dFormat.parse(form.getIncomingMsgFormParameters().get(e.getKey().toLowerCase()).getValue()); } else if (e.getValue().isEnum()) { paramObjs[idx] = Enum.valueOf(e.getValue(), form.getIncomingMsgFormParameters().get(e.getKey().toLowerCase()).getValue()); } else if (e.getValue().equals(String.class)) { paramObjs[idx] = form.getIncomingMsgFormParameters().get(e.getKey().toLowerCase()).getValue(); } else if (e.getValue().isArray()) { String[] a = form.getIncomingMsgFormParameters().get(e.getKey().toLowerCase()).getValue().split(" "); Class baseType = e.getValue().getComponentType(); Object arrayObj = Array.newInstance(baseType, a.length); for (int i = 0; i < a.length; i++) { Constructor constr = baseType.getConstructor(String.class); Object val = constr.newInstance(a[i]); Array.set(arrayObj, i, val); } paramObjs[idx] = arrayObj; } else { Constructor constr = e.getValue().getConstructor(String.class); paramObjs[idx] = constr.newInstance(form.getIncomingMsgFormParameters().get(e.getKey().toLowerCase()).getValue()); } } else { paramObjs[idx] = null; } idx++; } Method method = regWS.getClass().getDeclaredMethod(methodName, paramTypes); result = method.invoke(regWS, paramObjs); form.setMessageFormStatus(IncMessageFormStatus.SERVER_VALID); } catch (NoSuchMethodException ex) { <MASK>form.setMessageFormStatus(IncMessageFormStatus.SERVER_INVALID);</MASK> logger.fatal("Could not find web service method " + methodName, ex); } catch (SecurityException ex) { <MASK>form.setMessageFormStatus(IncMessageFormStatus.SERVER_INVALID);</MASK> logger.fatal("Could not access method " + methodName + " due to SecurityException", ex); } catch (IllegalAccessException ex) { <MASK>form.setMessageFormStatus(IncMessageFormStatus.SERVER_INVALID);</MASK> logger.fatal("Could not invoke method " + methodName + " due to IllegalAccessException", ex); } catch (InvocationTargetException ex) { if (ex.getCause().getClass().equals(ValidationException.class)) { parseValidationErrors(form, (ValidationException) ex.getCause()); } else { <MASK>form.setMessageFormStatus(IncMessageFormStatus.SERVER_INVALID);</MASK> logger.fatal("Could not invoke method " + methodName + " due to InvocationTargetException", ex); } } catch (Exception ex) { logger.error("Form could not be processed on server", ex); <MASK>form.setMessageFormStatus(IncMessageFormStatus.SERVER_INVALID);</MASK> return "An error occurred on the server"; } if (mSig.getCallback() == null) { return (result == null) ? null : String.valueOf(result); } return executeCallback(mSig.getCallback(), result); }"
Inversion-Mutation
megadiff
"@Override public ItemResult createOrUpdate() throws IOException { if (vCalendar.isTodo() && isMainCalendar(folderPath)) { // task item, move to tasks folder folderPath = TASKS; } ItemResult itemResult = new ItemResult(); EWSMethod createOrUpdateItemMethod; // first try to load existing event String currentEtag = null; ItemId currentItemId = null; EWSMethod.Item currentItem = getEwsItem(folderPath, itemName); if (currentItem != null) { currentItemId = new ItemId(currentItem); currentEtag = currentItem.get(Field.get("etag").getResponseName()); LOGGER.debug("Existing item found with etag: " + currentEtag + " client etag: " + etag + " id: " + currentItemId.id); } if ("*".equals(noneMatch)) { // create requested if (currentItemId != null) { itemResult.status = HttpStatus.SC_PRECONDITION_FAILED; return itemResult; } } else if (etag != null) { // update requested if (currentItemId == null || !etag.equals(currentEtag)) { itemResult.status = HttpStatus.SC_PRECONDITION_FAILED; return itemResult; } } if (vCalendar.isTodo()) { // create or update task method EWSMethod.Item newItem = new EWSMethod.Item(); newItem.type = "Task"; List<FieldUpdate> updates = new ArrayList<FieldUpdate>(); updates.add(Field.createFieldUpdate("calendaruid", vCalendar.getFirstVeventPropertyValue("UID"))); // force urlcompname updates.add(Field.createFieldUpdate("urlcompname", convertItemNameToEML(itemName))); updates.add(Field.createFieldUpdate("subject", vCalendar.getFirstVeventPropertyValue("SUMMARY"))); updates.add(Field.createFieldUpdate("description", vCalendar.getFirstVeventPropertyValue("DESCRIPTION"))); updates.add(Field.createFieldUpdate("keywords", vCalendar.getFirstVeventPropertyValue("CATEGORIES"))); String percentComplete = vCalendar.getFirstVeventPropertyValue("PERCENT-COMPLETE"); if (percentComplete == null) { percentComplete = "0"; } updates.add(Field.createFieldUpdate("percentcomplete", percentComplete)); String vTodoStatus = vCalendar.getFirstVeventPropertyValue("STATUS"); if (vTodoStatus == null) { updates.add(Field.createFieldUpdate("taskstatus", "NotStarted")); } else { updates.add(Field.createFieldUpdate("taskstatus", vTodoToTaskStatusMap.get(vTodoStatus))); } updates.add(Field.createFieldUpdate("startdate", convertTaskDateToZulu(vCalendar.getFirstVeventPropertyValue("DTSTART")))); updates.add(Field.createFieldUpdate("duedate", convertTaskDateToZulu(vCalendar.getFirstVeventPropertyValue("DUE")))); updates.add(Field.createFieldUpdate("datecompleted", convertTaskDateToZulu(vCalendar.getFirstVeventPropertyValue("COMPLETED")))); updates.add(Field.createFieldUpdate("commonstart", convertTaskDateToZulu(vCalendar.getFirstVeventPropertyValue("DTSTART")))); updates.add(Field.createFieldUpdate("commonend", convertTaskDateToZulu(vCalendar.getFirstVeventPropertyValue("DUE")))); //updates.add(Field.createFieldUpdate("iscomplete", "COMPLETED".equals(vTodoStatus)?"True":"False")); if (currentItemId != null) { // update createOrUpdateItemMethod = new UpdateItemMethod(MessageDisposition.SaveOnly, ConflictResolution.AutoResolve, SendMeetingInvitationsOrCancellations.SendToNone, currentItemId, updates); } else { newItem.setFieldUpdates(updates); // create createOrUpdateItemMethod = new CreateItemMethod(MessageDisposition.SaveOnly, SendMeetingInvitations.SendToNone, getFolderId(folderPath), newItem); } } else { if (currentItemId != null) { /*Set<FieldUpdate> updates = new HashSet<FieldUpdate>(); // TODO: update properties instead of brute force delete/add updates.add(new FieldUpdate(Field.get("mimeContent"), new String(Base64.encodeBase64(itemContent)))); // update createOrUpdateItemMethod = new UpdateItemMethod(MessageDisposition.SaveOnly, ConflictResolution.AutoResolve, SendMeetingInvitationsOrCancellations.SendToNone, currentItemId, updates);*/ // hard method: delete/create on update DeleteItemMethod deleteItemMethod = new DeleteItemMethod(currentItemId, DeleteType.HardDelete, SendMeetingCancellations.SendToNone); executeMethod(deleteItemMethod); } //else { // create EWSMethod.Item newItem = new EWSMethod.Item(); newItem.type = "CalendarItem"; newItem.mimeContent = Base64.encodeBase64(vCalendar.toString().getBytes("UTF-8")); ArrayList<FieldUpdate> updates = new ArrayList<FieldUpdate>(); if (!vCalendar.hasVAlarm()) { updates.add(Field.createFieldUpdate("reminderset", "false")); } //updates.add(Field.createFieldUpdate("outlookmessageclass", "IPM.Appointment")); // force urlcompname updates.add(Field.createFieldUpdate("urlcompname", convertItemNameToEML(itemName))); if (vCalendar.isMeeting() && vCalendar.isMeetingOrganizer()) { updates.add(Field.createFieldUpdate("apptstateflags", "1")); } else { updates.add(Field.createFieldUpdate("apptstateflags", "0")); } // store mozilla invitations option String xMozSendInvitations = vCalendar.getFirstVeventPropertyValue("X-MOZ-SEND-INVITATIONS"); if (xMozSendInvitations != null) { updates.add(Field.createFieldUpdate("xmozsendinvitations", xMozSendInvitations)); } // handle mozilla alarm String xMozLastack = vCalendar.getFirstVeventPropertyValue("X-MOZ-LASTACK"); if (xMozLastack != null) { updates.add(Field.createFieldUpdate("xmozlastack", xMozLastack)); } String xMozSnoozeTime = vCalendar.getFirstVeventPropertyValue("X-MOZ-SNOOZE-TIME"); if (xMozSnoozeTime != null) { updates.add(Field.createFieldUpdate("xmozsnoozetime", xMozSnoozeTime)); } if (vCalendar.isMeeting()) { VCalendar.Recipients recipients = vCalendar.getRecipients(false); if (recipients.attendees != null) { updates.add(Field.createFieldUpdate("to", recipients.attendees)); } if (recipients.optionalAttendees != null) { updates.add(Field.createFieldUpdate("cc", recipients.optionalAttendees)); } if (recipients.organizer != null && !vCalendar.isMeetingOrganizer()) { updates.add(Field.createFieldUpdate("from", recipients.optionalAttendees)); } } // patch allday date values if (vCalendar.isCdoAllDay()) { updates.add(Field.createFieldUpdate("dtstart", convertCalendarDateToExchange(vCalendar.getFirstVeventPropertyValue("DTSTART")))); updates.add(Field.createFieldUpdate("dtend", convertCalendarDateToExchange(vCalendar.getFirstVeventPropertyValue("DTEND")))); } updates.add(Field.createFieldUpdate("busystatus", "BUSY".equals(vCalendar.getFirstVeventPropertyValue("X-MICROSOFT-CDO-BUSYSTATUS")) ? "Busy" : "Free")); if (vCalendar.isCdoAllDay()) { if ("Exchange2010".equals(serverVersion)) { updates.add(Field.createFieldUpdate("starttimezone", vCalendar.getVTimezone().getPropertyValue("TZID"))); } else { updates.add(Field.createFieldUpdate("meetingtimezone", vCalendar.getVTimezone().getPropertyValue("TZID"))); } } newItem.setFieldUpdates(updates); createOrUpdateItemMethod = new CreateItemMethod(MessageDisposition.SaveOnly, SendMeetingInvitations.SendToNone, getFolderId(folderPath), newItem); //} } executeMethod(createOrUpdateItemMethod); itemResult.status = createOrUpdateItemMethod.getStatusCode(); if (itemResult.status == HttpURLConnection.HTTP_OK) { //noinspection VariableNotUsedInsideIf if (currentItemId == null) { itemResult.status = HttpStatus.SC_CREATED; LOGGER.debug("Created event " + getHref()); } else { LOGGER.warn("Overwritten event " + getHref()); } } ItemId newItemId = new ItemId(createOrUpdateItemMethod.getResponseItem()); GetItemMethod getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, newItemId, false); getItemMethod.addAdditionalProperty(Field.get("etag")); executeMethod(getItemMethod); itemResult.etag = getItemMethod.getResponseItem().get(Field.get("etag").getResponseName()); return itemResult; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createOrUpdate"
"@Override public ItemResult createOrUpdate() throws IOException { if (vCalendar.isTodo() && isMainCalendar(folderPath)) { // task item, move to tasks folder folderPath = TASKS; } ItemResult itemResult = new ItemResult(); EWSMethod createOrUpdateItemMethod; // first try to load existing event String currentEtag = null; ItemId currentItemId = null; EWSMethod.Item currentItem = getEwsItem(folderPath, itemName); if (currentItem != null) { currentItemId = new ItemId(currentItem); currentEtag = currentItem.get(Field.get("etag").getResponseName()); LOGGER.debug("Existing item found with etag: " + currentEtag + " client etag: " + etag + " id: " + currentItemId.id); } if ("*".equals(noneMatch)) { // create requested if (currentItemId != null) { itemResult.status = HttpStatus.SC_PRECONDITION_FAILED; return itemResult; } } else if (etag != null) { // update requested if (currentItemId == null || !etag.equals(currentEtag)) { itemResult.status = HttpStatus.SC_PRECONDITION_FAILED; return itemResult; } } if (vCalendar.isTodo()) { // create or update task method EWSMethod.Item newItem = new EWSMethod.Item(); newItem.type = "Task"; List<FieldUpdate> updates = new ArrayList<FieldUpdate>(); updates.add(Field.createFieldUpdate("calendaruid", vCalendar.getFirstVeventPropertyValue("UID"))); // force urlcompname updates.add(Field.createFieldUpdate("urlcompname", convertItemNameToEML(itemName))); updates.add(Field.createFieldUpdate("subject", vCalendar.getFirstVeventPropertyValue("SUMMARY"))); updates.add(Field.createFieldUpdate("description", vCalendar.getFirstVeventPropertyValue("DESCRIPTION"))); String percentComplete = vCalendar.getFirstVeventPropertyValue("PERCENT-COMPLETE"); if (percentComplete == null) { percentComplete = "0"; } updates.add(Field.createFieldUpdate("percentcomplete", percentComplete)); String vTodoStatus = vCalendar.getFirstVeventPropertyValue("STATUS"); if (vTodoStatus == null) { updates.add(Field.createFieldUpdate("taskstatus", "NotStarted")); } else { updates.add(Field.createFieldUpdate("taskstatus", vTodoToTaskStatusMap.get(vTodoStatus))); } <MASK>updates.add(Field.createFieldUpdate("keywords", vCalendar.getFirstVeventPropertyValue("CATEGORIES")));</MASK> updates.add(Field.createFieldUpdate("startdate", convertTaskDateToZulu(vCalendar.getFirstVeventPropertyValue("DTSTART")))); updates.add(Field.createFieldUpdate("duedate", convertTaskDateToZulu(vCalendar.getFirstVeventPropertyValue("DUE")))); updates.add(Field.createFieldUpdate("datecompleted", convertTaskDateToZulu(vCalendar.getFirstVeventPropertyValue("COMPLETED")))); updates.add(Field.createFieldUpdate("commonstart", convertTaskDateToZulu(vCalendar.getFirstVeventPropertyValue("DTSTART")))); updates.add(Field.createFieldUpdate("commonend", convertTaskDateToZulu(vCalendar.getFirstVeventPropertyValue("DUE")))); //updates.add(Field.createFieldUpdate("iscomplete", "COMPLETED".equals(vTodoStatus)?"True":"False")); if (currentItemId != null) { // update createOrUpdateItemMethod = new UpdateItemMethod(MessageDisposition.SaveOnly, ConflictResolution.AutoResolve, SendMeetingInvitationsOrCancellations.SendToNone, currentItemId, updates); } else { newItem.setFieldUpdates(updates); // create createOrUpdateItemMethod = new CreateItemMethod(MessageDisposition.SaveOnly, SendMeetingInvitations.SendToNone, getFolderId(folderPath), newItem); } } else { if (currentItemId != null) { /*Set<FieldUpdate> updates = new HashSet<FieldUpdate>(); // TODO: update properties instead of brute force delete/add updates.add(new FieldUpdate(Field.get("mimeContent"), new String(Base64.encodeBase64(itemContent)))); // update createOrUpdateItemMethod = new UpdateItemMethod(MessageDisposition.SaveOnly, ConflictResolution.AutoResolve, SendMeetingInvitationsOrCancellations.SendToNone, currentItemId, updates);*/ // hard method: delete/create on update DeleteItemMethod deleteItemMethod = new DeleteItemMethod(currentItemId, DeleteType.HardDelete, SendMeetingCancellations.SendToNone); executeMethod(deleteItemMethod); } //else { // create EWSMethod.Item newItem = new EWSMethod.Item(); newItem.type = "CalendarItem"; newItem.mimeContent = Base64.encodeBase64(vCalendar.toString().getBytes("UTF-8")); ArrayList<FieldUpdate> updates = new ArrayList<FieldUpdate>(); if (!vCalendar.hasVAlarm()) { updates.add(Field.createFieldUpdate("reminderset", "false")); } //updates.add(Field.createFieldUpdate("outlookmessageclass", "IPM.Appointment")); // force urlcompname updates.add(Field.createFieldUpdate("urlcompname", convertItemNameToEML(itemName))); if (vCalendar.isMeeting() && vCalendar.isMeetingOrganizer()) { updates.add(Field.createFieldUpdate("apptstateflags", "1")); } else { updates.add(Field.createFieldUpdate("apptstateflags", "0")); } // store mozilla invitations option String xMozSendInvitations = vCalendar.getFirstVeventPropertyValue("X-MOZ-SEND-INVITATIONS"); if (xMozSendInvitations != null) { updates.add(Field.createFieldUpdate("xmozsendinvitations", xMozSendInvitations)); } // handle mozilla alarm String xMozLastack = vCalendar.getFirstVeventPropertyValue("X-MOZ-LASTACK"); if (xMozLastack != null) { updates.add(Field.createFieldUpdate("xmozlastack", xMozLastack)); } String xMozSnoozeTime = vCalendar.getFirstVeventPropertyValue("X-MOZ-SNOOZE-TIME"); if (xMozSnoozeTime != null) { updates.add(Field.createFieldUpdate("xmozsnoozetime", xMozSnoozeTime)); } if (vCalendar.isMeeting()) { VCalendar.Recipients recipients = vCalendar.getRecipients(false); if (recipients.attendees != null) { updates.add(Field.createFieldUpdate("to", recipients.attendees)); } if (recipients.optionalAttendees != null) { updates.add(Field.createFieldUpdate("cc", recipients.optionalAttendees)); } if (recipients.organizer != null && !vCalendar.isMeetingOrganizer()) { updates.add(Field.createFieldUpdate("from", recipients.optionalAttendees)); } } // patch allday date values if (vCalendar.isCdoAllDay()) { updates.add(Field.createFieldUpdate("dtstart", convertCalendarDateToExchange(vCalendar.getFirstVeventPropertyValue("DTSTART")))); updates.add(Field.createFieldUpdate("dtend", convertCalendarDateToExchange(vCalendar.getFirstVeventPropertyValue("DTEND")))); } updates.add(Field.createFieldUpdate("busystatus", "BUSY".equals(vCalendar.getFirstVeventPropertyValue("X-MICROSOFT-CDO-BUSYSTATUS")) ? "Busy" : "Free")); if (vCalendar.isCdoAllDay()) { if ("Exchange2010".equals(serverVersion)) { updates.add(Field.createFieldUpdate("starttimezone", vCalendar.getVTimezone().getPropertyValue("TZID"))); } else { updates.add(Field.createFieldUpdate("meetingtimezone", vCalendar.getVTimezone().getPropertyValue("TZID"))); } } newItem.setFieldUpdates(updates); createOrUpdateItemMethod = new CreateItemMethod(MessageDisposition.SaveOnly, SendMeetingInvitations.SendToNone, getFolderId(folderPath), newItem); //} } executeMethod(createOrUpdateItemMethod); itemResult.status = createOrUpdateItemMethod.getStatusCode(); if (itemResult.status == HttpURLConnection.HTTP_OK) { //noinspection VariableNotUsedInsideIf if (currentItemId == null) { itemResult.status = HttpStatus.SC_CREATED; LOGGER.debug("Created event " + getHref()); } else { LOGGER.warn("Overwritten event " + getHref()); } } ItemId newItemId = new ItemId(createOrUpdateItemMethod.getResponseItem()); GetItemMethod getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, newItemId, false); getItemMethod.addAdditionalProperty(Field.get("etag")); executeMethod(getItemMethod); itemResult.etag = getItemMethod.getResponseItem().get(Field.get("etag").getResponseName()); return itemResult; }"
Inversion-Mutation
megadiff
"protected void transferOutputSettings(TransletOutputHandler output) { // It is an error if this method is called with anything else than // the translet post-processor (TextOutput) if (!(output instanceof TextOutput)) return; TextOutput handler = (TextOutput)output; // Transfer the output method setting if (_method != null) { // Transfer all settings relevant to XML output if (_method.equals("xml")) { if (_standalone != null) handler.setStandalone(_standalone); if (_omitHeader) handler.omitHeader(true); handler.setType(TextOutput.XML); handler.setCdataElements(_cdata); if (_version != null) handler.setVersion(_version); handler.setIndent(_indent); if (_doctypeSystem != null) handler.setDoctype(_doctypeSystem, _doctypePublic); } // Transfer all output settings relevant to HTML output else if (_method.equals("html")) { handler.setType(TextOutput.HTML); handler.setIndent(_indent); handler.setDoctype(_doctypeSystem, _doctypePublic); if (_mediaType != null) handler.setMediaType(_mediaType); } else if (_method.equals("text")) { handler.setType(TextOutput.TEXT); } else { handler.setType(TextOutput.QNAME); } } else { handler.setCdataElements(_cdata); if (_version != null) handler.setVersion(_version); if (_standalone != null) handler.setStandalone(_standalone); if (_omitHeader) handler.omitHeader(true); handler.setIndent(_indent); handler.setDoctype(_doctypeSystem, _doctypePublic); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "transferOutputSettings"
"protected void transferOutputSettings(TransletOutputHandler output) { // It is an error if this method is called with anything else than // the translet post-processor (TextOutput) if (!(output instanceof TextOutput)) return; TextOutput handler = (TextOutput)output; // Transfer the output method setting if (_method != null) { // Transfer all settings relevant to XML output if (_method.equals("xml")) { if (_standalone != null) handler.setStandalone(_standalone); handler.setType(TextOutput.XML); handler.setCdataElements(_cdata); if (_version != null) handler.setVersion(_version); <MASK>if (_omitHeader) handler.omitHeader(true);</MASK> handler.setIndent(_indent); if (_doctypeSystem != null) handler.setDoctype(_doctypeSystem, _doctypePublic); } // Transfer all output settings relevant to HTML output else if (_method.equals("html")) { handler.setType(TextOutput.HTML); handler.setIndent(_indent); handler.setDoctype(_doctypeSystem, _doctypePublic); if (_mediaType != null) handler.setMediaType(_mediaType); } else if (_method.equals("text")) { handler.setType(TextOutput.TEXT); } else { handler.setType(TextOutput.QNAME); } } else { handler.setCdataElements(_cdata); if (_version != null) handler.setVersion(_version); if (_standalone != null) handler.setStandalone(_standalone); <MASK>if (_omitHeader) handler.omitHeader(true);</MASK> handler.setIndent(_indent); handler.setDoctype(_doctypeSystem, _doctypePublic); } }"
Inversion-Mutation
megadiff
"public DriverConfiguration(Class<?> klass) { InputStream in = null; props = new Properties(); try { in = klass.getResourceAsStream(FILE_NAME); if (in != null) { props.load(in); } } catch (IOException e) { // silent } finally { Closeables.closeQuietly(in); } // system properties take precedence props.putAll(System.getProperties()); if (props.get(PROP_PORT) != null) { port = Integer.parseInt(props.getProperty(PROP_PORT)); } if (props.get(PROP_WAIT_FOR_BROWSER) != null) { waitForBrowser = Integer.parseInt(props.getProperty(PROP_WAIT_FOR_BROWSER)); } if (props.get(PROP_SKIP_IF_NO_BROWSER) != null) { skipIfNoBrowser = Boolean.parseBoolean(props.getProperty(PROP_SKIP_IF_NO_BROWSER)); } if (props.get(PROP_START_BROWSER) != null) { startBrowser = Boolean.parseBoolean(props.getProperty(PROP_START_BROWSER)); } if (props.get(PROP_TEST_TIMEOUT) != null) { testTimeout = Integer.parseInt(props.getProperty(PROP_TEST_TIMEOUT)); } if (props.get(PROP_BROWSER_COUNT) != null) { System.out.println("Configuration property " + PROP_BROWSER_COUNT + " is now ignored, use " + PROP_BROWSERS + " instead"); } if (props.get(PROP_DEBUG) != null) { debugEnabled = Boolean.parseBoolean(props.getProperty(PROP_DEBUG)); } classLoader = new WebAppClassLoader(new URL[] {}, klass.getClassLoader(), debugEnabled); // load browsers last browsers = instantiateBrowsers(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "DriverConfiguration"
"public DriverConfiguration(Class<?> klass) { InputStream in = null; try { in = klass.getResourceAsStream(FILE_NAME); if (in != null) { <MASK>props = new Properties();</MASK> props.load(in); } } catch (IOException e) { // silent } finally { Closeables.closeQuietly(in); } // system properties take precedence props.putAll(System.getProperties()); if (props.get(PROP_PORT) != null) { port = Integer.parseInt(props.getProperty(PROP_PORT)); } if (props.get(PROP_WAIT_FOR_BROWSER) != null) { waitForBrowser = Integer.parseInt(props.getProperty(PROP_WAIT_FOR_BROWSER)); } if (props.get(PROP_SKIP_IF_NO_BROWSER) != null) { skipIfNoBrowser = Boolean.parseBoolean(props.getProperty(PROP_SKIP_IF_NO_BROWSER)); } if (props.get(PROP_START_BROWSER) != null) { startBrowser = Boolean.parseBoolean(props.getProperty(PROP_START_BROWSER)); } if (props.get(PROP_TEST_TIMEOUT) != null) { testTimeout = Integer.parseInt(props.getProperty(PROP_TEST_TIMEOUT)); } if (props.get(PROP_BROWSER_COUNT) != null) { System.out.println("Configuration property " + PROP_BROWSER_COUNT + " is now ignored, use " + PROP_BROWSERS + " instead"); } if (props.get(PROP_DEBUG) != null) { debugEnabled = Boolean.parseBoolean(props.getProperty(PROP_DEBUG)); } classLoader = new WebAppClassLoader(new URL[] {}, klass.getClassLoader(), debugEnabled); // load browsers last browsers = instantiateBrowsers(); }"
Inversion-Mutation
megadiff
"private void processWeatherStations(List<WeatherStation<?>> weatherStations) { Collections.sort(weatherStations, new WeatherStationComparator()); for (WeatherStation<?> weatherStation : weatherStations) { try { if(weatherStation.isEnabled()) { processWeatherStation(weatherStation); } } catch (Exception e) { log("Error occured while processing: " + weatherStation); if (!inErrorHandling) { failedWeatherStations.add(weatherStation); e.printStackTrace(); } } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "processWeatherStations"
"private void processWeatherStations(List<WeatherStation<?>> weatherStations) { Collections.sort(weatherStations, new WeatherStationComparator()); for (WeatherStation<?> weatherStation : weatherStations) { try { if(weatherStation.isEnabled()) { processWeatherStation(weatherStation); } } catch (Exception e) { log("Error occured while processing: " + weatherStation); if (!inErrorHandling) { failedWeatherStations.add(weatherStation); } <MASK>e.printStackTrace();</MASK> } } }"
Inversion-Mutation
megadiff
"public BufferedImage paintOffscreen(final Layer layer, final ArrayList<Displayable> al_paint, final Displayable active, final int g_width, final int g_height, final int c_alphas, final Loader loader, final HashMap<Color,Layer> hm, final ArrayList<LayerPanel> blending_list, final int mode, final GraphicsSource graphics_source, final boolean prepaint, int first_non_patch) { try { // ALMOST, but not always perfect //if (null != clipRect) g.setClip(clipRect); // prepare the canvas for the srcRect and magnification final AffineTransform atc = new AffineTransform(); atc.scale(magnification, magnification); atc.translate(-srcRect.x, -srcRect.y); // the non-srcRect areas, in offscreen coords final Rectangle r1 = new Rectangle(srcRect.x + srcRect.width, srcRect.y, (int)(g_width / magnification) - srcRect.width, (int)(g_height / magnification)); final Rectangle r2 = new Rectangle(srcRect.x, srcRect.y + srcRect.height, srcRect.width, (int)(g_height / magnification) - srcRect.height); // create new graphics try { display.getProject().getLoader().releaseToFit(g_width * g_height * 10); } catch (Exception e) {} // when closing, asynch state may throw for a null loader. final BufferedImage target = getGraphicsConfiguration().createCompatibleImage(g_width, g_height, Transparency.TRANSLUCENT); // creates a BufferedImage.TYPE_INT_ARGB image in my T60p ATI FireGL laptop //Utils.log2("offscreen acceleration priority: " + target.getAccelerationPriority()); final Graphics2D g = target.createGraphics(); g.setTransform(atc); //at_original); //setRenderingHints(g); // always a stroke of 1.0, regardless of magnification; the stroke below corrects for that g.setStroke(stroke); // Testing: removed Area.subtract, now need to fill in background g.setColor(Color.black); g.fillRect(0, 0, g_width - r1.x, g_height - r2.y); // paint: // 1 - background // 2 - images and anything else not on al_top // 3 - non-srcRect areas //Utils.log2("offscreen painting: " + al_paint.size()); // filter paintables final Collection<? extends Paintable> paintables = graphics_source.asPaintable(al_paint); // adjust: first_non_patch = paintables.size() - (al_paint.size() - first_non_patch); // Determine painting mode if (Display.REPAINT_SINGLE_LAYER == mode) { if (display.isLiveFilteringEnabled()) { paintWithFiltering(g, al_paint, paintables, first_non_patch, g_width, g_height, active, c_alphas, layer, true); } else { // Direct painting mode, with prePaint abilities int i = 0; for (final Paintable d : paintables) { if (i == first_non_patch) { //Object antialias = g.getRenderingHint(RenderingHints.KEY_ANTIALIASING); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // to smooth edges of the images //Object text_antialias = g.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); //Object render_quality = g.getRenderingHint(RenderingHints.KEY_RENDERING); g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); } if (prepaint) d.prePaint(g, srcRect, magnification, d == active, c_alphas, layer); else d.paint(g, srcRect, magnification, d == active, c_alphas, layer); i++; } } } else if (Display.REPAINT_MULTI_LAYER == mode) { // paint first the current layer Patches only (to set the background) // With prePaint capabilities: if (display.isLiveFilteringEnabled()) { paintWithFiltering(g, al_paint, paintables, first_non_patch, g_width, g_height, active, c_alphas, layer, false); } else { int i = 0; if (prepaint) { for (final Paintable d : paintables) { if (first_non_patch == i) break; d.prePaint(g, srcRect, magnification, d == active, c_alphas, layer); i++; } } else { for (final Paintable d : paintables) { if (first_non_patch == i) break; d.paint(g, srcRect, magnification, d == active, c_alphas, layer); i++; } } } // then blend on top the ImageData of the others, in reverse Z order and using the alpha of the LayerPanel final Composite original = g.getComposite(); // reset g.setTransform(new AffineTransform()); for (final ListIterator<LayerPanel> it = blending_list.listIterator(blending_list.size()); it.hasPrevious(); ) { final LayerPanel lp = it.previous(); if (lp.layer == layer) continue; layer.getProject().getLoader().releaseToFit(g_width * g_height * 4 + 1024); final BufferedImage bi = getGraphicsConfiguration().createCompatibleImage(g_width, g_height, Transparency.TRANSLUCENT); final Graphics2D gb = bi.createGraphics(); gb.setTransform(atc); for (final Displayable d : lp.layer.find(srcRect, true)) { if ( ! ImageData.class.isInstance(d)) continue; // skip non-images d.paint(gb, srcRect, magnification, false, c_alphas, lp.layer); // not prePaint! We want direct painting, even if potentially slow } // Repeating loop ... the human compiler at work, just because one cannot lazily concatenate both sequences: for (final Displayable d : lp.layer.getParent().roughlyFindZDisplayables(lp.layer, srcRect, true)) { if ( ! ImageData.class.isInstance(d)) continue; // skip non-images d.paint(gb, srcRect, magnification, false, c_alphas, lp.layer); // not prePaint! We want direct painting, even if potentially slow } try { g.setComposite(Displayable.getComposite(display.getLayerCompositeMode(lp.layer), lp.getAlpha())); g.drawImage(display.applyFilters(bi), 0, 0, null); } catch (Throwable t) { Utils.log("Could not use composite mode for layer overlays! Your graphics card may not support it."); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, lp.getAlpha())); g.drawImage(bi, 0, 0, null); IJError.print(t); } bi.flush(); } // restore g.setComposite(original); g.setTransform(atc); // then paint the non-Patch objects of the current layer //Object antialias = g.getRenderingHint(RenderingHints.KEY_ANTIALIASING); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // to smooth edges of the images //Object text_antialias = g.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); //Object render_quality = g.getRenderingHint(RenderingHints.KEY_RENDERING); g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); // TODO this loop should be reading from the paintable_patches and paintables, since they length/order *could* have changed // And yes this means iterating and checking the Class of each. for (int i = first_non_patch; i < al_paint.size(); i++) { final Displayable d = al_paint.get(i); d.paint(g, srcRect, magnification, d == active, c_alphas, layer); } } else if(Display.REPAINT_RGB_LAYER == mode) { // TODO rewrite to avoid calling the list twice final Collection<? extends Paintable> paintable_patches = graphics_source.asPaintable(al_paint); // final HashMap<Color,byte[]> channels = new HashMap<Color,byte[]>(); hm.put(Color.green, layer); for (final Map.Entry<Color,Layer> e : hm.entrySet()) { final BufferedImage bi = new BufferedImage(g_width, g_height, BufferedImage.TYPE_BYTE_GRAY); //INDEXED, Loader.GRAY_LUT); final Graphics2D gb = bi.createGraphics(); gb.setTransform(atc); final Layer la = e.getValue(); ArrayList<Paintable> list = new ArrayList<Paintable>(); if (la == layer) { if (Color.green != e.getKey()) continue; // don't paint current layer in two channels list.addAll(paintable_patches); } else { list.addAll(la.find(Patch.class, srcRect, true)); } list.addAll(la.getParent().getZDisplayables(ImageData.class, true)); // Stack.class and perhaps others for (final Paintable d : list) { d.paint(gb, srcRect, magnification, false, c_alphas, la); } channels.put(e.getKey(), (byte[])new ByteProcessor(bi).getPixels()); } final byte[] red, green, blue; green = channels.get(Color.green); if (null == channels.get(Color.red)) red = new byte[green.length]; else red = channels.get(Color.red); if (null == channels.get(Color.blue)) blue = new byte[green.length]; else blue = channels.get(Color.blue); final int[] pix = new int[green.length]; for (int i=0; i<green.length; i++) { pix[i] = ((red[i] & 0xff) << 16) + ((green[i] & 0xff) << 8) + (blue[i] & 0xff); } // undo transform, is intended for Displayable objects g.setTransform(new AffineTransform()); final ColorProcessor cp = new ColorProcessor(g_width, g_height, pix); if (display.invert_colors) cp.invert(); display.applyFilters(cp); final Image img = cp.createImage(); g.drawImage(img, 0, 0, null); img.flush(); // reset g.setTransform(atc); // then paint the non-Image objects of the current layer //Object antialias = g.getRenderingHint(RenderingHints.KEY_ANTIALIASING); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // to smooth edges of the images //Object text_antialias = g.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); //Object render_quality = g.getRenderingHint(RenderingHints.KEY_RENDERING); g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); for (final Displayable d : al_paint) { if (ImageData.class.isInstance(d)) continue; d.paint(g, srcRect, magnification, d == active, c_alphas, layer); } // TODO having each object type in a key/list<type> table would be so much easier and likely performant. } // finally, paint non-srcRect areas if (r1.width > 0 || r1.height > 0 || r2.width > 0 || r2.height > 0) { g.setColor(Color.gray); g.setClip(r1); g.fill(r1); g.setClip(r2); g.fill(r2); } return target; } catch (OutOfMemoryError oome) { // so OutOfMemoryError won't generate locks IJError.print(oome); } catch (Exception e) { IJError.print(e); } return null; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "paintOffscreen"
"public BufferedImage paintOffscreen(final Layer layer, final ArrayList<Displayable> al_paint, final Displayable active, final int g_width, final int g_height, final int c_alphas, final Loader loader, final HashMap<Color,Layer> hm, final ArrayList<LayerPanel> blending_list, final int mode, final GraphicsSource graphics_source, final boolean prepaint, int first_non_patch) { try { // ALMOST, but not always perfect //if (null != clipRect) g.setClip(clipRect); // prepare the canvas for the srcRect and magnification final AffineTransform atc = new AffineTransform(); atc.scale(magnification, magnification); atc.translate(-srcRect.x, -srcRect.y); // the non-srcRect areas, in offscreen coords final Rectangle r1 = new Rectangle(srcRect.x + srcRect.width, srcRect.y, (int)(g_width / magnification) - srcRect.width, (int)(g_height / magnification)); final Rectangle r2 = new Rectangle(srcRect.x, srcRect.y + srcRect.height, srcRect.width, (int)(g_height / magnification) - srcRect.height); // create new graphics try { display.getProject().getLoader().releaseToFit(g_width * g_height * 10); } catch (Exception e) {} // when closing, asynch state may throw for a null loader. final BufferedImage target = getGraphicsConfiguration().createCompatibleImage(g_width, g_height, Transparency.TRANSLUCENT); // creates a BufferedImage.TYPE_INT_ARGB image in my T60p ATI FireGL laptop //Utils.log2("offscreen acceleration priority: " + target.getAccelerationPriority()); final Graphics2D g = target.createGraphics(); g.setTransform(atc); //at_original); //setRenderingHints(g); // always a stroke of 1.0, regardless of magnification; the stroke below corrects for that g.setStroke(stroke); // Testing: removed Area.subtract, now need to fill in background g.setColor(Color.black); g.fillRect(0, 0, g_width - r1.x, g_height - r2.y); // paint: // 1 - background // 2 - images and anything else not on al_top // 3 - non-srcRect areas //Utils.log2("offscreen painting: " + al_paint.size()); // filter paintables final Collection<? extends Paintable> paintables = graphics_source.asPaintable(al_paint); // adjust: first_non_patch = paintables.size() - (al_paint.size() - first_non_patch); // Determine painting mode if (Display.REPAINT_SINGLE_LAYER == mode) { if (display.isLiveFilteringEnabled()) { paintWithFiltering(g, al_paint, paintables, first_non_patch, g_width, g_height, active, c_alphas, layer, true); } else { // Direct painting mode, with prePaint abilities int i = 0; for (final Paintable d : paintables) { <MASK>i++;</MASK> if (i == first_non_patch) { //Object antialias = g.getRenderingHint(RenderingHints.KEY_ANTIALIASING); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // to smooth edges of the images //Object text_antialias = g.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); //Object render_quality = g.getRenderingHint(RenderingHints.KEY_RENDERING); g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); } if (prepaint) d.prePaint(g, srcRect, magnification, d == active, c_alphas, layer); else d.paint(g, srcRect, magnification, d == active, c_alphas, layer); } } } else if (Display.REPAINT_MULTI_LAYER == mode) { // paint first the current layer Patches only (to set the background) // With prePaint capabilities: if (display.isLiveFilteringEnabled()) { paintWithFiltering(g, al_paint, paintables, first_non_patch, g_width, g_height, active, c_alphas, layer, false); } else { int i = 0; if (prepaint) { for (final Paintable d : paintables) { if (first_non_patch == i) break; d.prePaint(g, srcRect, magnification, d == active, c_alphas, layer); <MASK>i++;</MASK> } } else { for (final Paintable d : paintables) { if (first_non_patch == i) break; d.paint(g, srcRect, magnification, d == active, c_alphas, layer); <MASK>i++;</MASK> } } } // then blend on top the ImageData of the others, in reverse Z order and using the alpha of the LayerPanel final Composite original = g.getComposite(); // reset g.setTransform(new AffineTransform()); for (final ListIterator<LayerPanel> it = blending_list.listIterator(blending_list.size()); it.hasPrevious(); ) { final LayerPanel lp = it.previous(); if (lp.layer == layer) continue; layer.getProject().getLoader().releaseToFit(g_width * g_height * 4 + 1024); final BufferedImage bi = getGraphicsConfiguration().createCompatibleImage(g_width, g_height, Transparency.TRANSLUCENT); final Graphics2D gb = bi.createGraphics(); gb.setTransform(atc); for (final Displayable d : lp.layer.find(srcRect, true)) { if ( ! ImageData.class.isInstance(d)) continue; // skip non-images d.paint(gb, srcRect, magnification, false, c_alphas, lp.layer); // not prePaint! We want direct painting, even if potentially slow } // Repeating loop ... the human compiler at work, just because one cannot lazily concatenate both sequences: for (final Displayable d : lp.layer.getParent().roughlyFindZDisplayables(lp.layer, srcRect, true)) { if ( ! ImageData.class.isInstance(d)) continue; // skip non-images d.paint(gb, srcRect, magnification, false, c_alphas, lp.layer); // not prePaint! We want direct painting, even if potentially slow } try { g.setComposite(Displayable.getComposite(display.getLayerCompositeMode(lp.layer), lp.getAlpha())); g.drawImage(display.applyFilters(bi), 0, 0, null); } catch (Throwable t) { Utils.log("Could not use composite mode for layer overlays! Your graphics card may not support it."); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, lp.getAlpha())); g.drawImage(bi, 0, 0, null); IJError.print(t); } bi.flush(); } // restore g.setComposite(original); g.setTransform(atc); // then paint the non-Patch objects of the current layer //Object antialias = g.getRenderingHint(RenderingHints.KEY_ANTIALIASING); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // to smooth edges of the images //Object text_antialias = g.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); //Object render_quality = g.getRenderingHint(RenderingHints.KEY_RENDERING); g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); // TODO this loop should be reading from the paintable_patches and paintables, since they length/order *could* have changed // And yes this means iterating and checking the Class of each. for (int i = first_non_patch; i < al_paint.size(); i++) { final Displayable d = al_paint.get(i); d.paint(g, srcRect, magnification, d == active, c_alphas, layer); } } else if(Display.REPAINT_RGB_LAYER == mode) { // TODO rewrite to avoid calling the list twice final Collection<? extends Paintable> paintable_patches = graphics_source.asPaintable(al_paint); // final HashMap<Color,byte[]> channels = new HashMap<Color,byte[]>(); hm.put(Color.green, layer); for (final Map.Entry<Color,Layer> e : hm.entrySet()) { final BufferedImage bi = new BufferedImage(g_width, g_height, BufferedImage.TYPE_BYTE_GRAY); //INDEXED, Loader.GRAY_LUT); final Graphics2D gb = bi.createGraphics(); gb.setTransform(atc); final Layer la = e.getValue(); ArrayList<Paintable> list = new ArrayList<Paintable>(); if (la == layer) { if (Color.green != e.getKey()) continue; // don't paint current layer in two channels list.addAll(paintable_patches); } else { list.addAll(la.find(Patch.class, srcRect, true)); } list.addAll(la.getParent().getZDisplayables(ImageData.class, true)); // Stack.class and perhaps others for (final Paintable d : list) { d.paint(gb, srcRect, magnification, false, c_alphas, la); } channels.put(e.getKey(), (byte[])new ByteProcessor(bi).getPixels()); } final byte[] red, green, blue; green = channels.get(Color.green); if (null == channels.get(Color.red)) red = new byte[green.length]; else red = channels.get(Color.red); if (null == channels.get(Color.blue)) blue = new byte[green.length]; else blue = channels.get(Color.blue); final int[] pix = new int[green.length]; for (int i=0; i<green.length; i++) { pix[i] = ((red[i] & 0xff) << 16) + ((green[i] & 0xff) << 8) + (blue[i] & 0xff); } // undo transform, is intended for Displayable objects g.setTransform(new AffineTransform()); final ColorProcessor cp = new ColorProcessor(g_width, g_height, pix); if (display.invert_colors) cp.invert(); display.applyFilters(cp); final Image img = cp.createImage(); g.drawImage(img, 0, 0, null); img.flush(); // reset g.setTransform(atc); // then paint the non-Image objects of the current layer //Object antialias = g.getRenderingHint(RenderingHints.KEY_ANTIALIASING); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // to smooth edges of the images //Object text_antialias = g.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); //Object render_quality = g.getRenderingHint(RenderingHints.KEY_RENDERING); g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); for (final Displayable d : al_paint) { if (ImageData.class.isInstance(d)) continue; d.paint(g, srcRect, magnification, d == active, c_alphas, layer); } // TODO having each object type in a key/list<type> table would be so much easier and likely performant. } // finally, paint non-srcRect areas if (r1.width > 0 || r1.height > 0 || r2.width > 0 || r2.height > 0) { g.setColor(Color.gray); g.setClip(r1); g.fill(r1); g.setClip(r2); g.fill(r2); } return target; } catch (OutOfMemoryError oome) { // so OutOfMemoryError won't generate locks IJError.print(oome); } catch (Exception e) { IJError.print(e); } return null; }"
Inversion-Mutation
megadiff
"public ImageExporter(Configuration config, Results results, CLIArgumentsGroup expectedGroup) { this.results = results; /* parse background color and other configuration options */ float[] clearColor = {0f, 0f, 0f}; if (config.containsKey(BG_COLOR_CONFIG_KEY)) { try { Color.decode(config.getString(BG_COLOR_CONFIG_KEY)) .getColorComponents(clearColor); } catch (NumberFormatException e) { System.err.println("incorrect color value: " + config.getString(BG_COLOR_CONFIG_KEY)); } } int canvasLimit = config.getInt(CANVAS_LIMIT_CONFIG_KEY, DEFAULT_CANVAS_LIMIT); /* find out what number and size of image file requests to expect */ int expectedFileCalls = 0; int expectedMaxSizeX = 1; int expectedMaxSizeY = 1; for (CLIArguments args : expectedGroup.getCLIArgumentsList()) { for (File outputFile : args.getOutput()) { OutputMode outputMode = CLIArgumentsUtil.getOutputMode(outputFile); if (outputMode == OutputMode.PNG || outputMode == OutputMode.PPM) { expectedFileCalls = 1; expectedMaxSizeX = max(expectedMaxSizeX, args.getResolution().x); expectedMaxSizeY = max(expectedMaxSizeY, args.getResolution().y); } } } /* create GL canvas and set rendering parameters */ GLProfile profile = GLProfile.getDefault(); GLDrawableFactory factory = GLDrawableFactory.getFactory(profile); if (! factory.canCreateGLPbuffer(null)) { throw new Error("Cannot create GLPbuffer for OpenGL output!"); } GLCapabilities cap = new GLCapabilities(profile); cap.setDoubleBuffered(false); pBufferSizeX = min(canvasLimit, expectedMaxSizeX); pBufferSizeY = min(canvasLimit, expectedMaxSizeY); pBuffer = factory.createGLPbuffer(null, cap, null, pBufferSizeX, pBufferSizeY, null); pBuffer.getContext().makeCurrent(); gl = pBuffer.getGL().getGL2(); gl.glFrontFace(GL_CCW); // use ccw polygons gl.glClearColor(clearColor[0], clearColor[1], clearColor[2], 1.0f); gl.glEnable (GL_DEPTH_TEST); // z buffer gl.glCullFace(GL_BACK); gl.glEnable (GL_CULL_FACE); // backface culling gl.glLightfv(GL_LIGHT0, GL_AMBIENT, new float[] {1.0f, 1.0f, 1.0f , 1.0f}, 0); gl.glLightfv(GL_LIGHT0, GL_DIFFUSE, new float[] {1.0f, 1.0f, 1.0f , 1.0f}, 0); gl.glLightfv(GL_LIGHT0, GL_SPECULAR, new float[] {1.0f, 1.0f, 1.0f , 1.0f}, 0); gl.glLightfv(GL_LIGHT0, GL_POSITION, new float[] {1.0f, 1.5f, -(-1.0f), 0.0f}, 0); gl.glEnable(GL_LIGHT0); gl.glEnable(GL_LIGHTING); gl.glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); /* render map data into buffer if it needs to be rendered multiple times */ if (config.getBoolean("forceUnbufferedPNGRendering", false) || (expectedFileCalls <= 1 && expectedMaxSizeX <= canvasLimit && expectedMaxSizeY <= canvasLimit) ) { PrimitiveBuffer buffer = new PrimitiveBuffer(); TargetUtil.renderWorldObjects(buffer, results.getMapData()); TargetUtil.renderObject(buffer, results.getTerrain()); bufferRenderer = new JOGLPrimitiveBufferRenderer(gl, buffer); } else { bufferRenderer = null; } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "ImageExporter"
"public ImageExporter(Configuration config, Results results, CLIArgumentsGroup expectedGroup) { this.results = results; /* parse background color and other configuration options */ float[] clearColor = {0f, 0f, 0f}; if (config.containsKey(BG_COLOR_CONFIG_KEY)) { try { Color.decode(config.getString(BG_COLOR_CONFIG_KEY)) .getColorComponents(clearColor); } catch (NumberFormatException e) { System.err.println("incorrect color value: " + config.getString(BG_COLOR_CONFIG_KEY)); } } int canvasLimit = config.getInt(CANVAS_LIMIT_CONFIG_KEY, DEFAULT_CANVAS_LIMIT); /* find out what number and size of image file requests to expect */ int expectedFileCalls = 0; int expectedMaxSizeX = 1; int expectedMaxSizeY = 1; for (CLIArguments args : expectedGroup.getCLIArgumentsList()) { for (File outputFile : args.getOutput()) { OutputMode outputMode = CLIArgumentsUtil.getOutputMode(outputFile); if (outputMode == OutputMode.PNG || outputMode == OutputMode.PPM) { expectedFileCalls = 1; expectedMaxSizeX = max(expectedMaxSizeX, args.getResolution().x); expectedMaxSizeY = max(expectedMaxSizeY, args.getResolution().y); } } } /* create GL canvas and set rendering parameters */ GLProfile profile = GLProfile.getDefault(); GLDrawableFactory factory = GLDrawableFactory.getFactory(profile); if (! factory.canCreateGLPbuffer(null)) { throw new Error("Cannot create GLPbuffer for OpenGL output!"); } GLCapabilities cap = new GLCapabilities(profile); cap.setDoubleBuffered(false); pBufferSizeX = min(canvasLimit, expectedMaxSizeX); pBufferSizeY = min(canvasLimit, expectedMaxSizeY); pBuffer = factory.createGLPbuffer(null, cap, null, pBufferSizeX, pBufferSizeY, null); <MASK>gl = pBuffer.getGL().getGL2();</MASK> pBuffer.getContext().makeCurrent(); gl.glFrontFace(GL_CCW); // use ccw polygons gl.glClearColor(clearColor[0], clearColor[1], clearColor[2], 1.0f); gl.glEnable (GL_DEPTH_TEST); // z buffer gl.glCullFace(GL_BACK); gl.glEnable (GL_CULL_FACE); // backface culling gl.glLightfv(GL_LIGHT0, GL_AMBIENT, new float[] {1.0f, 1.0f, 1.0f , 1.0f}, 0); gl.glLightfv(GL_LIGHT0, GL_DIFFUSE, new float[] {1.0f, 1.0f, 1.0f , 1.0f}, 0); gl.glLightfv(GL_LIGHT0, GL_SPECULAR, new float[] {1.0f, 1.0f, 1.0f , 1.0f}, 0); gl.glLightfv(GL_LIGHT0, GL_POSITION, new float[] {1.0f, 1.5f, -(-1.0f), 0.0f}, 0); gl.glEnable(GL_LIGHT0); gl.glEnable(GL_LIGHTING); gl.glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); /* render map data into buffer if it needs to be rendered multiple times */ if (config.getBoolean("forceUnbufferedPNGRendering", false) || (expectedFileCalls <= 1 && expectedMaxSizeX <= canvasLimit && expectedMaxSizeY <= canvasLimit) ) { PrimitiveBuffer buffer = new PrimitiveBuffer(); TargetUtil.renderWorldObjects(buffer, results.getMapData()); TargetUtil.renderObject(buffer, results.getTerrain()); bufferRenderer = new JOGLPrimitiveBufferRenderer(gl, buffer); } else { bufferRenderer = null; } }"
Inversion-Mutation
megadiff
"public void execute() throws HttpClientException { HttpURLConnection conn = null; UncloseableInputStream payloadStream = null; try { if (parameters != null && !parameters.isEmpty()) { final StringBuilder buf = new StringBuilder(256); if (!HTTP_POST.equals(method)) { buf.append('?'); } for (final Map.Entry<String, String> e : parameters.entrySet()) { if (buf.length() != 0) { buf.append("&"); } final String name = e.getKey(); final String value = e.getValue(); buf.append(URLEncoder.encode(name, CONTENT_CHARSET)) .append(URLEncoder.encode(value, CONTENT_CHARSET)); } if (HTTP_POST.equals(method)) { try { payload = buf.toString().getBytes(CONTENT_CHARSET); } catch (UnsupportedEncodingException e) { // Unlikely to happen. throw new HttpClientException("Encoding error", e); } } else { uri += buf; } } conn = (HttpURLConnection) new URL(uri).openConnection(); conn.setConnectTimeout(hc.getConnectTimeout()); conn.setReadTimeout(hc.getReadTimeout()); conn.setAllowUserInteraction(false); conn.setInstanceFollowRedirects(false); conn.setRequestMethod(method); if (HTTP_GET.equals(method)) { conn.setDoInput(true); } if (HTTP_POST.equals(method)) { conn.setDoOutput(true); conn.setUseCaches(false); } if (headers != null && !headers.isEmpty()) { for (final Map.Entry<String, List<String>> e : headers .entrySet()) { final List<String> values = e.getValue(); if (values != null) { final String name = e.getKey(); for (final String value : values) { conn.addRequestProperty(name, value); } } } } final StringBuilder cookieHeaderValue = new StringBuilder(256); prepareCookieHeader(cookies, cookieHeaderValue); prepareCookieHeader(hc.getInMemoryCookies(), cookieHeaderValue); conn.setRequestProperty("Cookie", cookieHeaderValue.toString()); final String userAgent = hc.getUserAgent(); if (userAgent != null) { conn.setRequestProperty("User-Agent", userAgent); } conn.setRequestProperty("Connection", "close"); conn.setRequestProperty("Location", uri); conn.setRequestProperty("Referrer", uri); conn.setRequestProperty("Accept-Encoding", "gzip,deflate"); conn.setRequestProperty("Accept-Charset", CONTENT_CHARSET); if (HTTP_POST.equals(method)) { conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + CONTENT_CHARSET); if (payload != null) { conn.setFixedLengthStreamingMode(payload.length); } } if (conn instanceof HttpsURLConnection) { setupSecureConnection(hc.getContext(), (HttpsURLConnection) conn); } conn.connect(); final int statusCode = conn.getResponseCode(); if (statusCode == -1) { throw new HttpClientException("Invalid response from " + uri); } if (!expectedStatusCodes.isEmpty() && !expectedStatusCodes.contains(statusCode)) { throw new HttpClientException("Expected status code " + expectedStatusCodes + ", got " + statusCode); } else if (expectedStatusCodes.isEmpty() && statusCode / 100 != 2) { throw new HttpClientException("Expected status code 2xx, got " + statusCode); } final Map<String, List<String>> headerFields = conn .getHeaderFields(); final Map<String, String> inMemoryCookies = hc.getInMemoryCookies(); if (headerFields != null) { final List<String> newCookies = headerFields.get("Set-Cookie"); if (newCookies != null) { for (final String newCookie : newCookies) { final String rawCookie = newCookie.split(";", 2)[0]; final int i = rawCookie.indexOf('='); final String name = rawCookie.substring(0, i); final String value = rawCookie.substring(i + 1); inMemoryCookies.put(name, value); } } } payloadStream = new UncloseableInputStream(getInputStream(conn)); if (handler != null) { final HttpResponse resp = new HttpResponse(statusCode, payloadStream, headerFields == null ? NO_HEADERS : headerFields, inMemoryCookies); try { handler.onResponse(resp); } catch (Exception e) { throw new HttpClientException("Error in response handler", e); } } } catch (SocketTimeoutException e) { if (handler != null) { try { handler.onTimeout(); } catch (Exception e2) { throw new HttpClientException("Error in response handler", e2); } } } catch (IOException e) { throw new HttpClientException("Connection failed to " + uri, e); } finally { if (conn != null) { if (payloadStream != null) { // Fully read Http response: // http://docs.oracle.com/javase/6/docs/technotes/guides/net/http-keepalive.html try { while (payloadStream.read(buffer) != -1) ; } catch (IOException ignore) { } payloadStream.forceClose(); } conn.disconnect(); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "execute"
"public void execute() throws HttpClientException { HttpURLConnection conn = null; UncloseableInputStream payloadStream = null; try { if (parameters != null && !parameters.isEmpty()) { final StringBuilder buf = new StringBuilder(256); if (!HTTP_POST.equals(method)) { buf.append('?'); } for (final Map.Entry<String, String> e : parameters.entrySet()) { if (buf.length() != 0) { buf.append("&"); } final String name = e.getKey(); final String value = e.getValue(); buf.append(URLEncoder.encode(name, CONTENT_CHARSET)) .append(URLEncoder.encode(value, CONTENT_CHARSET)); } if (HTTP_POST.equals(method)) { try { payload = buf.toString().getBytes(CONTENT_CHARSET); } catch (UnsupportedEncodingException e) { // Unlikely to happen. throw new HttpClientException("Encoding error", e); } } else { uri += buf; } } conn = (HttpURLConnection) new URL(uri).openConnection(); conn.setConnectTimeout(hc.getConnectTimeout()); conn.setReadTimeout(hc.getReadTimeout()); conn.setAllowUserInteraction(false); conn.setInstanceFollowRedirects(false); conn.setRequestMethod(method); if (HTTP_GET.equals(method)) { conn.setDoInput(true); } if (HTTP_POST.equals(method)) { conn.setDoOutput(true); conn.setUseCaches(false); } if (headers != null && !headers.isEmpty()) { for (final Map.Entry<String, List<String>> e : headers .entrySet()) { final List<String> values = e.getValue(); if (values != null) { final String name = e.getKey(); for (final String value : values) { conn.addRequestProperty(name, value); } } } } final StringBuilder cookieHeaderValue = new StringBuilder(256); prepareCookieHeader(cookies, cookieHeaderValue); prepareCookieHeader(hc.getInMemoryCookies(), cookieHeaderValue); conn.setRequestProperty("Cookie", cookieHeaderValue.toString()); final String userAgent = hc.getUserAgent(); if (userAgent != null) { conn.setRequestProperty("User-Agent", userAgent); } conn.setRequestProperty("Connection", "close"); conn.setRequestProperty("Location", uri); conn.setRequestProperty("Referrer", uri); conn.setRequestProperty("Accept-Encoding", "gzip,deflate"); conn.setRequestProperty("Accept-Charset", CONTENT_CHARSET); if (HTTP_POST.equals(method)) { conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + CONTENT_CHARSET); if (payload != null) { conn.setFixedLengthStreamingMode(payload.length); } } if (conn instanceof HttpsURLConnection) { setupSecureConnection(hc.getContext(), (HttpsURLConnection) conn); } conn.connect(); final int statusCode = conn.getResponseCode(); if (statusCode == -1) { throw new HttpClientException("Invalid response from " + uri); } if (!expectedStatusCodes.isEmpty() && !expectedStatusCodes.contains(statusCode)) { throw new HttpClientException("Expected status code " + expectedStatusCodes + ", got " + statusCode); } else if (expectedStatusCodes.isEmpty() && statusCode / 100 != 2) { throw new HttpClientException("Expected status code 2xx, got " + statusCode); } final Map<String, List<String>> headerFields = conn .getHeaderFields(); final Map<String, String> inMemoryCookies = hc.getInMemoryCookies(); if (headerFields != null) { final List<String> newCookies = headerFields.get("Set-Cookie"); if (newCookies != null) { for (final String newCookie : newCookies) { final String rawCookie = newCookie.split(";", 2)[0]; final int i = rawCookie.indexOf('='); final String name = rawCookie.substring(0, i); final String value = rawCookie.substring(i + 1); inMemoryCookies.put(name, value); } } } payloadStream = new UncloseableInputStream(getInputStream(conn)); if (handler != null) { final HttpResponse resp = new HttpResponse(statusCode, payloadStream, headerFields == null ? NO_HEADERS : headerFields, inMemoryCookies); try { handler.onResponse(resp); } catch (Exception e) { throw new HttpClientException("Error in response handler", e); } } } catch (SocketTimeoutException e) { if (handler != null) { try { handler.onTimeout(); } catch (Exception e2) { throw new HttpClientException("Error in response handler", e2); } } } catch (IOException e) { throw new HttpClientException("Connection failed to " + uri, e); } finally { if (conn != null) { if (payloadStream != null) { // Fully read Http response: // http://docs.oracle.com/javase/6/docs/technotes/guides/net/http-keepalive.html try { while (payloadStream.read(buffer) != -1) ; } catch (IOException ignore) { } } <MASK>payloadStream.forceClose();</MASK> conn.disconnect(); } } }"
Inversion-Mutation
megadiff
"@Override public List<MatchNode> search(String query) { List<MatchNode> result = new ArrayList<MatchNode>(); List<PatternRankResult> rankResult = new ArrayList<PatternRankResult>(); if (query.trim().equals("")) return result; if (sfMapList != null && sfMapList.size() > 0) for (SummaryFileMap map : sfMapList) { String summary = map.summary; rankQuery(summary.toLowerCase(), query.toLowerCase(), map.filePath, rankResult); } sortRankResult(rankResult); for(int k=0; k<Math.min(15, rankResult.size()); k++){ File jsonFile = new File(rankResult.get(k).getFilePath()); if (jsonFile.exists()) { Effect parent = GsonUtil.deserialize(jsonFile, Effect.class); parent.setId(System.currentTimeMillis() + String.valueOf(Math.random()).substring(5)); MatchNode[] children = new MatchNode[parent.getParameters().length]; this.values.clear(); if(rankResult.get(k).isInOrder()){ parseParameterValues(rankResult.get(k).getPattern(), query); } for (int i = 0; i < children.length; i++) { EffectParameter param = parent.getParameters()[i]; String keyName = param.getName().toLowerCase(); if(values.get(keyName) != null) param.setValue(values.get(keyName)); ArgumentMatchNode childNode = new ArgumentMatchNode(param.getName(), param); children[i] = childNode; } result.add(new EffectMatchNode(parent, rankResult.get(k).getPattern(), children)); } } return result; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "search"
"@Override public List<MatchNode> search(String query) { List<MatchNode> result = new ArrayList<MatchNode>(); List<PatternRankResult> rankResult = new ArrayList<PatternRankResult>(); if (query.trim().equals("")) return result; if (sfMapList != null && sfMapList.size() > 0) for (SummaryFileMap map : sfMapList) { String summary = map.summary; rankQuery(summary.toLowerCase(), query.toLowerCase(), map.filePath, rankResult); } sortRankResult(rankResult); for(int k=0; k<Math.min(15, rankResult.size()); k++){ File jsonFile = new File(rankResult.get(k).getFilePath()); if (jsonFile.exists()) { Effect parent = GsonUtil.deserialize(jsonFile, Effect.class); parent.setId(System.currentTimeMillis() + String.valueOf(Math.random()).substring(5)); MatchNode[] children = new MatchNode[parent.getParameters().length]; if(rankResult.get(k).isInOrder()){ <MASK>this.values.clear();</MASK> parseParameterValues(rankResult.get(k).getPattern(), query); } for (int i = 0; i < children.length; i++) { EffectParameter param = parent.getParameters()[i]; String keyName = param.getName().toLowerCase(); if(values.get(keyName) != null) param.setValue(values.get(keyName)); ArgumentMatchNode childNode = new ArgumentMatchNode(param.getName(), param); children[i] = childNode; } result.add(new EffectMatchNode(parent, rankResult.get(k).getPattern(), children)); } } return result; }"
Inversion-Mutation
megadiff
"public PageFetchResult fetchHeader(WebURL webUrl) { PageFetchResult fetchResult = new PageFetchResult(); String toFetchURL = webUrl.getURL(); HttpGet get = null; try { get = new HttpGet(toFetchURL); synchronized (mutex) { long now = (new Date()).getTime(); if (now - lastFetchTime < config.getPolitenessDelay()) { Thread.sleep(config.getPolitenessDelay() - (now - lastFetchTime)); } lastFetchTime = (new Date()).getTime(); } get.addHeader("Accept-Encoding", "gzip"); get.addHeader("Accept", "*/*"); for (final String header: config.getCustomHeaders()) { String name = header.split(":")[0]; String value = header.split(":")[1]; get.addHeader(name, value); } // Create a local instance of cookie store, and bind to local context // Without this we get killed w/lots of threads, due to sync() on single cookie store. HttpContext localContext = new BasicHttpContext(); CookieStore cookieStore = new BasicCookieStore(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpResponse response = httpClient.execute(get); fetchResult.setEntity(response.getEntity()); fetchResult.setResponseHeaders(response.getAllHeaders()); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { if (statusCode != HttpStatus.SC_NOT_FOUND) { if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { Header header = response.getFirstHeader("Location"); if (header != null) { String movedToUrl = header.getValue(); movedToUrl = URLCanonicalizer.getCanonicalURL(movedToUrl, toFetchURL); fetchResult.setMovedToUrl(movedToUrl); } fetchResult.setStatusCode(statusCode); return fetchResult; } logger.info("Failed: " + response.getStatusLine().toString() + ", while fetching " + toFetchURL); } fetchResult.setStatusCode(response.getStatusLine().getStatusCode()); return fetchResult; } fetchResult.setFetchedUrl(toFetchURL); String uri = get.getURI().toString(); if (!uri.equals(toFetchURL)) { if (!URLCanonicalizer.getCanonicalURL(uri).equals(toFetchURL)) { fetchResult.setFetchedUrl(uri); } } if (fetchResult.getEntity() != null) { long size = fetchResult.getEntity().getContentLength(); if (size == -1) { Header length = response.getLastHeader("Content-Length"); if (length == null) { length = response.getLastHeader("Content-length"); } if (length != null) { size = Integer.parseInt(length.getValue()); } else { size = -1; } } if (size > config.getMaxDownloadSize()) { fetchResult.setStatusCode(CustomFetchStatus.PageTooBig); get.abort(); logger.error("Failed: Page Size (" + size + ") exceeded max-download-size (" + config.getMaxDownloadSize() + ")"); return fetchResult; } fetchResult.setStatusCode(HttpStatus.SC_OK); return fetchResult; } get.abort(); } catch (IOException e) { logger.error("Fatal transport error: " + e.getMessage() + " while fetching " + toFetchURL + " (link found in doc #" + webUrl.getParentDocid() + ")"); fetchResult.setStatusCode(CustomFetchStatus.FatalTransportError); return fetchResult; } catch (IllegalStateException e) { // ignoring exceptions that occur because of not registering https // and other schemes } catch (Exception e) { if (e.getMessage() == null) { logger.error("Error while fetching " + webUrl.getURL(), e); } else { logger.error(e.getMessage() + " while fetching " + webUrl.getURL()); } } finally { try { if (fetchResult.getEntity() == null && get != null) { get.abort(); logger.error("Failed: To extract HTTP entity, from the fetched page result " + webUrl.getURL()); } } catch (Exception e) { e.printStackTrace(); } } fetchResult.setStatusCode(CustomFetchStatus.UnknownError); logger.error("Failed: Unknown error occurred., while fetching " + webUrl.getURL()); return fetchResult; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "fetchHeader"
"public PageFetchResult fetchHeader(WebURL webUrl) { PageFetchResult fetchResult = new PageFetchResult(); String toFetchURL = webUrl.getURL(); HttpGet get = null; try { get = new HttpGet(toFetchURL); synchronized (mutex) { long now = (new Date()).getTime(); if (now - lastFetchTime < config.getPolitenessDelay()) { Thread.sleep(config.getPolitenessDelay() - (now - lastFetchTime)); } lastFetchTime = (new Date()).getTime(); } get.addHeader("Accept-Encoding", "gzip"); get.addHeader("Accept", "*/*"); for (final String header: config.getCustomHeaders()) { String name = header.split(":")[0]; String value = header.split(":")[1]; get.addHeader(name, value); } // Create a local instance of cookie store, and bind to local context // Without this we get killed w/lots of threads, due to sync() on single cookie store. HttpContext localContext = new BasicHttpContext(); CookieStore cookieStore = new BasicCookieStore(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpResponse response = httpClient.execute(get); fetchResult.setEntity(response.getEntity()); fetchResult.setResponseHeaders(response.getAllHeaders()); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { if (statusCode != HttpStatus.SC_NOT_FOUND) { if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { Header header = response.getFirstHeader("Location"); if (header != null) { String movedToUrl = header.getValue(); movedToUrl = URLCanonicalizer.getCanonicalURL(movedToUrl, toFetchURL); fetchResult.setMovedToUrl(movedToUrl); } fetchResult.setStatusCode(statusCode); return fetchResult; } logger.info("Failed: " + response.getStatusLine().toString() + ", while fetching " + toFetchURL); } fetchResult.setStatusCode(response.getStatusLine().getStatusCode()); return fetchResult; } fetchResult.setFetchedUrl(toFetchURL); String uri = get.getURI().toString(); if (!uri.equals(toFetchURL)) { if (!URLCanonicalizer.getCanonicalURL(uri).equals(toFetchURL)) { fetchResult.setFetchedUrl(uri); } } if (fetchResult.getEntity() != null) { long size = fetchResult.getEntity().getContentLength(); if (size == -1) { Header length = response.getLastHeader("Content-Length"); if (length == null) { length = response.getLastHeader("Content-length"); } if (length != null) { size = Integer.parseInt(length.getValue()); } else { size = -1; } } if (size > config.getMaxDownloadSize()) { fetchResult.setStatusCode(CustomFetchStatus.PageTooBig); get.abort(); logger.error("Failed: Page Size (" + size + ") exceeded max-download-size (" + config.getMaxDownloadSize() + ")"); return fetchResult; } fetchResult.setStatusCode(HttpStatus.SC_OK); return fetchResult; } get.abort(); } catch (IOException e) { logger.error("Fatal transport error: " + e.getMessage() + " while fetching " + toFetchURL + " (link found in doc #" + webUrl.getParentDocid() + ")"); fetchResult.setStatusCode(CustomFetchStatus.FatalTransportError); return fetchResult; } catch (IllegalStateException e) { // ignoring exceptions that occur because of not registering https // and other schemes } catch (Exception e) { if (e.getMessage() == null) { logger.error("Error while fetching " + webUrl.getURL(), e); } else { logger.error(e.getMessage() + " while fetching " + webUrl.getURL()); } } finally { try { if (fetchResult.getEntity() == null && get != null) { get.abort(); } <MASK>logger.error("Failed: To extract HTTP entity, from the fetched page result " + webUrl.getURL());</MASK> } catch (Exception e) { e.printStackTrace(); } } fetchResult.setStatusCode(CustomFetchStatus.UnknownError); logger.error("Failed: Unknown error occurred., while fetching " + webUrl.getURL()); return fetchResult; }"
Inversion-Mutation
megadiff
"protected void extractContents() { ZipInputStream in = null; try { try { in = new ZipInputStream(new BufferedInputStream( GameModule.getGameModule().getDataArchive() .getInputStream("help/" + getContentsResource()))); //$NON-NLS-1$ } catch (IOException e) { // The help file was created with empty contents. // Assume an absolute URL as the starting page. url = new URL(startingPage); return; } final File tmp = File.createTempFile("VASSAL", "help"); //$NON-NLS-1$ //$NON-NLS-2$ File output = tmp.getParentFile(); tmp.delete(); output = new File(output, "VASSAL"); //$NON-NLS-1$ output = new File(output, "help"); //$NON-NLS-1$ output = new File(output, getContentsResource()); if (output.exists()) recursiveDelete(output); output.mkdirs(); ZipEntry entry; while ((entry = in.getNextEntry()) != null) { if (entry.isDirectory()) { new File(output, entry.getName()).mkdirs(); } else { // FIXME: no way to distinguish between read and write errors here FileOutputStream fos = null; try { fos = new FileOutputStream(new File(output, entry.getName())); IOUtils.copy(in, fos); fos.close(); } finally { IOUtils.closeQuietly(fos); } } } in.close(); url = new File(output, startingPage).toURI().toURL(); } // FIXME: review error message catch (IOException e) { Logger.log(e); } finally { IOUtils.closeQuietly(in); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "extractContents"
"protected void extractContents() { ZipInputStream in = null; try { try { in = new ZipInputStream(new BufferedInputStream( GameModule.getGameModule().getDataArchive() .getInputStream("help/" + getContentsResource()))); //$NON-NLS-1$ } catch (IOException e) { // The help file was created with empty contents. // Assume an absolute URL as the starting page. url = new URL(startingPage); return; } final File tmp = File.createTempFile("VASSAL", "help"); //$NON-NLS-1$ //$NON-NLS-2$ File output = tmp.getParentFile(); tmp.delete(); output = new File(output, "VASSAL"); //$NON-NLS-1$ output = new File(output, "help"); //$NON-NLS-1$ output = new File(output, getContentsResource()); if (output.exists()) recursiveDelete(output); output.mkdirs(); ZipEntry entry; while ((entry = in.getNextEntry()) != null) { if (entry.isDirectory()) { new File(output, entry.getName()).mkdirs(); } else { // FIXME: no way to distinguish between read and write errors here FileOutputStream fos = null; try { fos = new FileOutputStream(new File(output, entry.getName())); IOUtils.copy(in, fos); <MASK>in.close();</MASK> fos.close(); } finally { IOUtils.closeQuietly(fos); } } } url = new File(output, startingPage).toURI().toURL(); } // FIXME: review error message catch (IOException e) { Logger.log(e); } finally { IOUtils.closeQuietly(in); } }"
Inversion-Mutation
megadiff
"private MavenProject constructMavenProjectFromModel( Model model, File pomFile, File parentFile, ProjectBuilderConfiguration config ) throws ProjectBuildingException, InvalidRepositoryException { MavenProject project = new MavenProject( model, artifactFactory, mavenTools, this, config ); validateModel( model, pomFile ); Artifact projectArtifact = artifactFactory.createBuildArtifact( project.getGroupId(), project.getArtifactId(), project.getVersion(), project.getPackaging() ); project.setArtifact( projectArtifact ); project.setParentFile( parentFile ); return project; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "constructMavenProjectFromModel"
"private MavenProject constructMavenProjectFromModel( Model model, File pomFile, File parentFile, ProjectBuilderConfiguration config ) throws ProjectBuildingException, InvalidRepositoryException { MavenProject project = new MavenProject( model, artifactFactory, mavenTools, this, config ); Artifact projectArtifact = artifactFactory.createBuildArtifact( project.getGroupId(), project.getArtifactId(), project.getVersion(), project.getPackaging() ); project.setArtifact( projectArtifact ); project.setParentFile( parentFile ); <MASK>validateModel( model, pomFile );</MASK> return project; }"
Inversion-Mutation
megadiff
"@SuppressWarnings("unchecked") @Override protected Map referenceData(HttpServletRequest request, Object command, Errors errors, int page) throws Exception { ReportWizard wiz = (ReportWizard) command; Map refData = new HashMap(); refData.put("page",page); refData.put("maxpages", getPages().length-6); // 6 pages that are not actual steps // see if we went backwards if (wiz.getPreviousPage() > page) wiz.setPreviousPage(page -1); refData.put("previouspage", wiz.getPreviousPage()); // Load info passed to the wizard // if no user or password is in the request, see if the user has already been // populated on the wiz. Going to the second page and then back to the first could cause that. String userName = request.getParameter("username"); String password = request.getParameter("password"); if (userName == null || password == null) { userName = wiz.getUsername(); password = wiz.getPassword(); } else { GuruSessionData sessiondata = SessionHelper.getGuruSessionData(); sessiondata.setUsername(userName); sessiondata.setPassword(password); if (password.equals("/") || password.length() == 0) { UserDetails userDetails = userDetailsService.loadUserByUsername(userName); password = userDetails.getPassword(); } wiz.setUsername(userName); wiz.setPassword(password); } String reportUri = request.getParameter("reporturi"); if (reportUri != null && reportUri.length() > 0) { long reportId = -1; try { if (reportUri.contains("/THEGURU_")) reportId = Long.parseLong(reportUri.substring(reportUri.lastIndexOf("/THEGURU_") + 9)); if (reportId != -1) { ReportWizard tempWiz = reportWizardService.Find(reportId); if (tempWiz != null) { ReportWizardHelper.PopulateWizardFromSavedReport(wiz, tempWiz, page != 9); wiz.setPreviousDataSubSourceGroupId(wiz.getDataSubSourceGroupId()); wiz.setPreviousDataSubSourceId(wiz.getSubSourceId()); wiz.setReportPath(reportUri.substring(0, reportUri.indexOf("/THEGURU_"))); LoadWizardLookupTables(wiz); } else { errors.reject("1", "Unable to load report " + reportUri + ". You may continue to create a new report, or cancel to return to the report list."); } } } catch (Exception exception) { errors.reject("1", "Unable to load report " + reportUri + ". You may continue to create a new report, or cancel to return to the report list. " + exception.getMessage()); } } // If there is no user from the request or the wiz, send back to jasper server if (userName == null || password == null) { refData.put("userFound", false); } else { refData.put("userFound", true); refData.put("subSourceGroupId", wiz.getDataSubSourceGroupId()); refData.put("subSourceId", wiz.getSubSourceId()); wiz.getReportGenerator().setReportUserName(userName); wiz.getReportGenerator().setReportPassword(password); jasperServerService.setUserName(userName); jasperServerService.setPassword(password); //we want to allow the users logged in as a company to also see the default templates as well if (wiz.getReportTemplateList() != null) wiz.getReportTemplateList().clear(); if (!(wiz.getCompany().compareToIgnoreCase("default") == 0)) wiz.setReportTemplateList(jasperServerService.list("/Reports/Default/templates")); if (wiz.getReportTemplateList() != null) wiz.getReportTemplateList().addAll(jasperServerService.list("/Reports/" + wiz.getCompany() + "/templates")); else wiz.setReportTemplateList(jasperServerService.list("/Reports/" + wiz.getCompany() + "/templates")); if (wiz.getReportTemplateJRXML() == null || wiz.getReportTemplateJRXML().length() == 0) { if (wiz.getReportTemplateList().size() > 0) wiz.setReportTemplatePath(((ResourceDescriptor)wiz.getReportTemplateList().get(0)).getUriString()); else errors.reject("Invalid Repository","Invalid Repository. It appears your repository is not setup properly. Please contact your system administrator."); } } // // Report Source if (page == 0) { wiz.getReportGenerator().resetInputControls(); refData.put("previousSubSourceGroupId", wiz.getPreviousDataSubSourceGroupId()); refData.put("previousSubSourceId", wiz.getPreviousDataSubSourceId()); } // // Report Format if (page == 1) { String reportType = wiz.getReportType(); if (reportType.compareToIgnoreCase("summary") == 0) reportType = "tabular"; refData.put("reportType", reportType); } // // Report content selection if (page == 2) { String reportType = wiz.getReportType(); refData.put("reportType", reportType); Boolean reportUniqueRecords = wiz.getUniqueRecords(); refData.put("reportUniqueRecords", reportUniqueRecords); wiz.setUniqueRecords(false); ReportDataSubSource rdss = reportSubSourceService.find(wiz.getSubSourceId()); List<ReportFieldGroup> lrfg = reportFieldGroupService.readFieldGroupBySubSourceId(rdss.getId()); wiz.setFieldGroups(lrfg); refData.put("fieldGroups", wiz.getFieldGroups()); if (reportType.compareTo("tabular") == 0 || reportType.compareTo("summary") == 0) { List<ReportSelectedField> tempFields = new LinkedList<ReportSelectedField>(); tempFields.addAll(wiz.getReportSelectedFields()); refData.put("selectedFields", tempFields); // Clear out the selected fields because some items do not post back correctly wiz.getReportSelectedFields().clear(); refData.put("reportChartSettings", wiz.getReportChartSettings()); } else { List<ReportCrossTabColumn> tempColumns = new LinkedList<ReportCrossTabColumn>(); tempColumns.addAll(wiz.getReportCrossTabFields().getReportCrossTabColumns()); refData.put("matrixColumns", tempColumns); wiz.getReportCrossTabFields().getReportCrossTabColumns().clear(); List<ReportCrossTabRow> tempRows = new LinkedList<ReportCrossTabRow>(); tempRows.addAll(wiz.getReportCrossTabFields().getReportCrossTabRows()); refData.put("matrixRows", tempRows); wiz.getReportCrossTabFields().getReportCrossTabRows().clear(); List<ReportCrossTabMeasure> tempMeasures = new LinkedList<ReportCrossTabMeasure>(); tempMeasures.addAll(wiz.getReportCrossTabFields().getReportCrossTabMeasure()); refData.put("matrixMeasures", tempMeasures); wiz.getReportCrossTabFields().getReportCrossTabMeasure().clear(); } } // filter screen if(page==3) { ReportDataSubSource rdss = reportSubSourceService.find(wiz.getSubSourceId()); List<ReportFieldGroup> lrfg = reportFieldGroupService.readFieldGroupBySubSourceId(rdss.getId()); wiz.setFieldGroups(lrfg); if (wiz.getShowSqlQuery()) { ReportQueryGenerator reportQueryGenerator = new ReportQueryGenerator(wiz, reportFieldService, reportCustomFilterDefinitionService); refData.put("showSqlQuery", wiz.getShowSqlQuery()); refData.put("sqlQuery", reportQueryGenerator.getQueryString()); wiz.setShowSqlQuery(false); } refData.put("fieldGroups", lrfg); WebApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext()); refData.put("customFilters", reportCustomFilterHelper.getReportCustomFilterDefinitions(applicationContext, wiz)); List<ReportSegmentationType> reportSegmentationTypes = rdss.getReportSegmentationTypes(); refData.put("useReportAsSegmentation", wiz.getUseReportAsSegmentation()); wiz.setUseReportAsSegmentation(false); refData.put("segmentationTypeId", wiz.getReportSegmentationTypeId()); refData.put("segmentationTypeCount", reportSegmentationTypes.size()); refData.put("segmentationTypes", reportSegmentationTypes); List<ReportFilter> tempFilters = reportCustomFilterHelper.refreshReportCustomFilters(applicationContext, wiz); refData.put("selectedFilters", tempFilters); // Clear out the selected fields because some items do not post back correctly wiz.getReportFilters().clear(); refData.put("rowCount", wiz.getRowCount()); } if (page==4) { refData.put("executeSegmentation", wiz.getExecuteSegmentation()); wiz.setExecuteSegmentation(false); refData.put("useReportAsSegmentation", wiz.getUseReportAsSegmentation()); } // run a saved report if (page==7) { // wiz.setReportPath("/Reports/Clementine/" + wiz.getReportName().replace(" ", "_")); refData.put("reportPath", wiz.getReportPath()); } // running the report if (page==8) { // if there are no fields selected, select the defaults if (wiz.getReportSelectedFields().size() == 0) wiz.populateDefaultReportFields(); // SuppressWarnings("unused") DynamicReport dr = wiz.getReportGenerator().Generate(wiz, jdbcDataSource, reportFieldService, reportCustomFilterDefinitionService); //String query = dr.getQuery().getText(); // // execute the query and pass it to generateJasperPrint //Connection connection = jdbcDataSource.getConnection(); //Statement statement = connection.createStatement(); File tempFile = TempFileUtil.createTempFile("wiz", ".jrxml"); logger.info("Temp File: " + tempFile); DynamicJasperHelper.generateJRXML(dr,new ClassicLayoutManager(), wiz.getReportGenerator().getParams(), null, tempFile.getPath()); // // modify the jrxml ModifyReportJRXML reportXMLModifier = new ModifyReportJRXML(wiz, reportFieldService); //in the upgrade to DJ 3.0.4 they add a scriptletclass that jasperserver is not aware of so we remove as we //are not using it right now reportXMLModifier.removeDJDefaultScriptlet(tempFile.getPath()); // DJ adds a dataset that causes an error on the matrix reports so we need to remove it if (wiz.getReportType().compareToIgnoreCase("matrix") == 0) reportXMLModifier.removeCrossTabDataSubset(tempFile.getPath()); // add the summary info/totals to the report - DJ only allows one per column and we need to allow multiple so // we are altering the XML directly to add the summary calculations to the jasper report, // this also handles adding the calculations to the groups created by DJ. if (wiz.getReportType().compareToIgnoreCase("matrix") != 0 && wiz.HasSummaryFields() == true){ reportXMLModifier.AddGroupSummaryInfo(tempFile.getPath()); reportXMLModifier.AddReportSummaryInfo(tempFile.getPath()); } //move the chart to the header or footer of the report List<ReportChartSettings> rptChartSettings = wiz.getReportChartSettings(); Iterator itRptChartSettings = rptChartSettings.iterator(); while (itRptChartSettings.hasNext()){ ReportChartSettings rptChartSetting = (ReportChartSettings) itRptChartSettings.next(); String chartType = rptChartSetting.getChartType(); String chartLocation = rptChartSetting.getLocation(); reportXMLModifier.moveChartFromGroup(tempFile.getPath(), chartType, chartLocation); } // // save the report to the server wiz.getReportGenerator().put(ResourceDescriptor.TYPE_REPORTUNIT, tempFile.getName(), tempFile.getName(), tempFile.getName(), wiz.getTempFolderPath(), tempFile, wiz.getReportGenerator().getParams(), wiz.getDataSubSource().getJasperDatasourceName()); String tempReportPath = wiz.getTempFolderPath() + "/" + tempFile.getName(); refData.put("reportPath", tempReportPath); tempFile.delete(); } if (page == getPageIndexByName("ReportExecuteSegmentation") || page == getPageIndexByName("ReportSegmentationExecutionResults")) { boolean hasErrors = false; refData.put("wiz", wiz); if (!wiz.getUseReportAsSegmentation()) { hasErrors = true; errors.reject("error.segmentationnotselected", "This report was not selected to be used as a segmentation. To change this, go to the Report Criteria page and select the 'Use report as segmentation' check box. However, if the selected " + "secondary data source is not able to be used as a segmentation, that check box will not be available."); } if (wiz.getReportSegmentationTypeId() == 0) { hasErrors = true; errors.reject("error.segmentationtypenotselected", "No segmentation type was selected."); } if (!hasErrors) { try { if (page == getPageIndexByName("ReportExecuteSegmentation")) { int rowsAffected = reportSegmentationResultsService.executeSegmentation(wiz.getId()); ReportWizard tempWiz = reportWizardService.Find(wiz.getId()); wiz.setLastRunDateTime(tempWiz.getLastRunDateTime()); wiz.setLastRunByUserName(tempWiz.getLastRunByUserName()); wiz.setResultCount(tempWiz.getResultCount()); wiz.setExecutionTime(tempWiz.getExecutionTime()); } refData.put("segmentationType", reportSegmentationTypeService.find(wiz.getReportSegmentationTypeId()).getSegmentationType()); refData.put("rowsAffected", wiz.getResultCount()); refData.put("executionTime", wiz.getExecutionTime()); refData.put("lastRunDate", wiz.getLastRunDateTime()); refData.put("lastRunBy", wiz.getLastRunByUserName()); refData.put("hasErrors", false); } catch (Exception e) { e.printStackTrace(); refData.put("hasErrors", true); String message = "Error executing segmentation query for report ID " + wiz.getId().toString() + " (\"" + wiz.getReportName() + "\")" + System.getProperty("line.separator") + e.getMessage() + System.getProperty("line.separator") + wiz.getSegmentationQuery(); errors.reject("error.segmentationexecutionerror", message); } } else { refData.put("hasErrors", true); } } return refData; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "referenceData"
"@SuppressWarnings("unchecked") @Override protected Map referenceData(HttpServletRequest request, Object command, Errors errors, int page) throws Exception { ReportWizard wiz = (ReportWizard) command; Map refData = new HashMap(); refData.put("page",page); refData.put("maxpages", getPages().length-6); // 6 pages that are not actual steps // see if we went backwards if (wiz.getPreviousPage() > page) wiz.setPreviousPage(page -1); refData.put("previouspage", wiz.getPreviousPage()); // Load info passed to the wizard // if no user or password is in the request, see if the user has already been // populated on the wiz. Going to the second page and then back to the first could cause that. String userName = request.getParameter("username"); String password = request.getParameter("password"); if (userName == null || password == null) { userName = wiz.getUsername(); password = wiz.getPassword(); } else { GuruSessionData sessiondata = SessionHelper.getGuruSessionData(); sessiondata.setUsername(userName); sessiondata.setPassword(password); if (password.equals("/") || password.length() == 0) { UserDetails userDetails = userDetailsService.loadUserByUsername(userName); password = userDetails.getPassword(); } wiz.setUsername(userName); wiz.setPassword(password); } String reportUri = request.getParameter("reporturi"); if (reportUri != null && reportUri.length() > 0) { long reportId = -1; try { if (reportUri.contains("/THEGURU_")) reportId = Long.parseLong(reportUri.substring(reportUri.lastIndexOf("/THEGURU_") + 9)); if (reportId != -1) { ReportWizard tempWiz = reportWizardService.Find(reportId); if (tempWiz != null) { ReportWizardHelper.PopulateWizardFromSavedReport(wiz, tempWiz, page != 9); wiz.setPreviousDataSubSourceGroupId(wiz.getDataSubSourceGroupId()); wiz.setPreviousDataSubSourceId(wiz.getSubSourceId()); wiz.setReportPath(reportUri.substring(0, reportUri.indexOf("/THEGURU_"))); LoadWizardLookupTables(wiz); } else { errors.reject("1", "Unable to load report " + reportUri + ". You may continue to create a new report, or cancel to return to the report list."); } } } catch (Exception exception) { errors.reject("1", "Unable to load report " + reportUri + ". You may continue to create a new report, or cancel to return to the report list. " + exception.getMessage()); } } // If there is no user from the request or the wiz, send back to jasper server if (userName == null || password == null) { refData.put("userFound", false); } else { refData.put("userFound", true); refData.put("subSourceGroupId", wiz.getDataSubSourceGroupId()); refData.put("subSourceId", wiz.getSubSourceId()); wiz.getReportGenerator().setReportUserName(userName); wiz.getReportGenerator().setReportPassword(password); jasperServerService.setUserName(userName); jasperServerService.setPassword(password); //we want to allow the users logged in as a company to also see the default templates as well if (wiz.getReportTemplateList() != null) wiz.getReportTemplateList().clear(); if (!(wiz.getCompany().compareToIgnoreCase("default") == 0)) wiz.setReportTemplateList(jasperServerService.list("/Reports/Default/templates")); if (wiz.getReportTemplateList() != null) wiz.getReportTemplateList().addAll(jasperServerService.list("/Reports/" + wiz.getCompany() + "/templates")); else wiz.setReportTemplateList(jasperServerService.list("/Reports/" + wiz.getCompany() + "/templates")); if (wiz.getReportTemplateJRXML() == null || wiz.getReportTemplateJRXML().length() == 0) { if (wiz.getReportTemplateList().size() > 0) wiz.setReportTemplatePath(((ResourceDescriptor)wiz.getReportTemplateList().get(0)).getUriString()); else errors.reject("Invalid Repository","Invalid Repository. It appears your repository is not setup properly. Please contact your system administrator."); } } // // Report Source if (page == 0) { wiz.getReportGenerator().resetInputControls(); refData.put("previousSubSourceGroupId", wiz.getPreviousDataSubSourceGroupId()); refData.put("previousSubSourceId", wiz.getPreviousDataSubSourceId()); } // // Report Format if (page == 1) { String reportType = wiz.getReportType(); if (reportType.compareToIgnoreCase("summary") == 0) reportType = "tabular"; refData.put("reportType", reportType); } // // Report content selection if (page == 2) { String reportType = wiz.getReportType(); refData.put("reportType", reportType); Boolean reportUniqueRecords = wiz.getUniqueRecords(); refData.put("reportUniqueRecords", reportUniqueRecords); wiz.setUniqueRecords(false); ReportDataSubSource rdss = reportSubSourceService.find(wiz.getSubSourceId()); List<ReportFieldGroup> lrfg = reportFieldGroupService.readFieldGroupBySubSourceId(rdss.getId()); wiz.setFieldGroups(lrfg); refData.put("fieldGroups", wiz.getFieldGroups()); if (reportType.compareTo("tabular") == 0 || reportType.compareTo("summary") == 0) { List<ReportSelectedField> tempFields = new LinkedList<ReportSelectedField>(); tempFields.addAll(wiz.getReportSelectedFields()); refData.put("selectedFields", tempFields); // Clear out the selected fields because some items do not post back correctly wiz.getReportSelectedFields().clear(); refData.put("reportChartSettings", wiz.getReportChartSettings()); } else { List<ReportCrossTabColumn> tempColumns = new LinkedList<ReportCrossTabColumn>(); tempColumns.addAll(wiz.getReportCrossTabFields().getReportCrossTabColumns()); refData.put("matrixColumns", tempColumns); wiz.getReportCrossTabFields().getReportCrossTabColumns().clear(); List<ReportCrossTabRow> tempRows = new LinkedList<ReportCrossTabRow>(); tempRows.addAll(wiz.getReportCrossTabFields().getReportCrossTabRows()); refData.put("matrixRows", tempRows); wiz.getReportCrossTabFields().getReportCrossTabRows().clear(); List<ReportCrossTabMeasure> tempMeasures = new LinkedList<ReportCrossTabMeasure>(); tempMeasures.addAll(wiz.getReportCrossTabFields().getReportCrossTabMeasure()); refData.put("matrixMeasures", tempMeasures); wiz.getReportCrossTabFields().getReportCrossTabMeasure().clear(); } } // filter screen if(page==3) { ReportDataSubSource rdss = reportSubSourceService.find(wiz.getSubSourceId()); List<ReportFieldGroup> lrfg = reportFieldGroupService.readFieldGroupBySubSourceId(rdss.getId()); wiz.setFieldGroups(lrfg); if (wiz.getShowSqlQuery()) { ReportQueryGenerator reportQueryGenerator = new ReportQueryGenerator(wiz, reportFieldService, reportCustomFilterDefinitionService); refData.put("showSqlQuery", wiz.getShowSqlQuery()); refData.put("sqlQuery", reportQueryGenerator.getQueryString()); wiz.setShowSqlQuery(false); } refData.put("fieldGroups", lrfg); WebApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext()); refData.put("customFilters", reportCustomFilterHelper.getReportCustomFilterDefinitions(applicationContext, wiz)); List<ReportSegmentationType> reportSegmentationTypes = rdss.getReportSegmentationTypes(); refData.put("useReportAsSegmentation", wiz.getUseReportAsSegmentation()); wiz.setUseReportAsSegmentation(false); refData.put("segmentationTypeId", wiz.getReportSegmentationTypeId()); refData.put("segmentationTypeCount", reportSegmentationTypes.size()); refData.put("segmentationTypes", reportSegmentationTypes); List<ReportFilter> tempFilters = reportCustomFilterHelper.refreshReportCustomFilters(applicationContext, wiz); refData.put("selectedFilters", tempFilters); // Clear out the selected fields because some items do not post back correctly wiz.getReportFilters().clear(); refData.put("rowCount", wiz.getRowCount()); } if (page==4) { refData.put("executeSegmentation", wiz.getExecuteSegmentation()); wiz.setExecuteSegmentation(false); refData.put("useReportAsSegmentation", wiz.getUseReportAsSegmentation()); } // run a saved report if (page==7) { // wiz.setReportPath("/Reports/Clementine/" + wiz.getReportName().replace(" ", "_")); refData.put("reportPath", wiz.getReportPath()); } // running the report if (page==8) { // if there are no fields selected, select the defaults if (wiz.getReportSelectedFields().size() == 0) wiz.populateDefaultReportFields(); // SuppressWarnings("unused") DynamicReport dr = wiz.getReportGenerator().Generate(wiz, jdbcDataSource, reportFieldService, reportCustomFilterDefinitionService); //String query = dr.getQuery().getText(); // // execute the query and pass it to generateJasperPrint //Connection connection = jdbcDataSource.getConnection(); //Statement statement = connection.createStatement(); File tempFile = TempFileUtil.createTempFile("wiz", ".jrxml"); logger.info("Temp File: " + tempFile); DynamicJasperHelper.generateJRXML(dr,new ClassicLayoutManager(), wiz.getReportGenerator().getParams(), null, tempFile.getPath()); // // modify the jrxml ModifyReportJRXML reportXMLModifier = new ModifyReportJRXML(wiz, reportFieldService); //in the upgrade to DJ 3.0.4 they add a scriptletclass that jasperserver is not aware of so we remove as we //are not using it right now reportXMLModifier.removeDJDefaultScriptlet(tempFile.getPath()); // DJ adds a dataset that causes an error on the matrix reports so we need to remove it if (wiz.getReportType().compareToIgnoreCase("matrix") == 0) reportXMLModifier.removeCrossTabDataSubset(tempFile.getPath()); // add the summary info/totals to the report - DJ only allows one per column and we need to allow multiple so // we are altering the XML directly to add the summary calculations to the jasper report, // this also handles adding the calculations to the groups created by DJ. if (wiz.getReportType().compareToIgnoreCase("matrix") != 0 && wiz.HasSummaryFields() == true){ reportXMLModifier.AddGroupSummaryInfo(tempFile.getPath()); reportXMLModifier.AddReportSummaryInfo(tempFile.getPath()); } //move the chart to the header or footer of the report List<ReportChartSettings> rptChartSettings = wiz.getReportChartSettings(); Iterator itRptChartSettings = rptChartSettings.iterator(); while (itRptChartSettings.hasNext()){ ReportChartSettings rptChartSetting = (ReportChartSettings) itRptChartSettings.next(); String chartType = rptChartSetting.getChartType(); String chartLocation = rptChartSetting.getLocation(); reportXMLModifier.moveChartFromGroup(tempFile.getPath(), chartType, chartLocation); } // // save the report to the server wiz.getReportGenerator().put(ResourceDescriptor.TYPE_REPORTUNIT, tempFile.getName(), tempFile.getName(), tempFile.getName(), wiz.getTempFolderPath(), tempFile, wiz.getReportGenerator().getParams(), wiz.getDataSubSource().getJasperDatasourceName()); String tempReportPath = wiz.getTempFolderPath() + "/" + tempFile.getName(); refData.put("reportPath", tempReportPath); tempFile.delete(); } if (page == getPageIndexByName("ReportExecuteSegmentation") || page == getPageIndexByName("ReportSegmentationExecutionResults")) { boolean hasErrors = false; refData.put("wiz", wiz); <MASK>refData.put("segmentationType", reportSegmentationTypeService.find(wiz.getReportSegmentationTypeId()).getSegmentationType());</MASK> if (!wiz.getUseReportAsSegmentation()) { hasErrors = true; errors.reject("error.segmentationnotselected", "This report was not selected to be used as a segmentation. To change this, go to the Report Criteria page and select the 'Use report as segmentation' check box. However, if the selected " + "secondary data source is not able to be used as a segmentation, that check box will not be available."); } if (wiz.getReportSegmentationTypeId() == 0) { hasErrors = true; errors.reject("error.segmentationtypenotselected", "No segmentation type was selected."); } if (!hasErrors) { try { if (page == getPageIndexByName("ReportExecuteSegmentation")) { int rowsAffected = reportSegmentationResultsService.executeSegmentation(wiz.getId()); ReportWizard tempWiz = reportWizardService.Find(wiz.getId()); wiz.setLastRunDateTime(tempWiz.getLastRunDateTime()); wiz.setLastRunByUserName(tempWiz.getLastRunByUserName()); wiz.setResultCount(tempWiz.getResultCount()); wiz.setExecutionTime(tempWiz.getExecutionTime()); } refData.put("rowsAffected", wiz.getResultCount()); refData.put("executionTime", wiz.getExecutionTime()); refData.put("lastRunDate", wiz.getLastRunDateTime()); refData.put("lastRunBy", wiz.getLastRunByUserName()); refData.put("hasErrors", false); } catch (Exception e) { e.printStackTrace(); refData.put("hasErrors", true); String message = "Error executing segmentation query for report ID " + wiz.getId().toString() + " (\"" + wiz.getReportName() + "\")" + System.getProperty("line.separator") + e.getMessage() + System.getProperty("line.separator") + wiz.getSegmentationQuery(); errors.reject("error.segmentationexecutionerror", message); } } else { refData.put("hasErrors", true); } } return refData; }"
Inversion-Mutation
megadiff
"public static List<Row> getRangeSlice(RangeSliceCommand command, ConsistencyLevel consistency_level) throws IOException, UnavailableException, TimeoutException { if (logger.isDebugEnabled()) logger.debug(command.toString()); long startTime = System.nanoTime(); List<Row> rows; // now scan until we have enough results try { rows = new ArrayList<Row>(command.max_keys); List<AbstractBounds> ranges = getRestrictedRanges(command.range); for (AbstractBounds range : ranges) { List<InetAddress> liveEndpoints = StorageService.instance.getLiveNaturalEndpoints(command.keyspace, range.right); if (consistency_level == ConsistencyLevel.ONE && liveEndpoints.contains(FBUtilities.getLocalAddress())) { if (logger.isDebugEnabled()) logger.debug("local range slice"); ColumnFamilyStore cfs = Table.open(command.keyspace).getColumnFamilyStore(command.column_family); try { rows.addAll(cfs.getRangeSlice(command.super_column, range, command.max_keys, QueryFilter.getFilter(command.predicate, cfs.getComparator()))); } catch (ExecutionException e) { throw new RuntimeException(e.getCause()); } catch (InterruptedException e) { throw new AssertionError(e); } } else { DatabaseDescriptor.getEndpointSnitch().sortByProximity(FBUtilities.getLocalAddress(), liveEndpoints); RangeSliceCommand c2 = new RangeSliceCommand(command.keyspace, command.column_family, command.super_column, command.predicate, range, command.max_keys); // collect replies and resolve according to consistency level RangeSliceResponseResolver resolver = new RangeSliceResponseResolver(command.keyspace, liveEndpoints); AbstractReplicationStrategy rs = Table.open(command.keyspace).getReplicationStrategy(); ReadCallback<List<Row>> handler = getReadCallback(resolver, command.keyspace, consistency_level); // TODO bail early if live endpoints can't satisfy requested consistency level for (InetAddress endpoint : liveEndpoints) { Message message = c2.getMessage(); MessagingService.instance().sendRR(message, endpoint, handler); if (logger.isDebugEnabled()) logger.debug("reading " + c2 + " from " + message.getMessageId() + "@" + endpoint); } // TODO read repair on remaining replicas? // if we're done, great, otherwise, move to the next range try { if (logger.isDebugEnabled()) { for (Row row : handler.get()) { logger.debug("range slices read " + row.key); } } rows.addAll(handler.get()); } catch (DigestMismatchException e) { throw new AssertionError(e); // no digests in range slices yet } } if (rows.size() >= command.max_keys) break; } } finally { rangeStats.addNano(System.nanoTime() - startTime); } return rows.size() > command.max_keys ? rows.subList(0, command.max_keys) : rows; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getRangeSlice"
"public static List<Row> getRangeSlice(RangeSliceCommand command, ConsistencyLevel consistency_level) throws IOException, UnavailableException, TimeoutException { if (logger.isDebugEnabled()) logger.debug(command.toString()); long startTime = System.nanoTime(); List<Row> rows; // now scan until we have enough results try { rows = new ArrayList<Row>(command.max_keys); List<AbstractBounds> ranges = getRestrictedRanges(command.range); for (AbstractBounds range : ranges) { List<InetAddress> liveEndpoints = StorageService.instance.getLiveNaturalEndpoints(command.keyspace, range.right); if (consistency_level == ConsistencyLevel.ONE && liveEndpoints.contains(FBUtilities.getLocalAddress())) { if (logger.isDebugEnabled()) logger.debug("local range slice"); ColumnFamilyStore cfs = Table.open(command.keyspace).getColumnFamilyStore(command.column_family); try { rows.addAll(cfs.getRangeSlice(command.super_column, range, command.max_keys, QueryFilter.getFilter(command.predicate, cfs.getComparator()))); } catch (ExecutionException e) { throw new RuntimeException(e.getCause()); } catch (InterruptedException e) { throw new AssertionError(e); } } else { DatabaseDescriptor.getEndpointSnitch().sortByProximity(FBUtilities.getLocalAddress(), liveEndpoints); RangeSliceCommand c2 = new RangeSliceCommand(command.keyspace, command.column_family, command.super_column, command.predicate, range, command.max_keys); <MASK>Message message = c2.getMessage();</MASK> // collect replies and resolve according to consistency level RangeSliceResponseResolver resolver = new RangeSliceResponseResolver(command.keyspace, liveEndpoints); AbstractReplicationStrategy rs = Table.open(command.keyspace).getReplicationStrategy(); ReadCallback<List<Row>> handler = getReadCallback(resolver, command.keyspace, consistency_level); // TODO bail early if live endpoints can't satisfy requested consistency level for (InetAddress endpoint : liveEndpoints) { MessagingService.instance().sendRR(message, endpoint, handler); if (logger.isDebugEnabled()) logger.debug("reading " + c2 + " from " + message.getMessageId() + "@" + endpoint); } // TODO read repair on remaining replicas? // if we're done, great, otherwise, move to the next range try { if (logger.isDebugEnabled()) { for (Row row : handler.get()) { logger.debug("range slices read " + row.key); } } rows.addAll(handler.get()); } catch (DigestMismatchException e) { throw new AssertionError(e); // no digests in range slices yet } } if (rows.size() >= command.max_keys) break; } } finally { rangeStats.addNano(System.nanoTime() - startTime); } return rows.size() > command.max_keys ? rows.subList(0, command.max_keys) : rows; }"
Inversion-Mutation
megadiff
"protected Control createDialogArea(Composite parent) { Composite shell = new Composite(parent, SWT.NONE); GridData data = new GridData (GridData.FILL_BOTH); shell.setLayoutData(data); GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 2; gridLayout.makeColumnsEqualWidth = true; gridLayout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); gridLayout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); shell.setLayout (gridLayout); Composite comp = new Composite(shell, SWT.NULL); gridLayout = new GridLayout(); gridLayout.numColumns = 1; gridLayout.marginWidth = 0; gridLayout.marginHeight = 0; comp.setLayout(gridLayout); comp.setLayoutData(new GridData(GridData.FILL_BOTH)); Label cvsResourceTreeLabel = new Label(comp, SWT.NONE); cvsResourceTreeLabel.setText(CVSUIMessages.TagConfigurationDialog_5); //$NON-NLS-1$ data = new GridData(); data.horizontalSpan = 1; cvsResourceTreeLabel.setLayoutData(data); Tree tree = new Tree(comp, SWT.BORDER | SWT.MULTI); cvsResourceTree = new TreeViewer (tree); cvsResourceTree.setContentProvider(new RemoteContentProvider()); cvsResourceTree.setLabelProvider(new WorkbenchLabelProvider()); data = new GridData (GridData.FILL_BOTH); data.heightHint = 150; data.horizontalSpan = 1; cvsResourceTree.getTree().setLayoutData(data); cvsResourceTree.setSorter(new FileSorter()); cvsResourceTree.setInput(TagSourceResourceAdapter.getViewerInput(tagSource)); cvsResourceTree.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { updateShownTags(); updateEnablements(); } }); comp = new Composite(shell, SWT.NULL); gridLayout = new GridLayout(); gridLayout.numColumns = 1; gridLayout.marginWidth = 0; gridLayout.marginHeight = 0; comp.setLayout(gridLayout); comp.setLayoutData(new GridData(GridData.FILL_BOTH)); Label cvsTagTreeLabel = new Label(comp, SWT.NONE); cvsTagTreeLabel.setText(CVSUIMessages.TagConfigurationDialog_6); //$NON-NLS-1$ data = new GridData(); data.horizontalSpan = 1; cvsTagTreeLabel.setLayoutData(data); final Table table = new Table(comp, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION | SWT.CHECK); data = new GridData(GridData.FILL_BOTH); data.heightHint = 150; data.horizontalSpan = 1; table.setLayoutData(data); cvsTagTree = new CheckboxTableViewer(table); cvsTagTree.setContentProvider(new WorkbenchContentProvider()); cvsTagTree.setLabelProvider(new WorkbenchLabelProvider()); cvsTagTree.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { updateEnablements(); } }); Composite selectComp = new Composite(comp, SWT.NONE); GridLayout selectLayout = new GridLayout(2, true); selectLayout.marginHeight = selectLayout.marginWidth = 0; selectComp.setLayout(selectLayout); selectComp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Button selectAllButton = new Button(selectComp, SWT.PUSH); selectAllButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); selectAllButton.setText(CVSUIMessages.ReleaseCommentDialog_selectAll); //$NON-NLS-1$ selectAllButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { int nItems = table.getItemCount(); for (int j=0; j<nItems; j++) table.getItem(j).setChecked(true); } }); Button deselectAllButton = new Button(selectComp, SWT.PUSH); deselectAllButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); deselectAllButton.setText(CVSUIMessages.ReleaseCommentDialog_deselectAll); //$NON-NLS-1$ deselectAllButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { int nItems = table.getItemCount(); for (int j=0; j<nItems; j++) table.getItem(j).setChecked(false); } }); cvsTagTree.setSorter(new ViewerSorter() { public int compare(Viewer viewer, Object e1, Object e2) { if (!(e1 instanceof TagElement) || !(e2 instanceof TagElement)) return super.compare(viewer, e1, e2); CVSTag tag1 = ((TagElement)e1).getTag(); CVSTag tag2 = ((TagElement)e2).getTag(); int type1 = tag1.getType(); int type2 = tag2.getType(); if (type1 != type2) { return type1 - type2; } // Sort in reverse order so larger numbered versions are at the top return -tag1.compareTo(tag2); } }); Composite rememberedTags = new Composite(shell, SWT.NONE); data = new GridData (GridData.FILL_BOTH); data.horizontalSpan = 2; rememberedTags.setLayoutData(data); gridLayout = new GridLayout(); gridLayout.numColumns = 2; gridLayout.marginHeight = 0; gridLayout.marginWidth = 0; rememberedTags.setLayout (gridLayout); Label rememberedTagsLabel = new Label (rememberedTags, SWT.NONE); rememberedTagsLabel.setText (CVSUIMessages.TagConfigurationDialog_7); //$NON-NLS-1$ data = new GridData (); data.horizontalSpan = 2; rememberedTagsLabel.setLayoutData (data); tree = new Tree(rememberedTags, SWT.BORDER | SWT.MULTI); cvsDefinedTagsTree = new TreeViewer (tree); cvsDefinedTagsTree.setContentProvider(new WorkbenchContentProvider()); cvsDefinedTagsTree.setLabelProvider(new WorkbenchLabelProvider()); data = new GridData (GridData.FILL_BOTH); data.heightHint = 100; data.horizontalAlignment = GridData.FILL; data.grabExcessHorizontalSpace = true; cvsDefinedTagsTree.getTree().setLayoutData(data); cvsDefinedTagsRootElement = new TagSourceWorkbenchAdapter(wrappedTagSource, TagSourceWorkbenchAdapter.INCLUDE_BRANCHES | TagSourceWorkbenchAdapter.INCLUDE_VERSIONS |TagSourceWorkbenchAdapter.INCLUDE_DATES); cvsDefinedTagsTree.setInput(cvsDefinedTagsRootElement); cvsDefinedTagsTree.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { updateEnablements(); } }); cvsDefinedTagsTree.setSorter(new ProjectElementSorter()); Composite buttonComposite = new Composite(rememberedTags, SWT.NONE); data = new GridData (); data.verticalAlignment = GridData.BEGINNING; buttonComposite.setLayoutData(data); gridLayout = new GridLayout(); gridLayout.marginHeight = 0; gridLayout.marginWidth = 0; buttonComposite.setLayout (gridLayout); addSelectedTagsButton = new Button (buttonComposite, SWT.PUSH); addSelectedTagsButton.setText (CVSUIMessages.TagConfigurationDialog_8); //$NON-NLS-1$ data = getStandardButtonData(addSelectedTagsButton); data.horizontalAlignment = GridData.FILL; addSelectedTagsButton.setLayoutData(data); addSelectedTagsButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { rememberCheckedTags(); updateShownTags(); updateEnablements(); } }); Button addDatesButton = new Button(buttonComposite, SWT.PUSH); addDatesButton.setText(CVSUIMessages.TagConfigurationDialog_0); //$NON-NLS-1$ data = getStandardButtonData(addDatesButton); data.horizontalAlignment = GridData.FILL; addDatesButton.setLayoutData(data); addDatesButton.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event event){ CVSTag dateTag = NewDateTagAction.getDateTag(getShell(), tagSource.getLocation()); addDateTagsSelected(dateTag); updateShownTags(); updateEnablements(); } }); removeTagButton = new Button (buttonComposite, SWT.PUSH); removeTagButton.setText (CVSUIMessages.TagConfigurationDialog_9); //$NON-NLS-1$ data = getStandardButtonData(removeTagButton); data.horizontalAlignment = GridData.FILL; removeTagButton.setLayoutData(data); removeTagButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { deleteSelected(); updateShownTags(); updateEnablements(); } }); Button removeAllTags = new Button (buttonComposite, SWT.PUSH); removeAllTags.setText (CVSUIMessages.TagConfigurationDialog_10); //$NON-NLS-1$ data = getStandardButtonData(removeAllTags); data.horizontalAlignment = GridData.FILL; removeAllTags.setLayoutData(data); removeAllTags.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { removeAllKnownTags(); updateShownTags(); updateEnablements(); } }); if(allowSettingAutoRefreshFiles) { Label explanation = new Label(rememberedTags, SWT.WRAP); explanation.setText(CVSUIMessages.TagConfigurationDialog_11); //$NON-NLS-1$ data = new GridData (); data.horizontalSpan = 2; //data.widthHint = 300; explanation.setLayoutData(data); autoRefreshFileList = new org.eclipse.swt.widgets.List(rememberedTags, SWT.BORDER | SWT.MULTI); data = new GridData (); data.heightHint = 45; data.horizontalAlignment = GridData.FILL; data.grabExcessHorizontalSpace = true; autoRefreshFileList.setLayoutData(data); try { autoRefreshFileList.setItems(CVSUIPlugin.getPlugin().getRepositoryManager().getAutoRefreshFiles(getSingleFolder(tagSource, false))); } catch (CVSException e) { autoRefreshFileList.setItems(new String[0]); CVSUIPlugin.log(e); } autoRefreshFileList.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { updateEnablements(); } public void widgetDefaultSelected(SelectionEvent e) { updateEnablements(); } }); Composite buttonComposite2 = new Composite(rememberedTags, SWT.NONE); data = new GridData (); data.verticalAlignment = GridData.BEGINNING; buttonComposite2.setLayoutData(data); gridLayout = new GridLayout(); gridLayout.marginHeight = 0; gridLayout.marginWidth = 0; buttonComposite2.setLayout (gridLayout); addSelectedFilesButton = new Button (buttonComposite2, SWT.PUSH); addSelectedFilesButton.setText (CVSUIMessages.TagConfigurationDialog_12); //$NON-NLS-1$ data = getStandardButtonData(addSelectedFilesButton); data.horizontalAlignment = GridData.FILL; addSelectedFilesButton.setLayoutData(data); addSelectedFilesButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { addSelectionToAutoRefreshList(); } }); removeFileButton = new Button (buttonComposite2, SWT.PUSH); removeFileButton.setText (CVSUIMessages.TagConfigurationDialog_13); //$NON-NLS-1$ data = getStandardButtonData(removeFileButton); data.horizontalAlignment = GridData.FILL; removeFileButton.setLayoutData(data); removeFileButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { String[] selected = autoRefreshFileList.getSelection(); for (int i = 0; i < selected.length; i++) { autoRefreshFileList.remove(selected[i]); autoRefreshFileList.setFocus(); } } }); WorkbenchHelp.setHelp(autoRefreshFileList, IHelpContextIds.TAG_CONFIGURATION_REFRESHLIST); } Label seperator = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL); data = new GridData (GridData.FILL_BOTH); data.horizontalSpan = 2; seperator.setLayoutData(data); WorkbenchHelp.setHelp(shell, IHelpContextIds.TAG_CONFIGURATION_OVERVIEW); updateEnablements(); Dialog.applyDialogFont(parent); return shell; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createDialogArea"
"protected Control createDialogArea(Composite parent) { Composite shell = new Composite(parent, SWT.NONE); GridData data = new GridData (GridData.FILL_BOTH); shell.setLayoutData(data); GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 2; gridLayout.makeColumnsEqualWidth = true; gridLayout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); gridLayout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); shell.setLayout (gridLayout); Composite comp = new Composite(shell, SWT.NULL); gridLayout = new GridLayout(); gridLayout.numColumns = 1; gridLayout.marginWidth = 0; gridLayout.marginHeight = 0; comp.setLayout(gridLayout); comp.setLayoutData(new GridData(GridData.FILL_BOTH)); Label cvsResourceTreeLabel = new Label(comp, SWT.NONE); cvsResourceTreeLabel.setText(CVSUIMessages.TagConfigurationDialog_5); //$NON-NLS-1$ data = new GridData(); data.horizontalSpan = 1; cvsResourceTreeLabel.setLayoutData(data); Tree tree = new Tree(comp, SWT.BORDER | SWT.MULTI); cvsResourceTree = new TreeViewer (tree); cvsResourceTree.setContentProvider(new RemoteContentProvider()); cvsResourceTree.setLabelProvider(new WorkbenchLabelProvider()); data = new GridData (GridData.FILL_BOTH); data.heightHint = 150; data.horizontalSpan = 1; cvsResourceTree.getTree().setLayoutData(data); <MASK>cvsResourceTree.setInput(TagSourceResourceAdapter.getViewerInput(tagSource));</MASK> cvsResourceTree.setSorter(new FileSorter()); cvsResourceTree.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { updateShownTags(); updateEnablements(); } }); comp = new Composite(shell, SWT.NULL); gridLayout = new GridLayout(); gridLayout.numColumns = 1; gridLayout.marginWidth = 0; gridLayout.marginHeight = 0; comp.setLayout(gridLayout); comp.setLayoutData(new GridData(GridData.FILL_BOTH)); Label cvsTagTreeLabel = new Label(comp, SWT.NONE); cvsTagTreeLabel.setText(CVSUIMessages.TagConfigurationDialog_6); //$NON-NLS-1$ data = new GridData(); data.horizontalSpan = 1; cvsTagTreeLabel.setLayoutData(data); final Table table = new Table(comp, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION | SWT.CHECK); data = new GridData(GridData.FILL_BOTH); data.heightHint = 150; data.horizontalSpan = 1; table.setLayoutData(data); cvsTagTree = new CheckboxTableViewer(table); cvsTagTree.setContentProvider(new WorkbenchContentProvider()); cvsTagTree.setLabelProvider(new WorkbenchLabelProvider()); cvsTagTree.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { updateEnablements(); } }); Composite selectComp = new Composite(comp, SWT.NONE); GridLayout selectLayout = new GridLayout(2, true); selectLayout.marginHeight = selectLayout.marginWidth = 0; selectComp.setLayout(selectLayout); selectComp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Button selectAllButton = new Button(selectComp, SWT.PUSH); selectAllButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); selectAllButton.setText(CVSUIMessages.ReleaseCommentDialog_selectAll); //$NON-NLS-1$ selectAllButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { int nItems = table.getItemCount(); for (int j=0; j<nItems; j++) table.getItem(j).setChecked(true); } }); Button deselectAllButton = new Button(selectComp, SWT.PUSH); deselectAllButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); deselectAllButton.setText(CVSUIMessages.ReleaseCommentDialog_deselectAll); //$NON-NLS-1$ deselectAllButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { int nItems = table.getItemCount(); for (int j=0; j<nItems; j++) table.getItem(j).setChecked(false); } }); cvsTagTree.setSorter(new ViewerSorter() { public int compare(Viewer viewer, Object e1, Object e2) { if (!(e1 instanceof TagElement) || !(e2 instanceof TagElement)) return super.compare(viewer, e1, e2); CVSTag tag1 = ((TagElement)e1).getTag(); CVSTag tag2 = ((TagElement)e2).getTag(); int type1 = tag1.getType(); int type2 = tag2.getType(); if (type1 != type2) { return type1 - type2; } // Sort in reverse order so larger numbered versions are at the top return -tag1.compareTo(tag2); } }); Composite rememberedTags = new Composite(shell, SWT.NONE); data = new GridData (GridData.FILL_BOTH); data.horizontalSpan = 2; rememberedTags.setLayoutData(data); gridLayout = new GridLayout(); gridLayout.numColumns = 2; gridLayout.marginHeight = 0; gridLayout.marginWidth = 0; rememberedTags.setLayout (gridLayout); Label rememberedTagsLabel = new Label (rememberedTags, SWT.NONE); rememberedTagsLabel.setText (CVSUIMessages.TagConfigurationDialog_7); //$NON-NLS-1$ data = new GridData (); data.horizontalSpan = 2; rememberedTagsLabel.setLayoutData (data); tree = new Tree(rememberedTags, SWT.BORDER | SWT.MULTI); cvsDefinedTagsTree = new TreeViewer (tree); cvsDefinedTagsTree.setContentProvider(new WorkbenchContentProvider()); cvsDefinedTagsTree.setLabelProvider(new WorkbenchLabelProvider()); data = new GridData (GridData.FILL_BOTH); data.heightHint = 100; data.horizontalAlignment = GridData.FILL; data.grabExcessHorizontalSpace = true; cvsDefinedTagsTree.getTree().setLayoutData(data); cvsDefinedTagsRootElement = new TagSourceWorkbenchAdapter(wrappedTagSource, TagSourceWorkbenchAdapter.INCLUDE_BRANCHES | TagSourceWorkbenchAdapter.INCLUDE_VERSIONS |TagSourceWorkbenchAdapter.INCLUDE_DATES); cvsDefinedTagsTree.setInput(cvsDefinedTagsRootElement); cvsDefinedTagsTree.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { updateEnablements(); } }); cvsDefinedTagsTree.setSorter(new ProjectElementSorter()); Composite buttonComposite = new Composite(rememberedTags, SWT.NONE); data = new GridData (); data.verticalAlignment = GridData.BEGINNING; buttonComposite.setLayoutData(data); gridLayout = new GridLayout(); gridLayout.marginHeight = 0; gridLayout.marginWidth = 0; buttonComposite.setLayout (gridLayout); addSelectedTagsButton = new Button (buttonComposite, SWT.PUSH); addSelectedTagsButton.setText (CVSUIMessages.TagConfigurationDialog_8); //$NON-NLS-1$ data = getStandardButtonData(addSelectedTagsButton); data.horizontalAlignment = GridData.FILL; addSelectedTagsButton.setLayoutData(data); addSelectedTagsButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { rememberCheckedTags(); updateShownTags(); updateEnablements(); } }); Button addDatesButton = new Button(buttonComposite, SWT.PUSH); addDatesButton.setText(CVSUIMessages.TagConfigurationDialog_0); //$NON-NLS-1$ data = getStandardButtonData(addDatesButton); data.horizontalAlignment = GridData.FILL; addDatesButton.setLayoutData(data); addDatesButton.addListener(SWT.Selection, new Listener(){ public void handleEvent(Event event){ CVSTag dateTag = NewDateTagAction.getDateTag(getShell(), tagSource.getLocation()); addDateTagsSelected(dateTag); updateShownTags(); updateEnablements(); } }); removeTagButton = new Button (buttonComposite, SWT.PUSH); removeTagButton.setText (CVSUIMessages.TagConfigurationDialog_9); //$NON-NLS-1$ data = getStandardButtonData(removeTagButton); data.horizontalAlignment = GridData.FILL; removeTagButton.setLayoutData(data); removeTagButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { deleteSelected(); updateShownTags(); updateEnablements(); } }); Button removeAllTags = new Button (buttonComposite, SWT.PUSH); removeAllTags.setText (CVSUIMessages.TagConfigurationDialog_10); //$NON-NLS-1$ data = getStandardButtonData(removeAllTags); data.horizontalAlignment = GridData.FILL; removeAllTags.setLayoutData(data); removeAllTags.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { removeAllKnownTags(); updateShownTags(); updateEnablements(); } }); if(allowSettingAutoRefreshFiles) { Label explanation = new Label(rememberedTags, SWT.WRAP); explanation.setText(CVSUIMessages.TagConfigurationDialog_11); //$NON-NLS-1$ data = new GridData (); data.horizontalSpan = 2; //data.widthHint = 300; explanation.setLayoutData(data); autoRefreshFileList = new org.eclipse.swt.widgets.List(rememberedTags, SWT.BORDER | SWT.MULTI); data = new GridData (); data.heightHint = 45; data.horizontalAlignment = GridData.FILL; data.grabExcessHorizontalSpace = true; autoRefreshFileList.setLayoutData(data); try { autoRefreshFileList.setItems(CVSUIPlugin.getPlugin().getRepositoryManager().getAutoRefreshFiles(getSingleFolder(tagSource, false))); } catch (CVSException e) { autoRefreshFileList.setItems(new String[0]); CVSUIPlugin.log(e); } autoRefreshFileList.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { updateEnablements(); } public void widgetDefaultSelected(SelectionEvent e) { updateEnablements(); } }); Composite buttonComposite2 = new Composite(rememberedTags, SWT.NONE); data = new GridData (); data.verticalAlignment = GridData.BEGINNING; buttonComposite2.setLayoutData(data); gridLayout = new GridLayout(); gridLayout.marginHeight = 0; gridLayout.marginWidth = 0; buttonComposite2.setLayout (gridLayout); addSelectedFilesButton = new Button (buttonComposite2, SWT.PUSH); addSelectedFilesButton.setText (CVSUIMessages.TagConfigurationDialog_12); //$NON-NLS-1$ data = getStandardButtonData(addSelectedFilesButton); data.horizontalAlignment = GridData.FILL; addSelectedFilesButton.setLayoutData(data); addSelectedFilesButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { addSelectionToAutoRefreshList(); } }); removeFileButton = new Button (buttonComposite2, SWT.PUSH); removeFileButton.setText (CVSUIMessages.TagConfigurationDialog_13); //$NON-NLS-1$ data = getStandardButtonData(removeFileButton); data.horizontalAlignment = GridData.FILL; removeFileButton.setLayoutData(data); removeFileButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { String[] selected = autoRefreshFileList.getSelection(); for (int i = 0; i < selected.length; i++) { autoRefreshFileList.remove(selected[i]); autoRefreshFileList.setFocus(); } } }); WorkbenchHelp.setHelp(autoRefreshFileList, IHelpContextIds.TAG_CONFIGURATION_REFRESHLIST); } Label seperator = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL); data = new GridData (GridData.FILL_BOTH); data.horizontalSpan = 2; seperator.setLayoutData(data); WorkbenchHelp.setHelp(shell, IHelpContextIds.TAG_CONFIGURATION_OVERVIEW); updateEnablements(); Dialog.applyDialogFont(parent); return shell; }"
Inversion-Mutation
megadiff
"public void sqlResultSetAvailable(ResultSet rs, SQLExecutionInfo info, IDataSetUpdateableTableModel model) { _cancelPanel.setStatusLabel("Building output..."); rsds = new ResultSetDataSet(); SessionProperties props = getSession().getProperties(); ResultSetMetaDataDataSet rsmdds = null; try { // rsds.setResultSet(rs, props.getLargeResultSetObjectInfo()); rsmdds = new ResultSetMetaDataDataSet(rs); rsds.setResultSet(rs); } catch (DataSetException ex) { getSession().getMessageHandler().showMessage(ex); return; } addResultsTab(info, rsds, rsmdds, _cancelPanel, model); rsds = null; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "sqlResultSetAvailable"
"public void sqlResultSetAvailable(ResultSet rs, SQLExecutionInfo info, IDataSetUpdateableTableModel model) { _cancelPanel.setStatusLabel("Building output..."); rsds = new ResultSetDataSet(); SessionProperties props = getSession().getProperties(); ResultSetMetaDataDataSet rsmdds = null; try { // rsds.setResultSet(rs, props.getLargeResultSetObjectInfo()); rsds.setResultSet(rs); <MASK>rsmdds = new ResultSetMetaDataDataSet(rs);</MASK> } catch (DataSetException ex) { getSession().getMessageHandler().showMessage(ex); return; } addResultsTab(info, rsds, rsmdds, _cancelPanel, model); rsds = null; }"
Inversion-Mutation
megadiff
"public boolean service(WebloungeRequest request, WebloungeResponse response) { WebUrl url = request.getUrl(); Site site = request.getSite(); String path = url.getPath(); String fileName = null; // Get hold of the content repository ContentRepository contentRepository = site.getContentRepository(); if (contentRepository == null) { logger.warn("No content repository found for site '{}'", site); return false; } else if (contentRepository.isIndexing()) { logger.debug("Content repository of site '{}' is currently being indexed", site); DispatchUtils.sendServiceUnavailable(request, response); return true; } // Check if the request uri matches the special uri for images. If so, try // to extract the id from the last part of the path. If not, check if there // is an image with the current path. ResourceURI imageURI = null; ImageResource imageResource = null; try { String id = null; String imagePath = null; if (path.startsWith(URI_PREFIX)) { String uriSuffix = StringUtils.chomp(path.substring(URI_PREFIX.length()), "/"); uriSuffix = URLDecoder.decode(uriSuffix, "utf-8"); // Check whether we are looking at a uuid or a url path if (uriSuffix.length() == UUID_LENGTH) { id = uriSuffix; } else if (uriSuffix.length() >= UUID_LENGTH) { int lastSeparator = uriSuffix.indexOf('/'); if (lastSeparator == UUID_LENGTH && uriSuffix.indexOf('/', lastSeparator + 1) < 0) { id = uriSuffix.substring(0, lastSeparator); fileName = uriSuffix.substring(lastSeparator + 1); } else { imagePath = uriSuffix; fileName = FilenameUtils.getName(imagePath); } } else { imagePath = "/" + uriSuffix; fileName = FilenameUtils.getName(imagePath); } } else { imagePath = path; fileName = FilenameUtils.getName(imagePath); } // Try to load the resource imageURI = new ImageResourceURIImpl(site, imagePath, id); imageResource = contentRepository.get(imageURI); if (imageResource == null) { logger.debug("No image found at {}", imageURI); return false; } } catch (ContentRepositoryException e) { logger.error("Error loading image from {}: {}", contentRepository, e.getMessage()); DispatchUtils.sendInternalError(request, response); return true; } catch (UnsupportedEncodingException e) { logger.error("Error decoding image url {} using utf-8: {}", path, e.getMessage()); DispatchUtils.sendInternalError(request, response); return true; } // Agree to serve the image logger.debug("Image handler agrees to handle {}", path); // Check the request method. Only GET is supported right now. String requestMethod = request.getMethod().toUpperCase(); if ("OPTIONS".equals(requestMethod)) { String verbs = "OPTIONS,GET"; logger.trace("Answering options request to {} with {}", url, verbs); response.setHeader("Allow", verbs); response.setContentLength(0); return true; } else if (!"GET".equals(requestMethod)) { logger.debug("Image request handler does not support {} requests", requestMethod); DispatchUtils.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, request, response); return true; } // Is it published? // TODO: Fix this. imageResource.isPublished() currently returns false, // as both from and to dates are null (see PublishingCtx) // if (!imageResource.isPublished()) { // logger.debug("Access to unpublished image {}", imageURI); // DispatchUtils.sendNotFound(request, response); // return true; // } // Can the image be accessed by the current user? User user = request.getUser(); try { // TODO: Check permission // PagePermission p = new PagePermission(page, user); // AccessController.checkPermission(p); } catch (SecurityException e) { logger.warn("Access to image {} denied for user {}", imageURI, user); DispatchUtils.sendAccessDenied(request, response); return true; } // Determine the response language by filename Language language = null; if (StringUtils.isNotBlank(fileName)) { for (ImageContent c : imageResource.contents()) { if (c.getFilename().equalsIgnoreCase(fileName)) { if (language != null) { logger.debug("Unable to determine language from ambiguous filename"); language = LanguageUtils.getPreferredContentLanguage(imageResource, request, site); break; } language = c.getLanguage(); } } if (language == null) language = LanguageUtils.getPreferredContentLanguage(imageResource, request, site); } else { language = LanguageUtils.getPreferredContentLanguage(imageResource, request, site); } // If the filename did not lead to a language, apply language resolution if (language == null) { logger.warn("Image {} does not exist in any supported language", imageURI); DispatchUtils.sendNotFound(request, response); return true; } // Find an image preview generator ImagePreviewGenerator imagePreviewGenerator = null; synchronized (previewGenerators) { for (ImagePreviewGenerator generator : previewGenerators) { if (generator.supports(imageResource)) { imagePreviewGenerator = generator; break; } } } // If we did not find a preview generator, we need to let go if (imagePreviewGenerator == null) { logger.debug("Unable to generate image previews since no suitable image preview generator is available"); DispatchUtils.sendServiceUnavailable(request, response); return true; } // Extract the image style and scale the image ImageStyle style = null; String styleId = StringUtils.trimToNull(request.getParameter(OPT_IMAGE_STYLE)); if (styleId != null) { style = ImageStyleUtils.findStyle(styleId, site); if (style == null) { DispatchUtils.sendBadRequest("Image style '" + styleId + "' not found", request, response); return true; } } File scaledImageFile = null; // Check the modified headers long revalidationTime = MS_PER_DAY; long expirationDate = System.currentTimeMillis() + revalidationTime; if (style == null || ImageScalingMode.None.equals(style.getScalingMode())) { if (!ResourceUtils.hasChanged(request, imageResource, language)) { logger.debug("Image {} was not modified", imageURI); response.setDateHeader("Expires", expirationDate); DispatchUtils.sendNotModified(request, response); return true; } } else { scaledImageFile = ImageStyleUtils.getScaledFile(imageResource, language, style); if (!ResourceUtils.hasChanged(request, scaledImageFile)) { logger.debug("Scaled image {} was not modified", imageURI); response.setDateHeader("Expires", expirationDate); DispatchUtils.sendNotModified(request, response); return true; } } // Load the image contents from the repository ImageContent imageContents = imageResource.getContent(language); // Add mime type header String contentType = imageContents.getMimetype(); if (contentType == null) contentType = MediaType.APPLICATION_OCTET_STREAM; // Set the content type String characterEncoding = response.getCharacterEncoding(); if (StringUtils.isNotBlank(characterEncoding)) response.setContentType(contentType + "; charset=" + characterEncoding.toLowerCase()); else response.setContentType(contentType); // Browser caches and proxies are allowed to keep a copy response.setHeader("Cache-Control", "public, max-age=" + revalidationTime); // Set Expires header response.setDateHeader("Expires", expirationDate); // Get the mime type final String mimetype = imageContents.getMimetype(); final String format = mimetype.substring(mimetype.indexOf("/") + 1); // Determine the resource's modification date long resourceLastModified = ResourceUtils.getModificationDate(imageResource, language).getTime(); // When there is no scaling required, just return the original if (style == null || ImageScalingMode.None.equals(style.getScalingMode())) { // Add last modified header response.setDateHeader("Last-Modified", resourceLastModified); // Add ETag header response.setHeader("ETag", ResourceUtils.getETagValue(imageResource)); // Load the input stream from the repository InputStream imageInputStream = null; try { imageInputStream = contentRepository.getContent(imageURI, language); } catch (Throwable t) { logger.error("Error loading {} image '{}' from {}: {}", new Object[] { language, imageResource, contentRepository, t.getMessage() }); logger.error(t.getMessage(), t); IOUtils.closeQuietly(imageInputStream); return false; } // Write the image back to the client try { response.setHeader("Content-Length", Long.toString(imageContents.getSize())); response.setHeader("Content-Disposition", "inline; filename=" + imageContents.getFilename()); IOUtils.copy(imageInputStream, response.getOutputStream()); response.getOutputStream().flush(); } catch (EOFException e) { logger.debug("Error writing image '{}' back to client: connection closed by client", imageResource); return true; } catch (IOException e) { logger.error("Error writing {} image '{}' back to client: {}", new Object[] { language, imageResource, e.getMessage() }); } finally { IOUtils.closeQuietly(imageInputStream); } return true; } // Write the scaled file back to the response (and create it, if needed) boolean scalingFailed = false; boolean scaledImageExists = scaledImageFile.isFile(); boolean scaledImageIsOutdated = scaledImageFile.lastModified() < resourceLastModified; // Do we need to render the image? if (!scaledImageExists || scaledImageIsOutdated) { boolean firstOne = true; // Make sure the preview is not already being generated synchronized (previews) { while (previews.contains(scaledImageFile)) { logger.debug("Preview at {} is being created, waiting for it to be generated", scaledImageFile); firstOne = false; try { previews.wait(); } catch (InterruptedException e) { DispatchUtils.sendServiceUnavailable(request, response); return true; } } // Make sure others are waiting until we are done if (firstOne) { previews.add(scaledImageFile); } } // Create the preview if this is the first request if (firstOne) { logger.info("Creating preview of {} with style '{}' at {}", new String[] { imageResource.getIdentifier(), style.getIdentifier(), scaledImageFile.getAbsolutePath() }); InputStream imageInputStream = null; FileOutputStream fos = null; try { imageInputStream = contentRepository.getContent(imageURI, language); // Remove the original image FileUtils.deleteQuietly(scaledImageFile); // Create a work file File imageDirectory = scaledImageFile.getParentFile(); String workFileName = "." + UUID.randomUUID() + "-" + scaledImageFile.getName(); FileUtils.forceMkdir(imageDirectory); File workImageFile = new File(imageDirectory, workFileName); // Create the scaled image fos = new FileOutputStream(workImageFile); logger.debug("Creating scaled image '{}' at {}", imageResource, scaledImageFile); imagePreviewGenerator.createPreview(imageResource, environment, language, style, format, imageInputStream, fos); // Move the work image in place try { FileUtils.moveFile(workImageFile, scaledImageFile); } catch (IOException e) { logger.warn("Concurrent creation of preview {} resolved by copy instead of rename", scaledImageFile.getAbsolutePath()); FileUtils.copyFile(workImageFile, scaledImageFile); FileUtils.deleteQuietly(workImageFile); } finally { scaledImageFile.setLastModified(new Date().getTime()); } // Make sure preview generation was successful scalingFailed = !scaledImageFile.isFile() || scaledImageFile.length() == 0; } catch (ContentRepositoryException e) { logger.error("Unable to load image {}: {}", new Object[] { imageURI, e.getMessage(), e }); scalingFailed = true; DispatchUtils.sendInternalError(request, response); return true; } catch (IOException e) { logger.error("Error sending image '{}' to the client: {}", imageURI, e.getMessage()); DispatchUtils.sendInternalError(request, response); scalingFailed = true; return true; } catch (Throwable t) { logger.error("Error creating scaled image '{}': {}", imageURI, t.getMessage()); DispatchUtils.sendInternalError(request, response); scalingFailed = true; return true; } finally { IOUtils.closeQuietly(imageInputStream); IOUtils.closeQuietly(fos); if (scalingFailed && scaledImageFile != null) { File f = scaledImageFile; FileUtils.deleteQuietly(scaledImageFile); f = scaledImageFile.getParentFile(); while (f != null && f.isDirectory() && f.listFiles().length == 0) { FileUtils.deleteQuietly(f); f = f.getParentFile(); } } synchronized (previews) { previews.remove(scaledImageFile); previews.notifyAll(); } } } // Make sure whoever was in charge of creating the preview, was // successful else { scaledImageExists = scaledImageFile.isFile(); scaledImageIsOutdated = scaledImageFile.lastModified() < resourceLastModified; if (!scaledImageExists || scaledImageIsOutdated) { logger.debug("Apparently, preview rendering for {} failed", scaledImageFile.getAbsolutePath()); DispatchUtils.sendServiceUnavailable(request, response); return true; } } } // Write the image back to the client InputStream imageInputStream = null; try { // Add last modified header response.setDateHeader("Last-Modified", scaledImageFile.lastModified()); response.setHeader("ETag", ResourceUtils.getETagValue(scaledImageFile.lastModified())); response.setHeader("Content-Disposition", "inline; filename=" + scaledImageFile.getName()); response.setHeader("Content-Length", Long.toString(scaledImageFile.length())); imageInputStream = new FileInputStream(scaledImageFile); IOUtils.copy(imageInputStream, response.getOutputStream()); response.getOutputStream().flush(); return true; } catch (EOFException e) { logger.debug("Error writing image '{}' back to client: connection closed by client", imageResource); return true; } catch (IOException e) { logger.error("Error sending image '{}' to the client: {}", imageURI, e.getMessage()); DispatchUtils.sendInternalError(request, response); return true; } catch (Throwable t) { logger.error("Error creating scaled image '{}': {}", imageURI, t.getMessage()); DispatchUtils.sendInternalError(request, response); return true; } finally { IOUtils.closeQuietly(imageInputStream); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "service"
"public boolean service(WebloungeRequest request, WebloungeResponse response) { WebUrl url = request.getUrl(); Site site = request.getSite(); String path = url.getPath(); String fileName = null; // Get hold of the content repository ContentRepository contentRepository = site.getContentRepository(); if (contentRepository == null) { logger.warn("No content repository found for site '{}'", site); return false; } else if (contentRepository.isIndexing()) { logger.debug("Content repository of site '{}' is currently being indexed", site); DispatchUtils.sendServiceUnavailable(request, response); return true; } // Check if the request uri matches the special uri for images. If so, try // to extract the id from the last part of the path. If not, check if there // is an image with the current path. ResourceURI imageURI = null; ImageResource imageResource = null; try { String id = null; String imagePath = null; if (path.startsWith(URI_PREFIX)) { String uriSuffix = StringUtils.chomp(path.substring(URI_PREFIX.length()), "/"); uriSuffix = URLDecoder.decode(uriSuffix, "utf-8"); // Check whether we are looking at a uuid or a url path if (uriSuffix.length() == UUID_LENGTH) { id = uriSuffix; } else if (uriSuffix.length() >= UUID_LENGTH) { int lastSeparator = uriSuffix.indexOf('/'); if (lastSeparator == UUID_LENGTH && uriSuffix.indexOf('/', lastSeparator + 1) < 0) { id = uriSuffix.substring(0, lastSeparator); fileName = uriSuffix.substring(lastSeparator + 1); } else { imagePath = uriSuffix; fileName = FilenameUtils.getName(imagePath); } } else { imagePath = "/" + uriSuffix; fileName = FilenameUtils.getName(imagePath); } } else { imagePath = path; fileName = FilenameUtils.getName(imagePath); } // Try to load the resource imageURI = new ImageResourceURIImpl(site, imagePath, id); imageResource = contentRepository.get(imageURI); if (imageResource == null) { logger.debug("No image found at {}", imageURI); return false; } } catch (ContentRepositoryException e) { logger.error("Error loading image from {}: {}", contentRepository, e.getMessage()); DispatchUtils.sendInternalError(request, response); return true; } catch (UnsupportedEncodingException e) { logger.error("Error decoding image url {} using utf-8: {}", path, e.getMessage()); DispatchUtils.sendInternalError(request, response); return true; } // Agree to serve the image logger.debug("Image handler agrees to handle {}", path); // Check the request method. Only GET is supported right now. String requestMethod = request.getMethod().toUpperCase(); if ("OPTIONS".equals(requestMethod)) { String verbs = "OPTIONS,GET"; logger.trace("Answering options request to {} with {}", url, verbs); response.setHeader("Allow", verbs); response.setContentLength(0); return true; } else if (!"GET".equals(requestMethod)) { logger.debug("Image request handler does not support {} requests", requestMethod); DispatchUtils.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, request, response); return true; } // Is it published? // TODO: Fix this. imageResource.isPublished() currently returns false, // as both from and to dates are null (see PublishingCtx) // if (!imageResource.isPublished()) { // logger.debug("Access to unpublished image {}", imageURI); // DispatchUtils.sendNotFound(request, response); // return true; // } // Can the image be accessed by the current user? User user = request.getUser(); try { // TODO: Check permission // PagePermission p = new PagePermission(page, user); // AccessController.checkPermission(p); } catch (SecurityException e) { logger.warn("Access to image {} denied for user {}", imageURI, user); DispatchUtils.sendAccessDenied(request, response); return true; } // Determine the response language by filename Language language = null; if (StringUtils.isNotBlank(fileName)) { for (ImageContent c : imageResource.contents()) { if (c.getFilename().equalsIgnoreCase(fileName)) { if (language != null) { logger.debug("Unable to determine language from ambiguous filename"); language = LanguageUtils.getPreferredContentLanguage(imageResource, request, site); break; } language = c.getLanguage(); } } if (language == null) language = LanguageUtils.getPreferredContentLanguage(imageResource, request, site); } else { language = LanguageUtils.getPreferredContentLanguage(imageResource, request, site); } // If the filename did not lead to a language, apply language resolution if (language == null) { logger.warn("Image {} does not exist in any supported language", imageURI); DispatchUtils.sendNotFound(request, response); return true; } // Find an image preview generator ImagePreviewGenerator imagePreviewGenerator = null; synchronized (previewGenerators) { for (ImagePreviewGenerator generator : previewGenerators) { if (generator.supports(imageResource)) { imagePreviewGenerator = generator; break; } } } // If we did not find a preview generator, we need to let go if (imagePreviewGenerator == null) { logger.debug("Unable to generate image previews since no suitable image preview generator is available"); DispatchUtils.sendServiceUnavailable(request, response); return true; } // Extract the image style and scale the image ImageStyle style = null; String styleId = StringUtils.trimToNull(request.getParameter(OPT_IMAGE_STYLE)); if (styleId != null) { style = ImageStyleUtils.findStyle(styleId, site); if (style == null) { DispatchUtils.sendBadRequest("Image style '" + styleId + "' not found", request, response); return true; } } File scaledImageFile = null; // Check the modified headers long revalidationTime = MS_PER_DAY; long expirationDate = System.currentTimeMillis() + revalidationTime; if (style == null || ImageScalingMode.None.equals(style.getScalingMode())) { if (!ResourceUtils.hasChanged(request, imageResource, language)) { logger.debug("Image {} was not modified", imageURI); response.setDateHeader("Expires", expirationDate); DispatchUtils.sendNotModified(request, response); return true; } } else { scaledImageFile = ImageStyleUtils.getScaledFile(imageResource, language, style); if (!ResourceUtils.hasChanged(request, scaledImageFile)) { logger.debug("Scaled image {} was not modified", imageURI); response.setDateHeader("Expires", expirationDate); DispatchUtils.sendNotModified(request, response); return true; } } // Load the image contents from the repository ImageContent imageContents = imageResource.getContent(language); // Add mime type header String contentType = imageContents.getMimetype(); if (contentType == null) contentType = MediaType.APPLICATION_OCTET_STREAM; // Set the content type String characterEncoding = response.getCharacterEncoding(); if (StringUtils.isNotBlank(characterEncoding)) response.setContentType(contentType + "; charset=" + characterEncoding.toLowerCase()); else response.setContentType(contentType); // Browser caches and proxies are allowed to keep a copy response.setHeader("Cache-Control", "public, max-age=" + revalidationTime); // Set Expires header response.setDateHeader("Expires", expirationDate); // Get the mime type final String mimetype = imageContents.getMimetype(); final String format = mimetype.substring(mimetype.indexOf("/") + 1); // Determine the resource's modification date long resourceLastModified = ResourceUtils.getModificationDate(imageResource, language).getTime(); // When there is no scaling required, just return the original if (style == null || ImageScalingMode.None.equals(style.getScalingMode())) { // Add last modified header response.setDateHeader("Last-Modified", resourceLastModified); // Add ETag header response.setHeader("ETag", ResourceUtils.getETagValue(imageResource)); // Load the input stream from the repository InputStream imageInputStream = null; try { imageInputStream = contentRepository.getContent(imageURI, language); } catch (Throwable t) { logger.error("Error loading {} image '{}' from {}: {}", new Object[] { language, imageResource, contentRepository, t.getMessage() }); logger.error(t.getMessage(), t); IOUtils.closeQuietly(imageInputStream); return false; } // Write the image back to the client try { response.setHeader("Content-Length", Long.toString(imageContents.getSize())); response.setHeader("Content-Disposition", "inline; filename=" + imageContents.getFilename()); IOUtils.copy(imageInputStream, response.getOutputStream()); response.getOutputStream().flush(); } catch (EOFException e) { logger.debug("Error writing image '{}' back to client: connection closed by client", imageResource); return true; } catch (IOException e) { logger.error("Error writing {} image '{}' back to client: {}", new Object[] { language, imageResource, e.getMessage() }); <MASK>} finally {</MASK> IOUtils.closeQuietly(imageInputStream); } return true; } // Write the scaled file back to the response (and create it, if needed) boolean scalingFailed = false; boolean scaledImageExists = scaledImageFile.isFile(); boolean scaledImageIsOutdated = scaledImageFile.lastModified() < resourceLastModified; // Do we need to render the image? if (!scaledImageExists || scaledImageIsOutdated) { boolean firstOne = true; // Make sure the preview is not already being generated synchronized (previews) { while (previews.contains(scaledImageFile)) { logger.debug("Preview at {} is being created, waiting for it to be generated", scaledImageFile); firstOne = false; try { previews.wait(); } catch (InterruptedException e) { DispatchUtils.sendServiceUnavailable(request, response); return true; } } // Make sure others are waiting until we are done if (firstOne) { previews.add(scaledImageFile); } } // Create the preview if this is the first request if (firstOne) { logger.info("Creating preview of {} with style '{}' at {}", new String[] { imageResource.getIdentifier(), style.getIdentifier(), scaledImageFile.getAbsolutePath() }); InputStream imageInputStream = null; FileOutputStream fos = null; try { imageInputStream = contentRepository.getContent(imageURI, language); // Remove the original image FileUtils.deleteQuietly(scaledImageFile); // Create a work file File imageDirectory = scaledImageFile.getParentFile(); String workFileName = "." + UUID.randomUUID() + "-" + scaledImageFile.getName(); FileUtils.forceMkdir(imageDirectory); File workImageFile = new File(imageDirectory, workFileName); // Create the scaled image fos = new FileOutputStream(workImageFile); logger.debug("Creating scaled image '{}' at {}", imageResource, scaledImageFile); imagePreviewGenerator.createPreview(imageResource, environment, language, style, format, imageInputStream, fos); // Move the work image in place try { FileUtils.moveFile(workImageFile, scaledImageFile); } catch (IOException e) { logger.warn("Concurrent creation of preview {} resolved by copy instead of rename", scaledImageFile.getAbsolutePath()); FileUtils.copyFile(workImageFile, scaledImageFile); <MASK>} finally {</MASK> FileUtils.deleteQuietly(workImageFile); scaledImageFile.setLastModified(new Date().getTime()); } // Make sure preview generation was successful scalingFailed = !scaledImageFile.isFile() || scaledImageFile.length() == 0; } catch (ContentRepositoryException e) { logger.error("Unable to load image {}: {}", new Object[] { imageURI, e.getMessage(), e }); scalingFailed = true; DispatchUtils.sendInternalError(request, response); return true; } catch (IOException e) { logger.error("Error sending image '{}' to the client: {}", imageURI, e.getMessage()); DispatchUtils.sendInternalError(request, response); scalingFailed = true; return true; } catch (Throwable t) { logger.error("Error creating scaled image '{}': {}", imageURI, t.getMessage()); DispatchUtils.sendInternalError(request, response); scalingFailed = true; return true; <MASK>} finally {</MASK> IOUtils.closeQuietly(imageInputStream); IOUtils.closeQuietly(fos); if (scalingFailed && scaledImageFile != null) { File f = scaledImageFile; FileUtils.deleteQuietly(scaledImageFile); f = scaledImageFile.getParentFile(); while (f != null && f.isDirectory() && f.listFiles().length == 0) { FileUtils.deleteQuietly(f); f = f.getParentFile(); } } synchronized (previews) { previews.remove(scaledImageFile); previews.notifyAll(); } } } // Make sure whoever was in charge of creating the preview, was // successful else { scaledImageExists = scaledImageFile.isFile(); scaledImageIsOutdated = scaledImageFile.lastModified() < resourceLastModified; if (!scaledImageExists || scaledImageIsOutdated) { logger.debug("Apparently, preview rendering for {} failed", scaledImageFile.getAbsolutePath()); DispatchUtils.sendServiceUnavailable(request, response); return true; } } } // Write the image back to the client InputStream imageInputStream = null; try { // Add last modified header response.setDateHeader("Last-Modified", scaledImageFile.lastModified()); response.setHeader("ETag", ResourceUtils.getETagValue(scaledImageFile.lastModified())); response.setHeader("Content-Disposition", "inline; filename=" + scaledImageFile.getName()); response.setHeader("Content-Length", Long.toString(scaledImageFile.length())); imageInputStream = new FileInputStream(scaledImageFile); IOUtils.copy(imageInputStream, response.getOutputStream()); response.getOutputStream().flush(); return true; } catch (EOFException e) { logger.debug("Error writing image '{}' back to client: connection closed by client", imageResource); return true; } catch (IOException e) { logger.error("Error sending image '{}' to the client: {}", imageURI, e.getMessage()); DispatchUtils.sendInternalError(request, response); return true; } catch (Throwable t) { logger.error("Error creating scaled image '{}': {}", imageURI, t.getMessage()); DispatchUtils.sendInternalError(request, response); return true; <MASK>} finally {</MASK> IOUtils.closeQuietly(imageInputStream); } }"
Inversion-Mutation
megadiff
"private void doreport(Report r) throws IOException { if(!status.goterror(r.t)) return; URLConnection c = errordest.openConnection(); status.connecting(); c.setDoOutput(true); c.addRequestProperty("Content-Type", "application/x-java-error"); c.connect(); ObjectOutputStream o = new ObjectOutputStream(c.getOutputStream()); status.sending(); o.writeObject(r); o.close(); InputStream i = c.getInputStream(); byte[] buf = new byte[1024]; while(i.read(buf) >= 0); i.close(); status.done(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doreport"
"private void doreport(Report r) throws IOException { if(!status.goterror(r.t)) return; URLConnection c = errordest.openConnection(); status.connecting(); c.setDoOutput(true); c.addRequestProperty("Content-Type", "application/x-java-error"); c.connect(); ObjectOutputStream o = new ObjectOutputStream(c.getOutputStream()); o.writeObject(r); o.close(); <MASK>status.sending();</MASK> InputStream i = c.getInputStream(); byte[] buf = new byte[1024]; while(i.read(buf) >= 0); i.close(); status.done(); }"
Inversion-Mutation
megadiff
"@Override public void removeChildPage(final String name) { WikiPage childPage = getChildPage(name); if (childPage instanceof FileSystemPage) { versionsController.delete((FileSystemPage) childPage); super.removeChildPage(name); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "removeChildPage"
"@Override public void removeChildPage(final String name) { <MASK>super.removeChildPage(name);</MASK> WikiPage childPage = getChildPage(name); if (childPage instanceof FileSystemPage) { versionsController.delete((FileSystemPage) childPage); } }"
Inversion-Mutation
megadiff
"public LocalResourceSaveableComparison(ICompareInput input, CompareEditorInput editorInput, ITypedElement fileElement) { this.input = input; this.editorInput = editorInput; this.fileElement = fileElement; initializeContentChangeListeners(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "LocalResourceSaveableComparison"
"public LocalResourceSaveableComparison(ICompareInput input, CompareEditorInput editorInput, ITypedElement fileElement) { this.input = input; this.editorInput = editorInput; <MASK>initializeContentChangeListeners();</MASK> this.fileElement = fileElement; }"
Inversion-Mutation
megadiff
"@SuppressLint("NewApi") @Override public boolean onPrepareOptionsMenu(Menu menu) { menu.clear(); ImageButton overflowMenuButton = (ImageButton) findViewById(R.id.imageButton_overflowmenu); MenuItem searchActionItem = menu.add(0, R.id.collectionactivity_search_menu_button, 0, "Search"); searchActionItem.setIcon(R.drawable.ic_action_search).setActionView(R.layout.collapsible_edittext).setOnActionExpandListener( this).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) searchActionItem.setVisible(true); if (mSearchModeEnabled) { searchActionItem.setVisible(true); if (!searchActionItem.isActionViewExpanded()) searchActionItem.expandActionView(); View actionView = searchActionItem.getActionView(); EditText searchEditText = (EditText) actionView.findViewById(R.id.search_edittext); if (searchEditText != null) searchEditText.requestFocus(); if (!mSoftKeyboardShown) { mSoftKeyboardShown = true; InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(searchEditText, 0); } if (mSearchFragment != null && searchEditText != null) { mSearchFragment.setSearchText(searchEditText); searchEditText.setText(mSearchFragment.getSearchString()); searchEditText.setSelection(searchEditText.getText().length()); } } else { mSoftKeyboardShown = false; if (getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) { getSupportActionBar().setDisplayShowCustomEnabled(false); searchActionItem.setVisible(false); } searchActionItem.collapseActionView(); } if ((android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH && ViewConfiguration.get( getApplicationContext()).hasPermanentMenuKey()) || android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) { overflowMenuButton.setVisibility(ImageButton.GONE); overflowMenuButton.setClickable(false); overflowMenuButton.setLayoutParams(new LayoutParams(0, 0)); } refreshNowPlayingBarVisibility(); if (mPlaybackService != null) setNowPlayingInfo(mPlaybackService.getCurrentTrack()); mMenu = menu; return super.onPrepareOptionsMenu(menu); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onPrepareOptionsMenu"
"@SuppressLint("NewApi") @Override public boolean onPrepareOptionsMenu(Menu menu) { menu.clear(); ImageButton overflowMenuButton = (ImageButton) findViewById(R.id.imageButton_overflowmenu); MenuItem searchActionItem = menu.add(0, R.id.collectionactivity_search_menu_button, 0, "Search"); searchActionItem.setIcon(R.drawable.ic_action_search).setActionView(R.layout.collapsible_edittext).setOnActionExpandListener( this).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) searchActionItem.setVisible(true); if (mSearchModeEnabled) { searchActionItem.setVisible(true); if (!searchActionItem.isActionViewExpanded()) searchActionItem.expandActionView(); View actionView = searchActionItem.getActionView(); EditText searchEditText = (EditText) actionView.findViewById(R.id.search_edittext); if (searchEditText != null) searchEditText.requestFocus(); if (!mSoftKeyboardShown) { mSoftKeyboardShown = true; InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(searchEditText, 0); } if (mSearchFragment != null && searchEditText != null) { mSearchFragment.setSearchText(searchEditText); searchEditText.setText(mSearchFragment.getSearchString()); searchEditText.setSelection(searchEditText.getText().length()); } } else { mSoftKeyboardShown = false; if (getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) { getSupportActionBar().setDisplayShowCustomEnabled(false); searchActionItem.setVisible(false); } searchActionItem.collapseActionView(); } if ((android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH && ViewConfiguration.get( getApplicationContext()).hasPermanentMenuKey()) || android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) { overflowMenuButton.setVisibility(ImageButton.GONE); overflowMenuButton.setClickable(false); overflowMenuButton.setLayoutParams(new LayoutParams(0, 0)); } if (mPlaybackService != null) setNowPlayingInfo(mPlaybackService.getCurrentTrack()); <MASK>refreshNowPlayingBarVisibility();</MASK> mMenu = menu; return super.onPrepareOptionsMenu(menu); }"
Inversion-Mutation
megadiff
"public boolean takeTime(int q) { resetBorder(Color.red); time -= q; int sleep =q; int delayFactor = delayModel.getNumber().intValue(); try { if(time <= 0) { sleep += time; Thread.sleep((time+q)*delayFactor); } else { Thread.sleep(q*delayFactor); resetBorder(Color.green); } } catch (InterruptedException e) { // Reset colour when sleep is interrupted, // probably because the stop button was pressed resetBorder(Color.green); } textArea.append("Process "+id+" executed for: "+sleep+"ms\n"); if(time <= 0) { resetBorder(Color.black); textArea.append("Process "+id+" finished\n"); time = 0; } timeLbl.setText(""+time); if(time == 0) return true; else return false; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "takeTime"
"public boolean takeTime(int q) { resetBorder(Color.red); time -= q; int sleep =q; int delayFactor = delayModel.getNumber().intValue(); try { if(time <= 0) { sleep += time; Thread.sleep((time+q)*delayFactor); <MASK>resetBorder(Color.black);</MASK> } else { Thread.sleep(q*delayFactor); resetBorder(Color.green); } } catch (InterruptedException e) { // Reset colour when sleep is interrupted, // probably because the stop button was pressed resetBorder(Color.green); } textArea.append("Process "+id+" executed for: "+sleep+"ms\n"); if(time <= 0) { textArea.append("Process "+id+" finished\n"); time = 0; } timeLbl.setText(""+time); if(time == 0) return true; else return false; }"
Inversion-Mutation
megadiff
"@Override protected void onStop() { if (mRoomId != null) { GServiceClient.getInstance().leaveRoom(10000); } gHelper.onStop(); super.onStop(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onStop"
"@Override protected void onStop() { <MASK>super.onStop();</MASK> if (mRoomId != null) { GServiceClient.getInstance().leaveRoom(10000); } gHelper.onStop(); }"
Inversion-Mutation
megadiff
"@Override public void playbackFinished(Track track) { // move to next song try { MusicMachineApplication.playlist.removeTrack(track); this.playTrack(MusicMachineApplication.playlist.popTrack()); addWinnersToPlaylist(); } catch (MusicMachinePlaylist.PlaylistEmptyException e) { System.out.println("No more tracks to play, waiting for new ones"); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "playbackFinished"
"@Override public void playbackFinished(Track track) { <MASK>addWinnersToPlaylist();</MASK> // move to next song try { MusicMachineApplication.playlist.removeTrack(track); this.playTrack(MusicMachineApplication.playlist.popTrack()); } catch (MusicMachinePlaylist.PlaylistEmptyException e) { System.out.println("No more tracks to play, waiting for new ones"); } }"
Inversion-Mutation
megadiff
"public static List<Element> handlePropertyName(String[] propertyNames, ServiceContext context, boolean freq, int maxRecords, String cswServiceSpecificConstraint, LuceneConfig luceneConfig) throws Exception { List<Element> domainValuesList = null; if(Log.isDebugEnabled(Geonet.CSW)) Log.debug(Geonet.CSW,"Handling property names '"+Arrays.toString(propertyNames)+"' with max records of "+maxRecords); for (int i=0; i < propertyNames.length; i++) { if (i==0) domainValuesList = new ArrayList<Element>(); // Initialize list of values element. Element listOfValues = null; // Generate DomainValues element Element domainValues = new Element("DomainValues", Csw.NAMESPACE_CSW); // FIXME what should be the type ??? domainValues.setAttribute("type", "csw:Record"); String property = propertyNames[i].trim(); // Set propertyName in any case. Element pn = new Element("PropertyName", Csw.NAMESPACE_CSW); domainValues.addContent(pn.setText(property)); GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME); SearchManager sm = gc.getSearchmanager(); IndexAndTaxonomy indexAndTaxonomy= sm.getNewIndexReader(null); try { GeonetworkMultiReader reader = indexAndTaxonomy.indexReader; BooleanQuery groupsQuery = (BooleanQuery) CatalogSearcher.getGroupsQuery(context); BooleanQuery query = null; // Apply CSW service specific constraint if (StringUtils.isNotEmpty(cswServiceSpecificConstraint)) { Query constraintQuery = CatalogSearcher.getCswServiceSpecificConstraintQuery(cswServiceSpecificConstraint, luceneConfig); query = new BooleanQuery(); BooleanClause.Occur occur = LuceneUtils .convertRequiredAndProhibitedToOccur(true, false); query.add(groupsQuery, occur); query.add(constraintQuery, occur); } else { query = groupsQuery; } List<Pair<String, Boolean>> sortFields = Collections.singletonList(Pair.read(Geonet.SearchResult.SortBy.RELEVANCE, true)); Sort sort = LuceneSearcher.makeSort(sortFields, context.getLanguage(), false); CachingWrapperFilter filter = null; Pair<TopDocs,Element> searchResults = LuceneSearcher.doSearchAndMakeSummary( maxRecords, 0, maxRecords, context.getLanguage(), null, reader, query, filter, sort, null, false, false, false, false // Scoring is useless for GetDomain operation ); TopDocs hits = searchResults.one(); try { // Get mapped lucene field in CSW configuration String indexField = CatalogConfiguration.getFieldMapping().get( property.toLowerCase()); if (indexField != null) property = indexField; // check if params asked is in the index using getFieldNames ? @SuppressWarnings("resource") FieldInfos fi = new SlowCompositeReaderWrapper(reader).getFieldInfos(); if (fi.fieldInfo(property) == null) continue; boolean isRange = false; if (CatalogConfiguration.getGetRecordsRangeFields().contains( property)) isRange = true; if (isRange) listOfValues = new Element("RangeOfValues", Csw.NAMESPACE_CSW); else listOfValues = new Element("ListOfValues", Csw.NAMESPACE_CSW); Set<String> fields = new HashSet<String>(); fields.add(property); fields.add("_isTemplate"); // parse each document in the index String[] fieldValues; SortedSet<String> sortedValues = new TreeSet<String>(); ObjectKeyIntOpenHashMap duplicateValues = new ObjectKeyIntOpenHashMap(); for (int j = 0; j < hits.scoreDocs.length; j++) { DocumentStoredFieldVisitor selector = new DocumentStoredFieldVisitor(fields); reader.document(hits.scoreDocs[j].doc, selector); Document doc = selector.getDocument(); // Skip templates and subTemplates String[] isTemplate = doc.getValues("_isTemplate"); if (isTemplate[0] != null && !isTemplate[0].equals("n")) continue; // Get doc values for specified property fieldValues = doc.getValues(property); if (fieldValues == null) continue; addtoSortedSet(sortedValues, fieldValues, duplicateValues); } SummaryComparator valuesComparator = new SummaryComparator(SortOption.FREQUENCY, Type.STRING, context.getLanguage(), null); TreeSet<SummaryComparator.SummaryElement> sortedValuesFrequency = new TreeSet<SummaryComparator.SummaryElement>(valuesComparator); ObjectKeyIntMapIterator entries = duplicateValues.entries(); while(entries.hasNext()) { entries.next(); sortedValuesFrequency.add(new SummaryComparator.SummaryElement(entries)); } if (freq) return createValuesByFrequency(sortedValuesFrequency); else listOfValues.addContent(createValuesElement(sortedValues, isRange)); } finally { // any children means that the catalog was unable to determine // anything about the specified parameter if (listOfValues!= null && listOfValues.getChildren().size() != 0) domainValues.addContent(listOfValues); // Add current DomainValues to the list domainValuesList.add(domainValues); } } finally { sm.releaseIndexReader(indexAndTaxonomy); } } return domainValuesList; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handlePropertyName"
"public static List<Element> handlePropertyName(String[] propertyNames, ServiceContext context, boolean freq, int maxRecords, String cswServiceSpecificConstraint, LuceneConfig luceneConfig) throws Exception { List<Element> domainValuesList = null; if(Log.isDebugEnabled(Geonet.CSW)) Log.debug(Geonet.CSW,"Handling property names '"+Arrays.toString(propertyNames)+"' with max records of "+maxRecords); for (int i=0; i < propertyNames.length; i++) { if (i==0) domainValuesList = new ArrayList<Element>(); // Initialize list of values element. Element listOfValues = null; // Generate DomainValues element Element domainValues = new Element("DomainValues", Csw.NAMESPACE_CSW); // FIXME what should be the type ??? domainValues.setAttribute("type", "csw:Record"); String property = propertyNames[i].trim(); // Set propertyName in any case. Element pn = new Element("PropertyName", Csw.NAMESPACE_CSW); domainValues.addContent(pn.setText(property)); GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME); SearchManager sm = gc.getSearchmanager(); IndexAndTaxonomy indexAndTaxonomy= sm.getNewIndexReader(null); try { GeonetworkMultiReader reader = indexAndTaxonomy.indexReader; BooleanQuery groupsQuery = (BooleanQuery) CatalogSearcher.getGroupsQuery(context); BooleanQuery query = null; // Apply CSW service specific constraint if (StringUtils.isNotEmpty(cswServiceSpecificConstraint)) { Query constraintQuery = CatalogSearcher.getCswServiceSpecificConstraintQuery(cswServiceSpecificConstraint, luceneConfig); query = new BooleanQuery(); BooleanClause.Occur occur = LuceneUtils .convertRequiredAndProhibitedToOccur(true, false); query.add(groupsQuery, occur); query.add(constraintQuery, occur); } else { query = groupsQuery; } List<Pair<String, Boolean>> sortFields = Collections.singletonList(Pair.read(Geonet.SearchResult.SortBy.RELEVANCE, true)); Sort sort = LuceneSearcher.makeSort(sortFields, context.getLanguage(), false); CachingWrapperFilter filter = null; Pair<TopDocs,Element> searchResults = LuceneSearcher.doSearchAndMakeSummary( maxRecords, 0, maxRecords, context.getLanguage(), null, reader, query, filter, sort, null, false, false, false, false // Scoring is useless for GetDomain operation ); TopDocs hits = searchResults.one(); try { // Get mapped lucene field in CSW configuration String indexField = CatalogConfiguration.getFieldMapping().get( property.toLowerCase()); if (indexField != null) property = indexField; // check if params asked is in the index using getFieldNames ? @SuppressWarnings("resource") FieldInfos fi = new SlowCompositeReaderWrapper(reader).getFieldInfos(); if (fi.fieldInfo(property) == null) continue; boolean isRange = false; if (CatalogConfiguration.getGetRecordsRangeFields().contains( property)) isRange = true; if (isRange) listOfValues = new Element("RangeOfValues", Csw.NAMESPACE_CSW); else listOfValues = new Element("ListOfValues", Csw.NAMESPACE_CSW); Set<String> fields = new HashSet<String>(); fields.add(property); fields.add("_isTemplate"); // parse each document in the index String[] fieldValues; SortedSet<String> sortedValues = new TreeSet<String>(); ObjectKeyIntOpenHashMap duplicateValues = new ObjectKeyIntOpenHashMap(); for (int j = 0; j < hits.scoreDocs.length; j++) { DocumentStoredFieldVisitor selector = new DocumentStoredFieldVisitor(fields); reader.document(hits.scoreDocs[j].doc, selector); Document doc = selector.getDocument(); // Skip templates and subTemplates String[] isTemplate = doc.getValues("_isTemplate"); if (isTemplate[0] != null && !isTemplate[0].equals("n")) continue; // Get doc values for specified property fieldValues = doc.getValues(property); if (fieldValues == null) continue; addtoSortedSet(sortedValues, fieldValues, duplicateValues); } SummaryComparator valuesComparator = new SummaryComparator(SortOption.FREQUENCY, Type.STRING, context.getLanguage(), null); TreeSet<SummaryComparator.SummaryElement> sortedValuesFrequency = new TreeSet<SummaryComparator.SummaryElement>(valuesComparator); ObjectKeyIntMapIterator entries = duplicateValues.entries(); while(entries.hasNext()) { sortedValuesFrequency.add(new SummaryComparator.SummaryElement(entries)); <MASK>entries.next();</MASK> } if (freq) return createValuesByFrequency(sortedValuesFrequency); else listOfValues.addContent(createValuesElement(sortedValues, isRange)); } finally { // any children means that the catalog was unable to determine // anything about the specified parameter if (listOfValues!= null && listOfValues.getChildren().size() != 0) domainValues.addContent(listOfValues); // Add current DomainValues to the list domainValuesList.add(domainValues); } } finally { sm.releaseIndexReader(indexAndTaxonomy); } } return domainValuesList; }"
Inversion-Mutation
megadiff
"private void purgeBuildOutputDirectory( String path ) { File buildOutputDir = new File( path ); FileFilter filter = DirectoryFileFilter.DIRECTORY; File[] projectsDir = buildOutputDir.listFiles( filter ); for ( File projectDir : projectsDir ) { File[] buildsDir = projectDir.listFiles( filter ); if ( retentionCount > buildsDir.length ) { continue; } int countToPurge = buildsDir.length - retentionCount; Calendar olderThanThisDate = Calendar.getInstance( DateUtils.UTC_TIME_ZONE ); olderThanThisDate.add( Calendar.DATE, -daysOlder ); Arrays.sort( buildsDir, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR ); for ( File buildDir : buildsDir ) { if ( countToPurge <= 0 ) { break; } if ( buildDir.lastModified() < olderThanThisDate.getTimeInMillis() ) { try { log.info( ContinuumPurgeConstants.PURGE_DIR_CONTENTS + " - " + buildDir.getName() ); FileUtils.deleteDirectory( buildDir ); File logFile = new File( buildDir.getAbsoluteFile() + ".log.txt" ); if ( logFile.exists() ) { log.info( ContinuumPurgeConstants.PURGE_FILE + " - " + logFile.getName() ); logFile.delete(); } countToPurge--; } catch ( IOException e ) { // swallow? } } } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "purgeBuildOutputDirectory"
"private void purgeBuildOutputDirectory( String path ) { File buildOutputDir = new File( path ); FileFilter filter = DirectoryFileFilter.DIRECTORY; File[] projectsDir = buildOutputDir.listFiles( filter ); for ( File projectDir : projectsDir ) { File[] buildsDir = projectDir.listFiles( filter ); if ( retentionCount > buildsDir.length ) { continue; } int countToPurge = buildsDir.length - retentionCount; Calendar olderThanThisDate = Calendar.getInstance( DateUtils.UTC_TIME_ZONE ); olderThanThisDate.add( Calendar.DATE, -daysOlder ); Arrays.sort( buildsDir, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR ); for ( File buildDir : buildsDir ) { if ( countToPurge <= 0 ) { break; } if ( buildDir.lastModified() < olderThanThisDate.getTimeInMillis() ) { try { <MASK>FileUtils.deleteDirectory( buildDir );</MASK> log.info( ContinuumPurgeConstants.PURGE_DIR_CONTENTS + " - " + buildDir.getName() ); File logFile = new File( buildDir.getAbsoluteFile() + ".log.txt" ); if ( logFile.exists() ) { log.info( ContinuumPurgeConstants.PURGE_FILE + " - " + logFile.getName() ); logFile.delete(); } countToPurge--; } catch ( IOException e ) { // swallow? } } } } }"
Inversion-Mutation
megadiff
"public void destroy() { // the following doesn't fully clean up (maybe because of Java3D?) WindowManager wm = (WindowManager) getManager(WindowManager.class); wm.hideWindows(); setVisible(false); wm.disposeWindows(); StateManager sm = (StateManager) getManager(StateManager.class); sm.destroy(); instanceServer.stop(); dispose(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "destroy"
"public void destroy() { // the following doesn't fully clean up (maybe because of Java3D?) WindowManager wm = (WindowManager) getManager(WindowManager.class); wm.hideWindows(); <MASK>wm.disposeWindows();</MASK> setVisible(false); StateManager sm = (StateManager) getManager(StateManager.class); sm.destroy(); instanceServer.stop(); dispose(); }"
Inversion-Mutation
megadiff
"@Override public void start() throws QTasteException { if (getStatus() != ProcessStatus.READY_TO_START) { throw new QTasteException("Invalide state. Cannot start a non initialized process."); } new Thread(new Runnable() { @Override public void run() { try { mStatus = ProcessStatus.RUNNING; mCurrentProcess = mBuilder.start(); mStdLogs = new InputStreamWriter(mCurrentProcess.getInputStream()); new Thread(mStdLogs).start(); mErrLogs = new InputStreamWriter(mCurrentProcess.getErrorStream()); new Thread(mErrLogs).start(); mReturnCode = mCurrentProcess.waitFor(); } catch (IOException e) { LOGGER.error(e.getMessage(), e); } catch (InterruptedException e) { LOGGER.error(e.getMessage(), e); } finally { mStatus = ProcessStatus.STOPPED; } } }).start(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "start"
"@Override public void start() throws QTasteException { if (getStatus() != ProcessStatus.READY_TO_START) { throw new QTasteException("Invalide state. Cannot start a non initialized process."); } new Thread(new Runnable() { @Override public void run() { try { <MASK>mCurrentProcess = mBuilder.start();</MASK> mStatus = ProcessStatus.RUNNING; mStdLogs = new InputStreamWriter(mCurrentProcess.getInputStream()); new Thread(mStdLogs).start(); mErrLogs = new InputStreamWriter(mCurrentProcess.getErrorStream()); new Thread(mErrLogs).start(); mReturnCode = mCurrentProcess.waitFor(); } catch (IOException e) { LOGGER.error(e.getMessage(), e); } catch (InterruptedException e) { LOGGER.error(e.getMessage(), e); } finally { mStatus = ProcessStatus.STOPPED; } } }).start(); }"
Inversion-Mutation
megadiff
"@Override public void run() { try { mStatus = ProcessStatus.RUNNING; mCurrentProcess = mBuilder.start(); mStdLogs = new InputStreamWriter(mCurrentProcess.getInputStream()); new Thread(mStdLogs).start(); mErrLogs = new InputStreamWriter(mCurrentProcess.getErrorStream()); new Thread(mErrLogs).start(); mReturnCode = mCurrentProcess.waitFor(); } catch (IOException e) { LOGGER.error(e.getMessage(), e); } catch (InterruptedException e) { LOGGER.error(e.getMessage(), e); } finally { mStatus = ProcessStatus.STOPPED; } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"@Override public void run() { try { <MASK>mCurrentProcess = mBuilder.start();</MASK> mStatus = ProcessStatus.RUNNING; mStdLogs = new InputStreamWriter(mCurrentProcess.getInputStream()); new Thread(mStdLogs).start(); mErrLogs = new InputStreamWriter(mCurrentProcess.getErrorStream()); new Thread(mErrLogs).start(); mReturnCode = mCurrentProcess.waitFor(); } catch (IOException e) { LOGGER.error(e.getMessage(), e); } catch (InterruptedException e) { LOGGER.error(e.getMessage(), e); } finally { mStatus = ProcessStatus.STOPPED; } }"
Inversion-Mutation
megadiff
"@Override public void writeReady() { if (writes.size() == 0) { return; } try { ByteBuffer buffer = writes.get(0); if (!buffer.hasRemaining()) { writes.remove(0); } else { handler.get().getChannel().write(buffer); handler.get().selectForWrite(); } } catch (IOException e) { throw new IllegalStateException(e); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "writeReady"
"@Override public void writeReady() { if (writes.size() == 0) { return; } try { ByteBuffer buffer = writes.get(0); <MASK>handler.get().getChannel().write(buffer);</MASK> if (!buffer.hasRemaining()) { writes.remove(0); } else { handler.get().selectForWrite(); } } catch (IOException e) { throw new IllegalStateException(e); } }"
Inversion-Mutation
megadiff
"@Override protected byte[] getContent(ExchangeSession.Message message) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream contentInputStream; try { try { try { contentInputStream = getContentInputStream(message.messageUrl, restoreHostName); } catch (UnknownHostException e) { // failover for misconfigured Exchange server, replace host name in url restoreHostName = true; contentInputStream = getContentInputStream(message.messageUrl, restoreHostName); } } catch (HttpNotFoundException e) { LOGGER.debug("Message not found at: " + message.messageUrl + ", retrying with permanenturl"); contentInputStream = getContentInputStream(message.permanentUrl, restoreHostName); } try { IOUtil.write(contentInputStream, baos); } finally { contentInputStream.close(); } } catch (LoginTimeoutException e) { // throw error on expired session LOGGER.warn(e.getMessage()); throw e; } catch (IOException e) { LOGGER.warn("Broken message at: " + message.messageUrl + " permanentUrl: " + message.permanentUrl + ", trying to rebuild from properties"); try { DavPropertyNameSet messageProperties = new DavPropertyNameSet(); messageProperties.add(Field.getPropertyName("contentclass")); messageProperties.add(Field.getPropertyName("message-id")); messageProperties.add(Field.getPropertyName("from")); messageProperties.add(Field.getPropertyName("to")); messageProperties.add(Field.getPropertyName("cc")); messageProperties.add(Field.getPropertyName("subject")); messageProperties.add(Field.getPropertyName("htmldescription")); messageProperties.add(Field.getPropertyName("body")); PropFindMethod propFindMethod = new PropFindMethod(URIUtil.encodePath(message.permanentUrl), messageProperties, 0); DavGatewayHttpClientFacade.executeMethod(httpClient, propFindMethod); MultiStatus responses = propFindMethod.getResponseBodyAsMultiStatus(); if (responses.getResponses().length > 0) { MimeMessage mimeMessage = new MimeMessage((Session) null); DavPropertySet properties = responses.getResponses()[0].getProperties(HttpStatus.SC_OK); String propertyValue = getPropertyIfExists(properties, "contentclass"); if (propertyValue != null) { mimeMessage.addHeader("Content-class", propertyValue); } propertyValue = getPropertyIfExists(properties, "from"); if (propertyValue != null) { mimeMessage.addHeader("From", propertyValue); } propertyValue = getPropertyIfExists(properties, "to"); if (propertyValue != null) { mimeMessage.addHeader("To", propertyValue); } propertyValue = getPropertyIfExists(properties, "cc"); if (propertyValue != null) { mimeMessage.addHeader("Cc", propertyValue); } propertyValue = getPropertyIfExists(properties, "subject"); if (propertyValue != null) { mimeMessage.setSubject(propertyValue); } propertyValue = getPropertyIfExists(properties, "htmldescription"); if (propertyValue != null) { mimeMessage.setContent(propertyValue, "text/html"); } else { propertyValue = getPropertyIfExists(properties, "body"); if (propertyValue != null) { mimeMessage.setText(propertyValue); } } mimeMessage.writeTo(baos); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Rebuilt message content: " + new String(baos.toByteArray())); } } catch (IOException e2) { LOGGER.warn(e2); } catch (DavException e2) { LOGGER.warn(e2); } catch (MessagingException e2) { LOGGER.warn(e2); } // other exception if (baos.size() == 0 && Settings.getBooleanProperty("davmail.deleteBroken")) { LOGGER.warn("Deleting broken message at: " + message.messageUrl + " permanentUrl: " + message.permanentUrl); try { message.delete(); } catch (IOException ioe) { LOGGER.warn("Unable to delete broken message at: " + message.permanentUrl); } throw e; } } return baos.toByteArray(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getContent"
"@Override protected byte[] getContent(ExchangeSession.Message message) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream contentInputStream; try { try { try { <MASK>contentInputStream = getContentInputStream(message.messageUrl, restoreHostName);</MASK> } catch (UnknownHostException e) { // failover for misconfigured Exchange server, replace host name in url <MASK>contentInputStream = getContentInputStream(message.messageUrl, restoreHostName);</MASK> restoreHostName = true; } } catch (HttpNotFoundException e) { LOGGER.debug("Message not found at: " + message.messageUrl + ", retrying with permanenturl"); contentInputStream = getContentInputStream(message.permanentUrl, restoreHostName); } try { IOUtil.write(contentInputStream, baos); } finally { contentInputStream.close(); } } catch (LoginTimeoutException e) { // throw error on expired session LOGGER.warn(e.getMessage()); throw e; } catch (IOException e) { LOGGER.warn("Broken message at: " + message.messageUrl + " permanentUrl: " + message.permanentUrl + ", trying to rebuild from properties"); try { DavPropertyNameSet messageProperties = new DavPropertyNameSet(); messageProperties.add(Field.getPropertyName("contentclass")); messageProperties.add(Field.getPropertyName("message-id")); messageProperties.add(Field.getPropertyName("from")); messageProperties.add(Field.getPropertyName("to")); messageProperties.add(Field.getPropertyName("cc")); messageProperties.add(Field.getPropertyName("subject")); messageProperties.add(Field.getPropertyName("htmldescription")); messageProperties.add(Field.getPropertyName("body")); PropFindMethod propFindMethod = new PropFindMethod(URIUtil.encodePath(message.permanentUrl), messageProperties, 0); DavGatewayHttpClientFacade.executeMethod(httpClient, propFindMethod); MultiStatus responses = propFindMethod.getResponseBodyAsMultiStatus(); if (responses.getResponses().length > 0) { MimeMessage mimeMessage = new MimeMessage((Session) null); DavPropertySet properties = responses.getResponses()[0].getProperties(HttpStatus.SC_OK); String propertyValue = getPropertyIfExists(properties, "contentclass"); if (propertyValue != null) { mimeMessage.addHeader("Content-class", propertyValue); } propertyValue = getPropertyIfExists(properties, "from"); if (propertyValue != null) { mimeMessage.addHeader("From", propertyValue); } propertyValue = getPropertyIfExists(properties, "to"); if (propertyValue != null) { mimeMessage.addHeader("To", propertyValue); } propertyValue = getPropertyIfExists(properties, "cc"); if (propertyValue != null) { mimeMessage.addHeader("Cc", propertyValue); } propertyValue = getPropertyIfExists(properties, "subject"); if (propertyValue != null) { mimeMessage.setSubject(propertyValue); } propertyValue = getPropertyIfExists(properties, "htmldescription"); if (propertyValue != null) { mimeMessage.setContent(propertyValue, "text/html"); } else { propertyValue = getPropertyIfExists(properties, "body"); if (propertyValue != null) { mimeMessage.setText(propertyValue); } } mimeMessage.writeTo(baos); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Rebuilt message content: " + new String(baos.toByteArray())); } } catch (IOException e2) { LOGGER.warn(e2); } catch (DavException e2) { LOGGER.warn(e2); } catch (MessagingException e2) { LOGGER.warn(e2); } // other exception if (baos.size() == 0 && Settings.getBooleanProperty("davmail.deleteBroken")) { LOGGER.warn("Deleting broken message at: " + message.messageUrl + " permanentUrl: " + message.permanentUrl); try { message.delete(); } catch (IOException ioe) { LOGGER.warn("Unable to delete broken message at: " + message.permanentUrl); } throw e; } } return baos.toByteArray(); }"
Inversion-Mutation
megadiff
"private void initDisplayLists(DisplayListManager i_displayListManager, final Graphics3D g3d) { if (i_displayListManager.isDisplayList(DL_REST, DL_FRONT, DL_TEXTURE)) return; Runnable front = new Runnable() { public void run() { g3d.glBegin(Graphics3DDraw.GL_QUADS); g3d.glNormal3f(0, 0, -1); g3d.glVertex3f(0, 0, 0); g3d.glVertex3f(0, 1, 0); g3d.glVertex3f(1, 1, 0); g3d.glVertex3f(1, 0, 0); g3d.glEnd(); } }; Runnable texture = new Runnable() { public void run() { g3d.glBegin(Graphics3DDraw.GL_QUADS); g3d.glNormal3f(0, 0, -1); g3d.glTexCoord2f(0, 1); g3d.glVertex3f(0, 0, 0); g3d.glTexCoord2f(0, 0); g3d.glVertex3f(0, 1, 0); g3d.glTexCoord2f(1, 0); g3d.glVertex3f(1, 1, 0); g3d.glTexCoord2f(1, 1); g3d.glVertex3f(1, 0, 0); g3d.glNormal3f(0, 0, 1); g3d.glTexCoord2f(1, 1); g3d.glVertex3f(1, 0, 0); g3d.glTexCoord2f(1, 0); g3d.glVertex3f(1, 1, 0); g3d.glTexCoord2f(0, 0); g3d.glVertex3f(0, 1, 0); g3d.glTexCoord2f(0, 1); g3d.glVertex3f(0, 0, 0); g3d.glEnd(); } }; Runnable rest = new Runnable() { public void run() { g3d.glBegin(Graphics3DDraw.GL_QUADS); // back g3d.glNormal3f(0, 0, 1); g3d.glVertex3f(0, 0, 1); g3d.glVertex3f(1, 0, 1); g3d.glVertex3f(1, 1, 1); g3d.glVertex3f(0, 1, 1); // left g3d.glNormal3f(-1, 0, 0); g3d.glVertex3f(0, 0, 0); g3d.glVertex3f(0, 0, 1); g3d.glVertex3f(0, 1, 1); g3d.glVertex3f(0, 1, 0); // right g3d.glNormal3f(1, 0, 0); g3d.glVertex3f(1, 0, 1); g3d.glVertex3f(1, 0, 0); g3d.glVertex3f(1, 1, 0); g3d.glVertex3f(1, 1, 1); // top g3d.glNormal3f(0, 1, 0); g3d.glVertex3f(0, 1, 1); g3d.glVertex3f(1, 1, 1); g3d.glVertex3f(1, 1, 0); g3d.glVertex3f(0, 1, 0); // bottom g3d.glNormal3f(0, -1, 0); g3d.glVertex3f(1, 0, 0); g3d.glVertex3f(1, 0, 1); g3d.glVertex3f(0, 0, 1); g3d.glVertex3f(0, 0, 0); g3d.glEnd(); } }; i_displayListManager.createDisplayList(DL_FRONT, front); i_displayListManager.createDisplayList(DL_TEXTURE, texture); i_displayListManager.createDisplayList(DL_REST, rest); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "initDisplayLists"
"private void initDisplayLists(DisplayListManager i_displayListManager, final Graphics3D g3d) { if (i_displayListManager.isDisplayList(DL_REST, DL_FRONT, DL_TEXTURE)) return; Runnable front = new Runnable() { public void run() { g3d.glBegin(Graphics3DDraw.GL_QUADS); g3d.glNormal3f(0, 0, -1); <MASK>g3d.glVertex3f(0, 0, 0);</MASK> g3d.glVertex3f(0, 1, 0); g3d.glVertex3f(1, 1, 0); g3d.glVertex3f(1, 0, 0); g3d.glEnd(); } }; Runnable texture = new Runnable() { public void run() { g3d.glBegin(Graphics3DDraw.GL_QUADS); g3d.glNormal3f(0, 0, -1); g3d.glTexCoord2f(0, 1); <MASK>g3d.glVertex3f(0, 0, 0);</MASK> g3d.glTexCoord2f(0, 0); g3d.glVertex3f(0, 1, 0); g3d.glTexCoord2f(1, 0); g3d.glVertex3f(1, 1, 0); g3d.glTexCoord2f(1, 1); g3d.glVertex3f(1, 0, 0); g3d.glNormal3f(0, 0, 1); g3d.glTexCoord2f(1, 1); g3d.glVertex3f(1, 0, 0); g3d.glTexCoord2f(1, 0); g3d.glVertex3f(1, 1, 0); g3d.glTexCoord2f(0, 0); g3d.glVertex3f(0, 1, 0); g3d.glTexCoord2f(0, 1); <MASK>g3d.glVertex3f(0, 0, 0);</MASK> g3d.glEnd(); } }; Runnable rest = new Runnable() { public void run() { g3d.glBegin(Graphics3DDraw.GL_QUADS); // back g3d.glNormal3f(0, 0, 1); g3d.glVertex3f(0, 0, 1); g3d.glVertex3f(1, 0, 1); g3d.glVertex3f(1, 1, 1); g3d.glVertex3f(0, 1, 1); // left g3d.glNormal3f(-1, 0, 0); <MASK>g3d.glVertex3f(0, 0, 0);</MASK> g3d.glVertex3f(0, 0, 1); g3d.glVertex3f(0, 1, 1); g3d.glVertex3f(0, 1, 0); // right g3d.glNormal3f(1, 0, 0); g3d.glVertex3f(1, 0, 1); g3d.glVertex3f(1, 0, 0); g3d.glVertex3f(1, 1, 0); g3d.glVertex3f(1, 1, 1); // top g3d.glNormal3f(0, 1, 0); g3d.glVertex3f(0, 1, 1); g3d.glVertex3f(1, 1, 1); g3d.glVertex3f(1, 1, 0); g3d.glVertex3f(0, 1, 0); // bottom g3d.glNormal3f(0, -1, 0); <MASK>g3d.glVertex3f(0, 0, 0);</MASK> g3d.glVertex3f(1, 0, 0); g3d.glVertex3f(1, 0, 1); g3d.glVertex3f(0, 0, 1); g3d.glEnd(); } }; i_displayListManager.createDisplayList(DL_FRONT, front); i_displayListManager.createDisplayList(DL_TEXTURE, texture); i_displayListManager.createDisplayList(DL_REST, rest); }"
Inversion-Mutation
megadiff
"public void run() { g3d.glBegin(Graphics3DDraw.GL_QUADS); // back g3d.glNormal3f(0, 0, 1); g3d.glVertex3f(0, 0, 1); g3d.glVertex3f(1, 0, 1); g3d.glVertex3f(1, 1, 1); g3d.glVertex3f(0, 1, 1); // left g3d.glNormal3f(-1, 0, 0); g3d.glVertex3f(0, 0, 0); g3d.glVertex3f(0, 0, 1); g3d.glVertex3f(0, 1, 1); g3d.glVertex3f(0, 1, 0); // right g3d.glNormal3f(1, 0, 0); g3d.glVertex3f(1, 0, 1); g3d.glVertex3f(1, 0, 0); g3d.glVertex3f(1, 1, 0); g3d.glVertex3f(1, 1, 1); // top g3d.glNormal3f(0, 1, 0); g3d.glVertex3f(0, 1, 1); g3d.glVertex3f(1, 1, 1); g3d.glVertex3f(1, 1, 0); g3d.glVertex3f(0, 1, 0); // bottom g3d.glNormal3f(0, -1, 0); g3d.glVertex3f(1, 0, 0); g3d.glVertex3f(1, 0, 1); g3d.glVertex3f(0, 0, 1); g3d.glVertex3f(0, 0, 0); g3d.glEnd(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"public void run() { g3d.glBegin(Graphics3DDraw.GL_QUADS); // back g3d.glNormal3f(0, 0, 1); g3d.glVertex3f(0, 0, 1); g3d.glVertex3f(1, 0, 1); g3d.glVertex3f(1, 1, 1); g3d.glVertex3f(0, 1, 1); // left g3d.glNormal3f(-1, 0, 0); <MASK>g3d.glVertex3f(0, 0, 0);</MASK> g3d.glVertex3f(0, 0, 1); g3d.glVertex3f(0, 1, 1); g3d.glVertex3f(0, 1, 0); // right g3d.glNormal3f(1, 0, 0); g3d.glVertex3f(1, 0, 1); g3d.glVertex3f(1, 0, 0); g3d.glVertex3f(1, 1, 0); g3d.glVertex3f(1, 1, 1); // top g3d.glNormal3f(0, 1, 0); g3d.glVertex3f(0, 1, 1); g3d.glVertex3f(1, 1, 1); g3d.glVertex3f(1, 1, 0); g3d.glVertex3f(0, 1, 0); // bottom g3d.glNormal3f(0, -1, 0); <MASK>g3d.glVertex3f(0, 0, 0);</MASK> g3d.glVertex3f(1, 0, 0); g3d.glVertex3f(1, 0, 1); g3d.glVertex3f(0, 0, 1); g3d.glEnd(); }"
Inversion-Mutation
megadiff
"private void wakeupSerial(List<RobotPeer> robotsAtRandom) { for (RobotPeer robotPeer : robotsAtRandom) { if (robotPeer.isRunning()) { // This call blocks until the // robot's thread actually wakes up. robotPeer.waitWakeup(); if (robotPeer.isAlive()) { if (isDebugging || robotPeer.isPaintEnabled() || robotPeer.isPaintRecorded()) { robotPeer.waitSleeping(DEBUG_TURN_WAIT, 1); } else if (currentTime == 1) { robotPeer.waitSleeping(millisWait * 10, 1); } else { robotPeer.waitSleeping(millisWait, microWait); } robotPeer.setSkippedTurns(); } } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "wakeupSerial"
"private void wakeupSerial(List<RobotPeer> robotsAtRandom) { for (RobotPeer robotPeer : robotsAtRandom) { if (robotPeer.isRunning()) { // This call blocks until the // robot's thread actually wakes up. robotPeer.waitWakeup(); if (robotPeer.isAlive()) { if (isDebugging || robotPeer.isPaintEnabled() || robotPeer.isPaintRecorded()) { robotPeer.waitSleeping(DEBUG_TURN_WAIT, 1); } else if (currentTime == 1) { robotPeer.waitSleeping(millisWait * 10, 1); } else { robotPeer.waitSleeping(millisWait, microWait); } } <MASK>robotPeer.setSkippedTurns();</MASK> } } }"
Inversion-Mutation
megadiff
"@Override public List<MatchNode> search(String query) { List<MatchNode> result = new ArrayList<MatchNode>(); List<PatternRankResult> rankResult = new ArrayList<PatternRankResult>(); if (query.trim().equals("")) return result; if (sfMapList != null && sfMapList.size() > 0) for (SummaryFileMap map : sfMapList) { String summary = map.summary; rankQuery(summary.toLowerCase(), query.toLowerCase(), map.filePath, rankResult); } sortRankResult(rankResult); for(int k=0; k<Math.min(15, rankResult.size()); k++){ File jsonFile = new File(rankResult.get(k).getFilePath()); if (jsonFile.exists()) { Effect parent = GsonUtil.deserialize(jsonFile, Effect.class); parent.setId(System.currentTimeMillis() + String.valueOf(Math.random()).substring(5)); MatchNode[] children = new MatchNode[parent.getParameters().length]; this.values.clear(); if(rankResult.get(k).isInOrder()){ parseParameterValues(rankResult.get(k).getPattern(), query); } for (int i = 0; i < children.length; i++) { EffectParameter param = parent.getParameters()[i]; String keyName = param.getName().toLowerCase(); if(values.get(keyName) != null) param.setValue(values.get(keyName)); ArgumentMatchNode childNode = new ArgumentMatchNode(param.getName(), param); children[i] = childNode; } result.add(new EffectMatchNode(parent, rankResult.get(k).getPattern(), children)); } } return result; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "search"
"@Override public List<MatchNode> search(String query) { List<MatchNode> result = new ArrayList<MatchNode>(); List<PatternRankResult> rankResult = new ArrayList<PatternRankResult>(); if (query.trim().equals("")) return result; if (sfMapList != null && sfMapList.size() > 0) for (SummaryFileMap map : sfMapList) { String summary = map.summary; rankQuery(summary.toLowerCase(), query.toLowerCase(), map.filePath, rankResult); } sortRankResult(rankResult); for(int k=0; k<Math.min(15, rankResult.size()); k++){ File jsonFile = new File(rankResult.get(k).getFilePath()); if (jsonFile.exists()) { Effect parent = GsonUtil.deserialize(jsonFile, Effect.class); parent.setId(System.currentTimeMillis() + String.valueOf(Math.random()).substring(5)); MatchNode[] children = new MatchNode[parent.getParameters().length]; if(rankResult.get(k).isInOrder()){ <MASK>this.values.clear();</MASK> parseParameterValues(rankResult.get(k).getPattern(), query); } for (int i = 0; i < children.length; i++) { EffectParameter param = parent.getParameters()[i]; String keyName = param.getName().toLowerCase(); if(values.get(keyName) != null) param.setValue(values.get(keyName)); ArgumentMatchNode childNode = new ArgumentMatchNode(param.getName(), param); children[i] = childNode; } result.add(new EffectMatchNode(parent, rankResult.get(k).getPattern(), children)); } } return result; }"
Inversion-Mutation
megadiff
"protected void removeMacroSelected () { if (addedMacros.contains(selectedMacro)) { addedMacros.remove(selectedMacro); } else if (macros.contains(selectedMacro)) { removedMacros.add(selectedMacro); } macros.remove(selectedMacro); macroTable.remove(selectedMacro); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "removeMacroSelected"
"protected void removeMacroSelected () { if (addedMacros.contains(selectedMacro)) { addedMacros.remove(selectedMacro); } else if (macros.contains(selectedMacro)) { <MASK>macros.remove(selectedMacro);</MASK> removedMacros.add(selectedMacro); } macroTable.remove(selectedMacro); }"
Inversion-Mutation
megadiff
"@Override public void loadAsync (AssetManager manager, String fileName, FileHandle file, TextureParameter parameter) { info.filename = fileName; if (parameter == null || parameter.textureData == null) { Pixmap pixmap = null; Format format = null; boolean genMipMaps = false; info.texture = null; if (parameter != null) { format = parameter.format; genMipMaps = parameter.genMipMaps; info.texture = parameter.texture; } if (!fileName.contains(".etc1")) { if (fileName.contains(".cim")) pixmap = PixmapIO.readCIM(file); else pixmap = new Pixmap(file); info.data = new FileTextureData(file, pixmap, format, genMipMaps); } else { info.data = new ETC1TextureData(file, genMipMaps); } } else { info.data = parameter.textureData; info.texture = parameter.texture; } if (!info.data.isPrepared()) info.data.prepare(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "loadAsync"
"@Override public void loadAsync (AssetManager manager, String fileName, FileHandle file, TextureParameter parameter) { info.filename = fileName; if (parameter == null || parameter.textureData == null) { Pixmap pixmap = null; Format format = null; boolean genMipMaps = false; info.texture = null; if (parameter != null) { format = parameter.format; genMipMaps = parameter.genMipMaps; info.texture = parameter.texture; } if (!fileName.contains(".etc1")) { if (fileName.contains(".cim")) pixmap = PixmapIO.readCIM(file); else pixmap = new Pixmap(file); info.data = new FileTextureData(file, pixmap, format, genMipMaps); } else { info.data = new ETC1TextureData(file, genMipMaps); } } else { info.data = parameter.textureData; <MASK>if (!info.data.isPrepared()) info.data.prepare();</MASK> info.texture = parameter.texture; } }"
Inversion-Mutation
megadiff
"private byte[] getICSFromItemProperties() throws IOException { byte[] result; // experimental: build VCALENDAR from properties try { //MultiStatusResponse[] responses = DavGatewayHttpClientFacade.executeMethod(httpClient, propFindMethod); Set<String> eventProperties = new HashSet<String>(); eventProperties.add("method"); eventProperties.add("created"); eventProperties.add("calendarlastmodified"); eventProperties.add("dtstamp"); eventProperties.add("calendaruid"); eventProperties.add("subject"); eventProperties.add("dtstart"); eventProperties.add("dtend"); eventProperties.add("transparent"); eventProperties.add("organizer"); eventProperties.add("to"); eventProperties.add("description"); eventProperties.add("rrule"); eventProperties.add("exdate"); eventProperties.add("sensitivity"); eventProperties.add("alldayevent"); eventProperties.add("busystatus"); eventProperties.add("reminderset"); eventProperties.add("reminderdelta"); // task eventProperties.add("importance"); eventProperties.add("uid"); eventProperties.add("taskstatus"); eventProperties.add("percentcomplete"); eventProperties.add("keywords"); eventProperties.add("startdate"); eventProperties.add("duedate"); eventProperties.add("datecompleted"); MultiStatusResponse[] responses = searchItems(folderPath, eventProperties, DavExchangeSession.this.isEqualTo("urlcompname", convertItemNameToEML(itemName)), FolderQueryTraversal.Shallow, 1); if (responses.length == 0) { throw new HttpNotFoundException(permanentUrl + " not found"); } DavPropertySet davPropertySet = responses[0].getProperties(HttpStatus.SC_OK); VCalendar localVCalendar = new VCalendar(); localVCalendar.setPropertyValue("PRODID", "-//davmail.sf.net/NONSGML DavMail Calendar V1.1//EN"); localVCalendar.setPropertyValue("VERSION", "2.0"); localVCalendar.setPropertyValue("METHOD", getPropertyIfExists(davPropertySet, "method")); VObject vEvent = new VObject(); vEvent.setPropertyValue("CREATED", convertDateFromExchange(getPropertyIfExists(davPropertySet, "created"))); vEvent.setPropertyValue("LAST-MODIFIED", convertDateFromExchange(getPropertyIfExists(davPropertySet, "calendarlastmodified"))); vEvent.setPropertyValue("DTSTAMP", convertDateFromExchange(getPropertyIfExists(davPropertySet, "dtstamp"))); String uid = getPropertyIfExists(davPropertySet, "calendaruid"); if (uid == null) { uid = getPropertyIfExists(davPropertySet, "uid"); } vEvent.setPropertyValue("UID", uid); vEvent.setPropertyValue("SUMMARY", getPropertyIfExists(davPropertySet, "subject")); vEvent.setPropertyValue("DESCRIPTION", getPropertyIfExists(davPropertySet, "description")); vEvent.setPropertyValue("PRIORITY", convertPriorityFromExchange(getPropertyIfExists(davPropertySet, "importance"))); vEvent.setPropertyValue("CATEGORIES", getPropertyIfExists(davPropertySet, "keywords")); if (instancetype == null) { vEvent.type = "VTODO"; double percentComplete = getDoublePropertyIfExists(davPropertySet, "percentcomplete"); if (percentComplete > 0) { vEvent.setPropertyValue("PERCENT-COMPLETE", String.valueOf((int) (percentComplete * 100))); } vEvent.setPropertyValue("STATUS", taskTovTodoStatusMap.get(getPropertyIfExists(davPropertySet, "taskstatus"))); vEvent.setPropertyValue("DUE;VALUE=DATE", convertDateFromExchangeToTaskDate(getPropertyIfExists(davPropertySet, "duedate"))); vEvent.setPropertyValue("DTSTART;VALUE=DATE", convertDateFromExchangeToTaskDate(getPropertyIfExists(davPropertySet, "startdate"))); vEvent.setPropertyValue("COMPLETED;VALUE=DATE", convertDateFromExchangeToTaskDate(getPropertyIfExists(davPropertySet, "datecompleted"))); } else { vEvent.type = "VEVENT"; // check mandatory dtstart value String dtstart = getPropertyIfExists(davPropertySet, "dtstart"); if (dtstart != null) { vEvent.setPropertyValue("DTSTART", convertDateFromExchange(dtstart)); } else { LOGGER.warn("missing dtstart on item, using fake value. Set davmail.deleteBroken=true to delete broken events"); vEvent.setPropertyValue("DTSTART", "20000101T000000Z"); deleteBroken(); } // same on DTEND String dtend = getPropertyIfExists(davPropertySet, "dtend"); if (dtend != null) { vEvent.setPropertyValue("DTEND", convertDateFromExchange(dtend)); } else { LOGGER.warn("missing dtend on item, using fake value. Set davmail.deleteBroken=true to delete broken events"); vEvent.setPropertyValue("DTEND", "20000101T010000Z"); deleteBroken(); } vEvent.setPropertyValue("TRANSP", getPropertyIfExists(davPropertySet, "transparent")); vEvent.setPropertyValue("RRULE", getPropertyIfExists(davPropertySet, "rrule")); String exdates = getPropertyIfExists(davPropertySet, "exdate"); if (exdates != null) { String[] exdatearray = exdates.split(","); for (String exdate : exdatearray) { vEvent.addPropertyValue("EXDATE", StringUtil.convertZuluDateTimeToAllDay(convertDateFromExchange(exdate))); } } String sensitivity = getPropertyIfExists(davPropertySet, "sensitivity"); if ("2".equals(sensitivity)) { vEvent.setPropertyValue("CLASS", "PRIVATE"); } else if ("3".equals(sensitivity)) { vEvent.setPropertyValue("CLASS", "CONFIDENTIAL"); } else if ("0".equals(sensitivity)) { vEvent.setPropertyValue("CLASS", "PUBLIC"); } String organizer = getPropertyIfExists(davPropertySet, "organizer"); String organizerEmail = null; if (organizer != null) { InternetAddress organizerAddress = new InternetAddress(organizer); organizerEmail = organizerAddress.getAddress(); vEvent.setPropertyValue("ORGANIZER", "MAILTO:" + organizerEmail); } // Parse attendee list String toHeader = getPropertyIfExists(davPropertySet, "to"); if (toHeader != null && !toHeader.equals(organizerEmail)) { InternetAddress[] attendees = InternetAddress.parseHeader(toHeader, false); for (InternetAddress attendee : attendees) { if (!attendee.getAddress().equalsIgnoreCase(organizerEmail)) { VProperty vProperty = new VProperty("ATTENDEE", attendee.getAddress()); if (attendee.getPersonal() != null) { vProperty.addParam("CN", attendee.getPersonal()); } vEvent.addProperty(vProperty); } } } vEvent.setPropertyValue("X-MICROSOFT-CDO-ALLDAYEVENT", "1".equals(getPropertyIfExists(davPropertySet, "alldayevent")) ? "TRUE" : "FALSE"); vEvent.setPropertyValue("X-MICROSOFT-CDO-BUSYSTATUS", getPropertyIfExists(davPropertySet, "busystatus")); if ("1".equals(getPropertyIfExists(davPropertySet, "reminderset"))) { VObject vAlarm = new VObject(); vAlarm.type = "VALARM"; vAlarm.setPropertyValue("ACTION", "DISPLAY"); vAlarm.setPropertyValue("DISPLAY", "Reminder"); String reminderdelta = getPropertyIfExists(davPropertySet, "reminderdelta"); VProperty vProperty = new VProperty("TRIGGER", "-PT" + reminderdelta + 'M'); vProperty.addParam("VALUE", "DURATION"); vAlarm.addProperty(vProperty); vEvent.addVObject(vAlarm); } } localVCalendar.addVObject(vEvent); result = localVCalendar.toString().getBytes("UTF-8"); } catch (MessagingException e) { LOGGER.warn("Unable to rebuild event content: " + e.getMessage(), e); throw buildHttpException(e); } catch (IOException e) { LOGGER.warn("Unable to rebuild event content: " + e.getMessage(), e); throw buildHttpException(e); } return result; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getICSFromItemProperties"
"private byte[] getICSFromItemProperties() throws IOException { byte[] result; // experimental: build VCALENDAR from properties try { //MultiStatusResponse[] responses = DavGatewayHttpClientFacade.executeMethod(httpClient, propFindMethod); Set<String> eventProperties = new HashSet<String>(); eventProperties.add("method"); eventProperties.add("created"); eventProperties.add("calendarlastmodified"); eventProperties.add("dtstamp"); eventProperties.add("calendaruid"); eventProperties.add("subject"); eventProperties.add("dtstart"); eventProperties.add("dtend"); eventProperties.add("transparent"); eventProperties.add("organizer"); eventProperties.add("to"); eventProperties.add("description"); eventProperties.add("rrule"); eventProperties.add("exdate"); eventProperties.add("sensitivity"); eventProperties.add("alldayevent"); eventProperties.add("busystatus"); eventProperties.add("reminderset"); eventProperties.add("reminderdelta"); // task eventProperties.add("importance"); eventProperties.add("uid"); eventProperties.add("taskstatus"); eventProperties.add("percentcomplete"); eventProperties.add("keywords"); eventProperties.add("startdate"); eventProperties.add("duedate"); eventProperties.add("datecompleted"); MultiStatusResponse[] responses = searchItems(folderPath, eventProperties, DavExchangeSession.this.isEqualTo("urlcompname", convertItemNameToEML(itemName)), FolderQueryTraversal.Shallow, 1); if (responses.length == 0) { throw new HttpNotFoundException(permanentUrl + " not found"); } DavPropertySet davPropertySet = responses[0].getProperties(HttpStatus.SC_OK); VCalendar localVCalendar = new VCalendar(); localVCalendar.setPropertyValue("PRODID", "-//davmail.sf.net/NONSGML DavMail Calendar V1.1//EN"); localVCalendar.setPropertyValue("VERSION", "2.0"); localVCalendar.setPropertyValue("METHOD", getPropertyIfExists(davPropertySet, "method")); VObject vEvent = new VObject(); vEvent.setPropertyValue("CREATED", convertDateFromExchange(getPropertyIfExists(davPropertySet, "created"))); vEvent.setPropertyValue("LAST-MODIFIED", convertDateFromExchange(getPropertyIfExists(davPropertySet, "calendarlastmodified"))); vEvent.setPropertyValue("DTSTAMP", convertDateFromExchange(getPropertyIfExists(davPropertySet, "dtstamp"))); String uid = getPropertyIfExists(davPropertySet, "calendaruid"); if (uid == null) { uid = getPropertyIfExists(davPropertySet, "uid"); } vEvent.setPropertyValue("UID", uid); vEvent.setPropertyValue("SUMMARY", getPropertyIfExists(davPropertySet, "subject")); vEvent.setPropertyValue("PRIORITY", convertPriorityFromExchange(getPropertyIfExists(davPropertySet, "importance"))); vEvent.setPropertyValue("CATEGORIES", getPropertyIfExists(davPropertySet, "keywords")); if (instancetype == null) { vEvent.type = "VTODO"; double percentComplete = getDoublePropertyIfExists(davPropertySet, "percentcomplete"); if (percentComplete > 0) { vEvent.setPropertyValue("PERCENT-COMPLETE", String.valueOf((int) (percentComplete * 100))); } vEvent.setPropertyValue("STATUS", taskTovTodoStatusMap.get(getPropertyIfExists(davPropertySet, "taskstatus"))); vEvent.setPropertyValue("DUE;VALUE=DATE", convertDateFromExchangeToTaskDate(getPropertyIfExists(davPropertySet, "duedate"))); vEvent.setPropertyValue("DTSTART;VALUE=DATE", convertDateFromExchangeToTaskDate(getPropertyIfExists(davPropertySet, "startdate"))); vEvent.setPropertyValue("COMPLETED;VALUE=DATE", convertDateFromExchangeToTaskDate(getPropertyIfExists(davPropertySet, "datecompleted"))); } else { vEvent.type = "VEVENT"; // check mandatory dtstart value String dtstart = getPropertyIfExists(davPropertySet, "dtstart"); if (dtstart != null) { vEvent.setPropertyValue("DTSTART", convertDateFromExchange(dtstart)); } else { LOGGER.warn("missing dtstart on item, using fake value. Set davmail.deleteBroken=true to delete broken events"); vEvent.setPropertyValue("DTSTART", "20000101T000000Z"); deleteBroken(); } // same on DTEND String dtend = getPropertyIfExists(davPropertySet, "dtend"); if (dtend != null) { vEvent.setPropertyValue("DTEND", convertDateFromExchange(dtend)); } else { LOGGER.warn("missing dtend on item, using fake value. Set davmail.deleteBroken=true to delete broken events"); vEvent.setPropertyValue("DTEND", "20000101T010000Z"); deleteBroken(); } vEvent.setPropertyValue("TRANSP", getPropertyIfExists(davPropertySet, "transparent")); vEvent.setPropertyValue("RRULE", getPropertyIfExists(davPropertySet, "rrule")); String exdates = getPropertyIfExists(davPropertySet, "exdate"); if (exdates != null) { String[] exdatearray = exdates.split(","); for (String exdate : exdatearray) { vEvent.addPropertyValue("EXDATE", StringUtil.convertZuluDateTimeToAllDay(convertDateFromExchange(exdate))); } } String sensitivity = getPropertyIfExists(davPropertySet, "sensitivity"); if ("2".equals(sensitivity)) { vEvent.setPropertyValue("CLASS", "PRIVATE"); } else if ("3".equals(sensitivity)) { vEvent.setPropertyValue("CLASS", "CONFIDENTIAL"); } else if ("0".equals(sensitivity)) { vEvent.setPropertyValue("CLASS", "PUBLIC"); } String organizer = getPropertyIfExists(davPropertySet, "organizer"); String organizerEmail = null; if (organizer != null) { InternetAddress organizerAddress = new InternetAddress(organizer); organizerEmail = organizerAddress.getAddress(); vEvent.setPropertyValue("ORGANIZER", "MAILTO:" + organizerEmail); } // Parse attendee list String toHeader = getPropertyIfExists(davPropertySet, "to"); if (toHeader != null && !toHeader.equals(organizerEmail)) { InternetAddress[] attendees = InternetAddress.parseHeader(toHeader, false); for (InternetAddress attendee : attendees) { if (!attendee.getAddress().equalsIgnoreCase(organizerEmail)) { VProperty vProperty = new VProperty("ATTENDEE", attendee.getAddress()); if (attendee.getPersonal() != null) { vProperty.addParam("CN", attendee.getPersonal()); } vEvent.addProperty(vProperty); } } } <MASK>vEvent.setPropertyValue("DESCRIPTION", getPropertyIfExists(davPropertySet, "description"));</MASK> vEvent.setPropertyValue("X-MICROSOFT-CDO-ALLDAYEVENT", "1".equals(getPropertyIfExists(davPropertySet, "alldayevent")) ? "TRUE" : "FALSE"); vEvent.setPropertyValue("X-MICROSOFT-CDO-BUSYSTATUS", getPropertyIfExists(davPropertySet, "busystatus")); if ("1".equals(getPropertyIfExists(davPropertySet, "reminderset"))) { VObject vAlarm = new VObject(); vAlarm.type = "VALARM"; vAlarm.setPropertyValue("ACTION", "DISPLAY"); vAlarm.setPropertyValue("DISPLAY", "Reminder"); String reminderdelta = getPropertyIfExists(davPropertySet, "reminderdelta"); VProperty vProperty = new VProperty("TRIGGER", "-PT" + reminderdelta + 'M'); vProperty.addParam("VALUE", "DURATION"); vAlarm.addProperty(vProperty); vEvent.addVObject(vAlarm); } } localVCalendar.addVObject(vEvent); result = localVCalendar.toString().getBytes("UTF-8"); } catch (MessagingException e) { LOGGER.warn("Unable to rebuild event content: " + e.getMessage(), e); throw buildHttpException(e); } catch (IOException e) { LOGGER.warn("Unable to rebuild event content: " + e.getMessage(), e); throw buildHttpException(e); } return result; }"
Inversion-Mutation
megadiff
"@Override public void handleReaderList(ITagListHandler tagHandler, ISubscriptionListHandler subHandler, long syncTime) throws ReaderException { try { SubsStruct.InstanceRefresh(c); APIHelper.updateFeedCounts(c, SubsStruct.Instance(c).Subs); if (SubsStruct.Instance(c).Subs.size() == 0) throw new ReaderException("No subscriptions available"); else { subHandler.subscriptions(SubsStruct.Instance(c).Subs); tagHandler.tags(SubsStruct.Instance(c).Tags); } } catch (JSONException e) { throw new ReaderException("Data parse error", e); } catch (RemoteException e) { throw new ReaderException("Remote connection error", e); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handleReaderList"
"@Override public void handleReaderList(ITagListHandler tagHandler, ISubscriptionListHandler subHandler, long syncTime) throws ReaderException { try { SubsStruct.InstanceRefresh(c); APIHelper.updateFeedCounts(c, SubsStruct.Instance(c).Subs); if (SubsStruct.Instance(c).Subs.size() == 0) throw new ReaderException("No subscriptions available"); else { <MASK>tagHandler.tags(SubsStruct.Instance(c).Tags);</MASK> subHandler.subscriptions(SubsStruct.Instance(c).Subs); } } catch (JSONException e) { throw new ReaderException("Data parse error", e); } catch (RemoteException e) { throw new ReaderException("Remote connection error", e); } }"
Inversion-Mutation
megadiff
"@SuppressWarnings("unchecked") @Override public void init(GameContainer gc, StateBasedGame sbg) throws SlickException { background= new Image("img/game_background.png"); cannonImage = new Image("img/cannon2.png"); block = new Image("img/block.png"); pausedScreen = new Image(Util.WINDOW_WIDTH, Util.WINDOW_HEIGHT); block = new Image("img/block/purple.png"); cannon = new Cannon(); bulletList = new ArrayList<Bullet>(); blocks = new ArrayList<Image>(); player = new Player(); blockBox = new BlockBox(player); ch = new CollisionHandler(blockBox); isPaused = false; timerInterval = 2000; Font font = new Font("Verdana", Font.PLAIN,55); scoreDisplay = new UnicodeFont(font , 15, true, false); scoreDisplay.addAsciiGlyphs(); scoreDisplay.addGlyphs(400, 600); scoreDisplay.getEffects().add(new ColorEffect(java.awt.Color.YELLOW)); try { scoreDisplay.loadGlyphs(); } catch (SlickException e1) { e1.printStackTrace(); } blockTimer = new Timer(); blockTimer.scheduleAtFixedRate(new TimerTask() { public void run() { try { blockBox.newBlock((int)(Math.random()*7+0.5)); } catch (SlickException e) { e.printStackTrace(); } } }, timerInterval, timerInterval); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "init"
"@SuppressWarnings("unchecked") @Override public void init(GameContainer gc, StateBasedGame sbg) throws SlickException { background= new Image("img/game_background.png"); cannonImage = new Image("img/cannon2.png"); block = new Image("img/block.png"); pausedScreen = new Image(Util.WINDOW_WIDTH, Util.WINDOW_HEIGHT); block = new Image("img/block/purple.png"); cannon = new Cannon(); bulletList = new ArrayList<Bullet>(); blocks = new ArrayList<Image>(); <MASK>ch = new CollisionHandler(blockBox);</MASK> player = new Player(); blockBox = new BlockBox(player); isPaused = false; timerInterval = 2000; Font font = new Font("Verdana", Font.PLAIN,55); scoreDisplay = new UnicodeFont(font , 15, true, false); scoreDisplay.addAsciiGlyphs(); scoreDisplay.addGlyphs(400, 600); scoreDisplay.getEffects().add(new ColorEffect(java.awt.Color.YELLOW)); try { scoreDisplay.loadGlyphs(); } catch (SlickException e1) { e1.printStackTrace(); } blockTimer = new Timer(); blockTimer.scheduleAtFixedRate(new TimerTask() { public void run() { try { blockBox.newBlock((int)(Math.random()*7+0.5)); } catch (SlickException e) { e.printStackTrace(); } } }, timerInterval, timerInterval); }"
Inversion-Mutation
megadiff
"public void build() { buildClassMapRegistry(); for (final ClassMap<?, ?> classMap : classMapRegistry.values()) { buildMapper(classMap); } for (final ClassMap<?, ?> classMap : classMapRegistry.values()) { buildObjectFactories(classMap); initializeUsedMappers(classMap); } isBuilt = true; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "build"
"public void build() { <MASK>isBuilt = true;</MASK> buildClassMapRegistry(); for (final ClassMap<?, ?> classMap : classMapRegistry.values()) { buildMapper(classMap); } for (final ClassMap<?, ?> classMap : classMapRegistry.values()) { buildObjectFactories(classMap); initializeUsedMappers(classMap); } }"
Inversion-Mutation
megadiff
"@Override public void updateFormModel(ProductSceneView productSceneView) { ImageInfoEditorModel1B model = new ImageInfoEditorModel1B(parentForm.getImageInfo()); model.addChangeListener(applyEnablerCL); ImageInfoEditorModel oldModel = imageInfoEditor.getModel(); if (oldModel != null) { model.setHistogramViewGain(oldModel.getHistogramViewGain()); model.setMinHistogramViewSample(oldModel.getMinHistogramViewSample()); model.setMaxHistogramViewSample(oldModel.getMaxHistogramViewSample()); } imageInfoEditor.setModel(model); model.setDisplayProperties(productSceneView.getRaster()); parentForm.revalidateToolViewPaneControl(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "updateFormModel"
"@Override public void updateFormModel(ProductSceneView productSceneView) { ImageInfoEditorModel1B model = new ImageInfoEditorModel1B(parentForm.getImageInfo()); <MASK>model.setDisplayProperties(productSceneView.getRaster());</MASK> model.addChangeListener(applyEnablerCL); ImageInfoEditorModel oldModel = imageInfoEditor.getModel(); if (oldModel != null) { model.setHistogramViewGain(oldModel.getHistogramViewGain()); model.setMinHistogramViewSample(oldModel.getMinHistogramViewSample()); model.setMaxHistogramViewSample(oldModel.getMaxHistogramViewSample()); } imageInfoEditor.setModel(model); parentForm.revalidateToolViewPaneControl(); }"
Inversion-Mutation
megadiff
"private void joinTransaction() throws SystemException { SeamTransaction transaction = userTransactionInstance.get(); if (transaction.isActive()) { synchronizationRegistered = true; transaction.enlist(delegate); try { transaction.registerSynchronization(this); } catch (Exception e) { // synchronizationRegistered = // PersistenceProvider.instance().registerSynchronization(this, // entityManager); synchronizationRegistered = false; throw new RuntimeException(e); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "joinTransaction"
"private void joinTransaction() throws SystemException { <MASK>synchronizationRegistered = true;</MASK> SeamTransaction transaction = userTransactionInstance.get(); if (transaction.isActive()) { transaction.enlist(delegate); try { transaction.registerSynchronization(this); } catch (Exception e) { // synchronizationRegistered = // PersistenceProvider.instance().registerSynchronization(this, // entityManager); synchronizationRegistered = false; throw new RuntimeException(e); } } }"
Inversion-Mutation
megadiff
"public static void delete(Episode episode) { episode.setStorageState(StorageState.NOT_ON_DEVICE); cancelDownload(episode); if (episode.getFilePath() != null) { File file = new File(episode.getFilePath()); file.delete(); episode.setFilePath(null); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "delete"
"public static void delete(Episode episode) { <MASK>episode.setFilePath(null);</MASK> episode.setStorageState(StorageState.NOT_ON_DEVICE); cancelDownload(episode); if (episode.getFilePath() != null) { File file = new File(episode.getFilePath()); file.delete(); } }"
Inversion-Mutation
megadiff
"@SuppressWarnings("unchecked") private void executeRewrite() { BufferedReader reader = null; PrintStream output = null; try { try { reader = new BufferedReader(new FileReader(input)); output = new PrintStream(new File(destDir, input.getName())); int i, num = 0; String line, key, value; OverrideType override; while ((line = reader.readLine()) != null) { num ++; i = line.indexOf(':'); if (i == -1) throw new BuildException("unexpected line in jad file: "+num); key = line.substring(0, i); value = line.substring(i+1); if (key.startsWith("RIM-COD-URL") || key.startsWith("RIM-COD-SHA1") || key.startsWith("RIM-COD-Size")) { continue; // ignore line } // check for .jad element override, remove from map if found override = overrideMap.get(key.toLowerCase()); if (override != null) { value = override.getValue(); overrideMap.remove(key.toLowerCase()); } output.printf("%s: %s\n", key, value); } } catch (IOException e) { throw new BuildException("error creating jad file", e); } try { int num = 0; File destFile; Resource r; for (ResourceCollection rc : resources) { Iterator<Resource> i = rc.iterator(); while (i.hasNext()) { r = i.next(); destFile = new File(destDir, Utils.getFilePart(r)); if (Utils.isZip(r)) { String[] zipEntries = Utils.extract(r, destDir); for (String entry : zipEntries) { destFile = new File(destDir, entry); if (num == 0) { output.printf("RIM-COD-URL: %s\n", destFile.getName()); output.printf("RIM-COD-SHA1: %s\n", Utils.getSHA1(destFile)); output.printf("RIM-COD-Size: %d\n", destFile.length()); } else { output.printf("RIM-COD-URL-%d: %s\n", num, destFile.getName()); output.printf("RIM-COD-SHA1-%d: %s\n", num, Utils.getSHA1(destFile)); output.printf("RIM-COD-Size-%d: %d\n", num, destFile.length()); } num++; } } else { ResourceUtils.copyResource(r, new FileResource(destFile)); if (num == 0) { output.printf("RIM-COD-URL: %s\n", destFile.getName()); output.printf("RIM-COD-SHA1: %s\n", Utils.getSHA1(destFile)); output.printf("RIM-COD-Size: %d\n", destFile.length()); } else { output.printf("RIM-COD-URL-%d: %s\n", num, destFile.getName()); output.printf("RIM-COD-SHA1-%d: %s\n", num, Utils.getSHA1(destFile)); output.printf("RIM-COD-Size-%d: %d\n", num, destFile.length()); } num ++; } } } } catch (IOException e) { throw new BuildException("error copying cod file", e); } // flush remaining overrides into target .jad for (OverrideType override : overrideMap.values()) { output.printf("%s: %s\n", override.getKey(), override.getValue()); } } finally { FileUtils.close(reader); FileUtils.close(output); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "executeRewrite"
"@SuppressWarnings("unchecked") private void executeRewrite() { BufferedReader reader = null; PrintStream output = null; try { try { reader = new BufferedReader(new FileReader(input)); output = new PrintStream(new File(destDir, input.getName())); int i, num = 0; String line, key, value; OverrideType override; while ((line = reader.readLine()) != null) { <MASK>num ++;</MASK> i = line.indexOf(':'); if (i == -1) throw new BuildException("unexpected line in jad file: "+num); key = line.substring(0, i); value = line.substring(i+1); if (key.startsWith("RIM-COD-URL") || key.startsWith("RIM-COD-SHA1") || key.startsWith("RIM-COD-Size")) { continue; // ignore line } // check for .jad element override, remove from map if found override = overrideMap.get(key.toLowerCase()); if (override != null) { value = override.getValue(); overrideMap.remove(key.toLowerCase()); } output.printf("%s: %s\n", key, value); } } catch (IOException e) { throw new BuildException("error creating jad file", e); } try { int num = 0; File destFile; Resource r; for (ResourceCollection rc : resources) { Iterator<Resource> i = rc.iterator(); while (i.hasNext()) { r = i.next(); destFile = new File(destDir, Utils.getFilePart(r)); if (Utils.isZip(r)) { String[] zipEntries = Utils.extract(r, destDir); for (String entry : zipEntries) { destFile = new File(destDir, entry); if (num == 0) { output.printf("RIM-COD-URL: %s\n", destFile.getName()); output.printf("RIM-COD-SHA1: %s\n", Utils.getSHA1(destFile)); output.printf("RIM-COD-Size: %d\n", destFile.length()); } else { output.printf("RIM-COD-URL-%d: %s\n", num, destFile.getName()); output.printf("RIM-COD-SHA1-%d: %s\n", num, Utils.getSHA1(destFile)); output.printf("RIM-COD-Size-%d: %d\n", num, destFile.length()); } num++; } } else { ResourceUtils.copyResource(r, new FileResource(destFile)); if (num == 0) { output.printf("RIM-COD-URL: %s\n", destFile.getName()); output.printf("RIM-COD-SHA1: %s\n", Utils.getSHA1(destFile)); output.printf("RIM-COD-Size: %d\n", destFile.length()); } else { output.printf("RIM-COD-URL-%d: %s\n", num, destFile.getName()); output.printf("RIM-COD-SHA1-%d: %s\n", num, Utils.getSHA1(destFile)); output.printf("RIM-COD-Size-%d: %d\n", num, destFile.length()); } } <MASK>num ++;</MASK> } } } catch (IOException e) { throw new BuildException("error copying cod file", e); } // flush remaining overrides into target .jad for (OverrideType override : overrideMap.values()) { output.printf("%s: %s\n", override.getKey(), override.getValue()); } } finally { FileUtils.close(reader); FileUtils.close(output); } }"
Inversion-Mutation
megadiff
"public void ensureOutOfSync(final IFile file) { modifyInFileSystem(file); touchInFilesystem(file); assertTrue("File not out of sync: " + file.getLocation().toOSString(), file.getLocation().toFile().lastModified() != file.getLocalTimeStamp()); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "ensureOutOfSync"
"public void ensureOutOfSync(final IFile file) { <MASK>touchInFilesystem(file);</MASK> modifyInFileSystem(file); assertTrue("File not out of sync: " + file.getLocation().toOSString(), file.getLocation().toFile().lastModified() != file.getLocalTimeStamp()); }"
Inversion-Mutation
megadiff
"private void loadPlugins(HostPageData hpd, final String token) { ApiGlue.init(); if (hpd.plugins != null && !hpd.plugins.isEmpty()) { for (final String url : hpd.plugins) { ScriptInjector.fromUrl(url) .setWindow(ScriptInjector.TOP_WINDOW) .setCallback(new Callback<Void, Exception>() { @Override public void onSuccess(Void result) { } @Override public void onFailure(Exception reason) { ErrorDialog d = new ErrorDialog(reason); d.setTitle(M.pluginFailed(url)); d.center(); } }).inject(); } } CallbackHandle<Void> cb = new CallbackHandle<Void>( new ResultDeserializer<Void>() { @Override public Void fromResult(JavaScriptObject responseObject) { return null; } }, new AsyncCallback<Void>() { @Override public void onFailure(Throwable caught) { } @Override public void onSuccess(Void result) { display(token); } }); cb.install(); ScriptInjector.fromString(cb.getFunctionName() + "();") .setWindow(ScriptInjector.TOP_WINDOW) .inject(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "loadPlugins"
"private void loadPlugins(HostPageData hpd, final String token) { if (hpd.plugins != null && !hpd.plugins.isEmpty()) { <MASK>ApiGlue.init();</MASK> for (final String url : hpd.plugins) { ScriptInjector.fromUrl(url) .setWindow(ScriptInjector.TOP_WINDOW) .setCallback(new Callback<Void, Exception>() { @Override public void onSuccess(Void result) { } @Override public void onFailure(Exception reason) { ErrorDialog d = new ErrorDialog(reason); d.setTitle(M.pluginFailed(url)); d.center(); } }).inject(); } } CallbackHandle<Void> cb = new CallbackHandle<Void>( new ResultDeserializer<Void>() { @Override public Void fromResult(JavaScriptObject responseObject) { return null; } }, new AsyncCallback<Void>() { @Override public void onFailure(Throwable caught) { } @Override public void onSuccess(Void result) { display(token); } }); cb.install(); ScriptInjector.fromString(cb.getFunctionName() + "();") .setWindow(ScriptInjector.TOP_WINDOW) .inject(); }"
Inversion-Mutation
megadiff
"public static String buildGeneralURLForCalendarPage(String provId, String provTitle, String keyword, String courseTitle, String preserve){ StringBuilder sb = new StringBuilder(buildBasicURL(provId, provTitle, keyword, courseTitle)); if (StringUtils.hasText(preserve)){ StringBuilder calendarSb = new StringBuilder(); String[] parameterPairs = preserve.split(","); for (String pair : parameterPairs){ if (calendarSb.length() > 0){ calendarSb.append("&"); } calendarSb.append(pair.split(":")[0]); calendarSb.append("="); calendarSb.append(pair.split(":")[1]); } if (sb.length() > 0){ sb.append("&"); } sb.append(calendarSb); } return sb.toString(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "buildGeneralURLForCalendarPage"
"public static String buildGeneralURLForCalendarPage(String provId, String provTitle, String keyword, String courseTitle, String preserve){ StringBuilder sb = new StringBuilder(buildBasicURL(provId, provTitle, keyword, courseTitle)); if (StringUtils.hasText(preserve)){ StringBuilder calendarSb = new StringBuilder(); String[] parameterPairs = preserve.split(","); for (String pair : parameterPairs){ if (calendarSb.length() > 0){ calendarSb.append("&"); } calendarSb.append(pair.split(":")[0]); calendarSb.append("="); calendarSb.append(pair.split(":")[1]); } if (sb.length() > 0){ sb.append("&"); <MASK>sb.append(calendarSb);</MASK> } } return sb.toString(); }"
Inversion-Mutation
megadiff
"public Propiedades() { FileInputStream file = null; URL root = getClass().getProtectionDomain().getCodeSource() .getLocation(); URL filePath = null; prop = new Properties(); try { filePath = new URL(root, NOMBRE_ARCHIVO); file = new FileInputStream(filePath.getPath()); prop.load(file); file.close(); } catch (IOException e) { LOG.error("# Error al leer el archivo de configuración", e); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "Propiedades"
"public Propiedades() { FileInputStream file = null; URL root = getClass().getProtectionDomain().getCodeSource() .getLocation(); URL filePath = null; prop = new Properties(); try { filePath = new URL(root, NOMBRE_ARCHIVO); prop.load(file); <MASK>file = new FileInputStream(filePath.getPath());</MASK> file.close(); } catch (IOException e) { LOG.error("# Error al leer el archivo de configuración", e); } }"
Inversion-Mutation
megadiff
"public final void disable() { disableModule(); synchronized (lock) { enabled = false; } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "disable"
"public final void disable() { synchronized (lock) { enabled = false; } <MASK>disableModule();</MASK> }"
Inversion-Mutation
megadiff
"private void addAction(final IAction action, Composite parent, boolean isQuick) { final ImageHyperlink link = toolkit.createImageHyperlink(parent, SWT.NONE); link.setImage(getActionImage(action)); if (isQuick) link.setToolTipText(action.getText()); else link.setText(action.getText()); link.addHyperlinkListener(new HyperlinkAdapter() { public void linkActivated(HyperlinkEvent e) { if (action instanceof ISpaceAction) { ISpaceAction spaceAction = (ISpaceAction) action; spaceAction.setSpace(space); if (((ToolConfiguration) spaceAction.getConfiguration()).isFixed()) { spaceAction.run(); close(); } else { RunActionDialog runActionDialog = new RunActionDialog(getParentShell(), getShell().getLocation(), spaceAction); close(); runActionDialog.open(); } } else { close(); action.run(); } } }); if (firstActionLink == null) firstActionLink = link; addArrowNavigation(link); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addAction"
"private void addAction(final IAction action, Composite parent, boolean isQuick) { final ImageHyperlink link = toolkit.createImageHyperlink(parent, SWT.NONE); link.setImage(getActionImage(action)); if (isQuick) link.setToolTipText(action.getText()); else link.setText(action.getText()); link.addHyperlinkListener(new HyperlinkAdapter() { public void linkActivated(HyperlinkEvent e) { if (action instanceof ISpaceAction) { ISpaceAction spaceAction = (ISpaceAction) action; spaceAction.setSpace(space); if (((ToolConfiguration) spaceAction.getConfiguration()).isFixed()) { <MASK>close();</MASK> spaceAction.run(); } else { RunActionDialog runActionDialog = new RunActionDialog(getParentShell(), getShell().getLocation(), spaceAction); <MASK>close();</MASK> runActionDialog.open(); } } else { <MASK>close();</MASK> action.run(); } } }); if (firstActionLink == null) firstActionLink = link; addArrowNavigation(link); }"
Inversion-Mutation
megadiff
"public void linkActivated(HyperlinkEvent e) { if (action instanceof ISpaceAction) { ISpaceAction spaceAction = (ISpaceAction) action; spaceAction.setSpace(space); if (((ToolConfiguration) spaceAction.getConfiguration()).isFixed()) { spaceAction.run(); close(); } else { RunActionDialog runActionDialog = new RunActionDialog(getParentShell(), getShell().getLocation(), spaceAction); close(); runActionDialog.open(); } } else { close(); action.run(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "linkActivated"
"public void linkActivated(HyperlinkEvent e) { if (action instanceof ISpaceAction) { ISpaceAction spaceAction = (ISpaceAction) action; spaceAction.setSpace(space); if (((ToolConfiguration) spaceAction.getConfiguration()).isFixed()) { <MASK>close();</MASK> spaceAction.run(); } else { RunActionDialog runActionDialog = new RunActionDialog(getParentShell(), getShell().getLocation(), spaceAction); <MASK>close();</MASK> runActionDialog.open(); } } else { <MASK>close();</MASK> action.run(); } }"
Inversion-Mutation
megadiff
"public void run() { final int size = imageloader.length; // as many as Preloader threads final ArrayList<Tuple> list = new ArrayList<Tuple>(size); while (go) { try { synchronized (lock2) { lock2.lock(); } // read out a group of imageloader.length patches to load while (true) { // block 1: pop out 'size' valid tuples from the queue (and all invalid in between as well) synchronized (lock) { lock.lock(); int len = queue.size(); //Utils.log2("@@@@@ Queue size: " + len); if (0 == len) { lock.unlock(); break; } // When more than a hundred images, multiply by 10 the remove/read -out batch for preloading. // (if the batch_size is too large, then the removing/invalidating tuples from the queue would not work properly, i.e. they would never get invalidated and thus they'd be preloaded unnecessarily.) final int batch_size = size * (len < 100 ? 1 : 10); // for (int i=0; i<batch_size && i<len; len--) { final Tuple tuple = queue.remove(len-1); // start removing from the end, since those are the latest additions, hence the ones the user wants to see immediately. removeMapping(tuple); if (!tuple.valid) { //Utils.log2("@@@@@ skipping invalid tuple"); continue; } list.add(tuple); i++; } //Utils.log2("@@@@@ Queue size after: " + queue.size()); lock.unlock(); } // changes may occur now to the queue, so work on the list //Utils.log2("@@@@@ list size: " + list.size()); // block 2: now iterate until each tuple in the list has been assigned to a preloader thread while (!list.isEmpty()) { final Iterator<Tuple> it = list.iterator(); while (it.hasNext()) { for (int i=0; i<imageloader.length; i++) { final Tuple tu = it.next(); if (!imageloader[i].isLoading()) { it.remove(); imageloader[i].load(tu.patch, tu.mag, tu.repaint); } } } if (!list.isEmpty()) try { //Utils.log2("@@@@@ list not empty, waiting 50 ms"); Thread.sleep(50); } catch (InterruptedException ie) {} } } } catch (Exception e) { e.printStackTrace(); synchronized (lock) { lock.unlock(); } // just in case ... } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"public void run() { final int size = imageloader.length; // as many as Preloader threads final ArrayList<Tuple> list = new ArrayList<Tuple>(size); while (go) { try { synchronized (lock2) { lock2.lock(); } // read out a group of imageloader.length patches to load while (true) { // block 1: pop out 'size' valid tuples from the queue (and all invalid in between as well) synchronized (lock) { lock.lock(); int len = queue.size(); //Utils.log2("@@@@@ Queue size: " + len); if (0 == len) { lock.unlock(); break; } // When more than a hundred images, multiply by 10 the remove/read -out batch for preloading. // (if the batch_size is too large, then the removing/invalidating tuples from the queue would not work properly, i.e. they would never get invalidated and thus they'd be preloaded unnecessarily.) final int batch_size = size * (len < 100 ? 1 : 10); // for (int i=0; i<batch_size && i<len; len--) { final Tuple tuple = queue.remove(len-1); // start removing from the end, since those are the latest additions, hence the ones the user wants to see immediately. removeMapping(tuple); if (!tuple.valid) { //Utils.log2("@@@@@ skipping invalid tuple"); continue; } list.add(tuple); i++; } //Utils.log2("@@@@@ Queue size after: " + queue.size()); lock.unlock(); } // changes may occur now to the queue, so work on the list //Utils.log2("@@@@@ list size: " + list.size()); // block 2: now iterate until each tuple in the list has been assigned to a preloader thread while (!list.isEmpty()) { final Iterator<Tuple> it = list.iterator(); while (it.hasNext()) { for (int i=0; i<imageloader.length; i++) { if (!imageloader[i].isLoading()) { <MASK>final Tuple tu = it.next();</MASK> it.remove(); imageloader[i].load(tu.patch, tu.mag, tu.repaint); } } } if (!list.isEmpty()) try { //Utils.log2("@@@@@ list not empty, waiting 50 ms"); Thread.sleep(50); } catch (InterruptedException ie) {} } } } catch (Exception e) { e.printStackTrace(); synchronized (lock) { lock.unlock(); } // just in case ... } } }"
Inversion-Mutation
megadiff
"private void initComponents() { setLayout(new GridBagLayout()); JLabel playerLabel = new JLabel(); if (isSubstitution()) { playerLabel.setText(HOVerwaltung.instance().getLanguageString( "subs.Out")); } else if (isPositionSwap()) { playerLabel.setText(HOVerwaltung.instance().getLanguageString( "subs.Reposition")); } else { playerLabel.setText(HOVerwaltung.instance().getLanguageString( "subs.Player")); } GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridx = 0; gbc.gridy = 0; gbc.anchor = GridBagConstraints.WEST; gbc.insets = new Insets(10, 10, 4, 2); add(playerLabel, gbc); this.playerComboBox = new JComboBox(); Dimension comboBoxSize = new Dimension(200, this.playerComboBox.getPreferredSize().height); this.playerComboBox.setMinimumSize(comboBoxSize); this.playerComboBox.setPreferredSize(comboBoxSize); gbc.gridx = 1; gbc.insets = new Insets(10, 2, 4, 10); add(this.playerComboBox, gbc); if (isSubstitution() || isPositionSwap()) { JLabel playerInLabel = new JLabel(); if (isSubstitution()) { playerInLabel.setText(HOVerwaltung.instance() .getLanguageString("subs.In")); } else { playerInLabel.setText(HOVerwaltung.instance() .getLanguageString("subs.RepositionWith")); } gbc.gridx = 0; gbc.gridy++; gbc.anchor = GridBagConstraints.WEST; gbc.insets = new Insets(4, 10, 4, 2); add(playerInLabel, gbc); this.playerInComboBox = new JComboBox(); this.playerInComboBox.setMinimumSize(comboBoxSize); this.playerInComboBox.setPreferredSize(comboBoxSize); gbc.gridx = 1; gbc.insets = new Insets(4, 2, 4, 10); add(this.playerInComboBox, gbc); } this.behaviourComboBox = new JComboBox(); if (!isPositionSwap()) { JLabel behaviourLabel = new JLabel(HOVerwaltung.instance() .getLanguageString("subs.Behavior")); gbc.gridx = 0; gbc.gridy++; gbc.anchor = GridBagConstraints.WEST; gbc.insets = new Insets(4, 10, 4, 2); add(behaviourLabel, gbc); this.behaviourComboBox.setMinimumSize(comboBoxSize); this.behaviourComboBox.setPreferredSize(comboBoxSize); gbc.gridx = 1; gbc.insets = new Insets(4, 2, 4, 10); add(this.behaviourComboBox, gbc); } JLabel whenLabel = new JLabel(HOVerwaltung.instance() .getLanguageString("subs.When")); gbc.gridx = 0; gbc.gridy++; gbc.insets = new Insets(4, 10, 4, 2); add(whenLabel, gbc); this.whenTextField = new WhenTextField(HOVerwaltung.instance() .getLanguageString("subs.MinuteAnytime"), HOVerwaltung .instance().getLanguageString("subs.MinuteAfterX")); Dimension textFieldSize = new Dimension(200, this.whenTextField.getPreferredSize().height); this.whenTextField.setMinimumSize(textFieldSize); this.whenTextField.setPreferredSize(textFieldSize); gbc.fill = GridBagConstraints.NONE; gbc.gridx = 1; gbc.insets = new Insets(4, 2, 4, 10); add(this.whenTextField, gbc); this.whenSlider = new JSlider(-1, 119, -1); this.whenSlider.setMinimumSize(new Dimension(this.whenTextField .getMinimumSize().width, this.whenSlider.getPreferredSize().height)); gbc.gridx = 1; gbc.gridy++; gbc.insets = new Insets(0, 2, 8, 10); add(this.whenSlider, gbc); gbc.gridx = 0; gbc.gridy++; gbc.gridwidth = 2; gbc.insets = new Insets(8, 4, 8, 4); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = 1.0; add(new Divider(HOVerwaltung.instance().getLanguageString( "subs.AdvancedConditions")), gbc); gbc.gridwidth = 1; gbc.weightx = 0.0; if (!isPositionSwap()) { JLabel positionLabel = new JLabel(HOVerwaltung.instance() .getLanguageString("subs.Position")); gbc.gridx = 0; gbc.gridy++; gbc.insets = new Insets(4, 10, 4, 2); add(positionLabel, gbc); this.positionComboBox = new JComboBox(); this.positionComboBox.setMinimumSize(comboBoxSize); this.positionComboBox.setPreferredSize(comboBoxSize); gbc.gridx = 1; gbc.insets = new Insets(4, 2, 4, 10); add(this.positionComboBox, gbc); this.positionChooser = new PositionChooser(); gbc.gridy++; gbc.insets = new Insets(2, 10, 8, 10); gbc.fill = GridBagConstraints.NONE; add(this.positionChooser, gbc); } JLabel redCardsLabel = new JLabel(HOVerwaltung.instance() .getLanguageString("subs.RedCard")); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridx = 0; gbc.gridy++; gbc.insets = new Insets(4, 10, 4, 2); add(redCardsLabel, gbc); this.redCardsComboBox = new JComboBox( SubstitutionDataProvider.getRedCardItems()); this.redCardsComboBox.setMinimumSize(comboBoxSize); this.redCardsComboBox.setPreferredSize(comboBoxSize); gbc.gridx = 1; gbc.insets = new Insets(4, 2, 4, 10); add(this.redCardsComboBox, gbc); JLabel standingLabel = new JLabel(HOVerwaltung.instance() .getLanguageString("subs.Standing")); gbc.gridx = 0; gbc.gridy++; gbc.insets = new Insets(4, 10, 4, 2); add(standingLabel, gbc); this.standingComboBox = new JComboBox( SubstitutionDataProvider.getStandingItems()); this.standingComboBox.setMinimumSize(comboBoxSize); this.standingComboBox.setPreferredSize(comboBoxSize); gbc.gridx = 1; gbc.insets = new Insets(4, 2, 4, 10); add(this.standingComboBox, gbc); // dummy to consume all extra space gbc.gridy++; gbc.weighty = 1.0; add(new JPanel(), gbc); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "initComponents"
"private void initComponents() { setLayout(new GridBagLayout()); JLabel playerLabel = new JLabel(); if (isSubstitution()) { playerLabel.setText(HOVerwaltung.instance().getLanguageString( "subs.Out")); } else if (isPositionSwap()) { playerLabel.setText(HOVerwaltung.instance().getLanguageString( "subs.Reposition")); } else { playerLabel.setText(HOVerwaltung.instance().getLanguageString( "subs.Player")); } GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridx = 0; gbc.gridy = 0; gbc.anchor = GridBagConstraints.WEST; gbc.insets = new Insets(10, 10, 4, 2); add(playerLabel, gbc); this.playerComboBox = new JComboBox(); Dimension comboBoxSize = new Dimension(200, this.playerComboBox.getPreferredSize().height); this.playerComboBox.setMinimumSize(comboBoxSize); this.playerComboBox.setPreferredSize(comboBoxSize); gbc.gridx = 1; gbc.insets = new Insets(10, 2, 4, 10); add(this.playerComboBox, gbc); if (isSubstitution() || isPositionSwap()) { JLabel playerInLabel = new JLabel(); if (isSubstitution()) { playerInLabel.setText(HOVerwaltung.instance() .getLanguageString("subs.In")); } else { playerInLabel.setText(HOVerwaltung.instance() .getLanguageString("subs.RepositionWith")); } gbc.gridx = 0; gbc.gridy++; gbc.anchor = GridBagConstraints.WEST; gbc.insets = new Insets(4, 10, 4, 2); add(playerInLabel, gbc); this.playerInComboBox = new JComboBox(); this.playerInComboBox.setMinimumSize(comboBoxSize); this.playerInComboBox.setPreferredSize(comboBoxSize); gbc.gridx = 1; gbc.insets = new Insets(4, 2, 4, 10); add(this.playerInComboBox, gbc); } if (!isPositionSwap()) { JLabel behaviourLabel = new JLabel(HOVerwaltung.instance() .getLanguageString("subs.Behavior")); gbc.gridx = 0; gbc.gridy++; gbc.anchor = GridBagConstraints.WEST; gbc.insets = new Insets(4, 10, 4, 2); add(behaviourLabel, gbc); <MASK>this.behaviourComboBox = new JComboBox();</MASK> this.behaviourComboBox.setMinimumSize(comboBoxSize); this.behaviourComboBox.setPreferredSize(comboBoxSize); gbc.gridx = 1; gbc.insets = new Insets(4, 2, 4, 10); add(this.behaviourComboBox, gbc); } JLabel whenLabel = new JLabel(HOVerwaltung.instance() .getLanguageString("subs.When")); gbc.gridx = 0; gbc.gridy++; gbc.insets = new Insets(4, 10, 4, 2); add(whenLabel, gbc); this.whenTextField = new WhenTextField(HOVerwaltung.instance() .getLanguageString("subs.MinuteAnytime"), HOVerwaltung .instance().getLanguageString("subs.MinuteAfterX")); Dimension textFieldSize = new Dimension(200, this.whenTextField.getPreferredSize().height); this.whenTextField.setMinimumSize(textFieldSize); this.whenTextField.setPreferredSize(textFieldSize); gbc.fill = GridBagConstraints.NONE; gbc.gridx = 1; gbc.insets = new Insets(4, 2, 4, 10); add(this.whenTextField, gbc); this.whenSlider = new JSlider(-1, 119, -1); this.whenSlider.setMinimumSize(new Dimension(this.whenTextField .getMinimumSize().width, this.whenSlider.getPreferredSize().height)); gbc.gridx = 1; gbc.gridy++; gbc.insets = new Insets(0, 2, 8, 10); add(this.whenSlider, gbc); gbc.gridx = 0; gbc.gridy++; gbc.gridwidth = 2; gbc.insets = new Insets(8, 4, 8, 4); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = 1.0; add(new Divider(HOVerwaltung.instance().getLanguageString( "subs.AdvancedConditions")), gbc); gbc.gridwidth = 1; gbc.weightx = 0.0; if (!isPositionSwap()) { JLabel positionLabel = new JLabel(HOVerwaltung.instance() .getLanguageString("subs.Position")); gbc.gridx = 0; gbc.gridy++; gbc.insets = new Insets(4, 10, 4, 2); add(positionLabel, gbc); this.positionComboBox = new JComboBox(); this.positionComboBox.setMinimumSize(comboBoxSize); this.positionComboBox.setPreferredSize(comboBoxSize); gbc.gridx = 1; gbc.insets = new Insets(4, 2, 4, 10); add(this.positionComboBox, gbc); this.positionChooser = new PositionChooser(); gbc.gridy++; gbc.insets = new Insets(2, 10, 8, 10); gbc.fill = GridBagConstraints.NONE; add(this.positionChooser, gbc); } JLabel redCardsLabel = new JLabel(HOVerwaltung.instance() .getLanguageString("subs.RedCard")); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridx = 0; gbc.gridy++; gbc.insets = new Insets(4, 10, 4, 2); add(redCardsLabel, gbc); this.redCardsComboBox = new JComboBox( SubstitutionDataProvider.getRedCardItems()); this.redCardsComboBox.setMinimumSize(comboBoxSize); this.redCardsComboBox.setPreferredSize(comboBoxSize); gbc.gridx = 1; gbc.insets = new Insets(4, 2, 4, 10); add(this.redCardsComboBox, gbc); JLabel standingLabel = new JLabel(HOVerwaltung.instance() .getLanguageString("subs.Standing")); gbc.gridx = 0; gbc.gridy++; gbc.insets = new Insets(4, 10, 4, 2); add(standingLabel, gbc); this.standingComboBox = new JComboBox( SubstitutionDataProvider.getStandingItems()); this.standingComboBox.setMinimumSize(comboBoxSize); this.standingComboBox.setPreferredSize(comboBoxSize); gbc.gridx = 1; gbc.insets = new Insets(4, 2, 4, 10); add(this.standingComboBox, gbc); // dummy to consume all extra space gbc.gridy++; gbc.weighty = 1.0; add(new JPanel(), gbc); }"
Inversion-Mutation
megadiff
"private void onTransitionEnd() { VConsole.log("Trs end"); new Timer() { @Override public void run() { VConsole.log("Place holder hide"); hidePlaceHolder(); } }.schedule(160); transitionPending = false; fireAnimationDidEnd(); if (pendingWidth != null) { setWidth(pendingWidth); pendingWidth = null; } for (Widget w : detachAfterAnimation) { if (w != null) { w.removeFromParent(); } } detachAfterAnimation.clear(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onTransitionEnd"
"private void onTransitionEnd() { VConsole.log("Trs end"); new Timer() { @Override public void run() { VConsole.log("Place holder hide"); hidePlaceHolder(); } }.schedule(160); <MASK>fireAnimationDidEnd();</MASK> transitionPending = false; if (pendingWidth != null) { setWidth(pendingWidth); pendingWidth = null; } for (Widget w : detachAfterAnimation) { if (w != null) { w.removeFromParent(); } } detachAfterAnimation.clear(); }"
Inversion-Mutation
megadiff
"public DefaultSearchResultButton(String name, String id, String clue) { super(name); this.name = name; this.id = id; this.clue = clue; this.setToolTipText(this.clue); this.addMouseListener(new MouseListener(){ public void mouseClicked(MouseEvent arg0) { System.out.println("Mouse Clicked on button: " + DefaultSearchResultButton.this.getText() + " " + DefaultSearchResultButton.this.name); searchSuggestionListener.resultChosen(new ActionEvent(DefaultSearchResultButton.this,0,DefaultSearchResultButton.this.getText())); } public void mouseEntered(MouseEvent arg0) { System.out.println("Mouse Entered over button: " + DefaultSearchResultButton.this.getText() + " " + DefaultSearchResultButton.this.name); if(searchSuggestionListener != null){ searchSuggestionListener.resultHovered(new ActionEvent(DefaultSearchResultButton.this,0,DefaultSearchResultButton.this.getToolTipText())); } } public void mouseExited(MouseEvent arg0) { System.out.println("Mouse Exited over button: " + DefaultSearchResultButton.this.getText() + " " + DefaultSearchResultButton.this.name); if(searchSuggestionListener != null){ searchSuggestionListener.resultNoLongerHovered(new ActionEvent(DefaultSearchResultButton.this,0,DefaultSearchResultButton.this.getToolTipText())); } } public void mousePressed(MouseEvent arg0) { } public void mouseReleased(MouseEvent arg0) { } }); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "DefaultSearchResultButton"
"public DefaultSearchResultButton(String name, String id, String clue) { super(name); this.name = name; this.id = id; <MASK>this.setToolTipText(this.clue);</MASK> this.clue = clue; this.addMouseListener(new MouseListener(){ public void mouseClicked(MouseEvent arg0) { System.out.println("Mouse Clicked on button: " + DefaultSearchResultButton.this.getText() + " " + DefaultSearchResultButton.this.name); searchSuggestionListener.resultChosen(new ActionEvent(DefaultSearchResultButton.this,0,DefaultSearchResultButton.this.getText())); } public void mouseEntered(MouseEvent arg0) { System.out.println("Mouse Entered over button: " + DefaultSearchResultButton.this.getText() + " " + DefaultSearchResultButton.this.name); if(searchSuggestionListener != null){ searchSuggestionListener.resultHovered(new ActionEvent(DefaultSearchResultButton.this,0,DefaultSearchResultButton.this.getToolTipText())); } } public void mouseExited(MouseEvent arg0) { System.out.println("Mouse Exited over button: " + DefaultSearchResultButton.this.getText() + " " + DefaultSearchResultButton.this.name); if(searchSuggestionListener != null){ searchSuggestionListener.resultNoLongerHovered(new ActionEvent(DefaultSearchResultButton.this,0,DefaultSearchResultButton.this.getToolTipText())); } } public void mousePressed(MouseEvent arg0) { } public void mouseReleased(MouseEvent arg0) { } }); }"
Inversion-Mutation
megadiff
"public FitSphere(final Vector3D[] points) { Vector3D mean = Vector3D.ZERO; for(Vector3D point : points) mean = mean.add(point.scalarMultiply(1D/(double)points.length)); ReportingUtils.logMessage("MEAN: " + mean.toString()); final Vector3D endMean = new Vector3D(mean.getX(), mean.getY(), mean.getZ()); double[] params = new double[PARAMLEN]; params[RADIUS] = 0.5*points[0].subtract(points[points.length-1]).getNorm(); Vector3D centerGuess = points[points.length/2].subtract(mean).add(mean.subtract(points[points.length/2]).normalize().scalarMultiply(params[RADIUS])); params[XC] = centerGuess.getX(); params[YC] = centerGuess.getY(); params[ZC] = centerGuess.getZ(); double[] steps = new double[PARAMLEN]; steps[XC] = steps[YC] = steps[ZC] = 0.001; steps[RADIUS] = 0.00001; ReportingUtils.logMessage("Initial parameters: " + Arrays.toString(params) + ", steps: " + Arrays.toString(steps)); MultivariateRealFunction MRF = new MultivariateRealFunction() { @Override public double value(double[] params) { Vector3D center = new Vector3D(params[XC], params[YC], params[ZC]); double err = 0; for(Vector3D point : points) err += Math.pow(point.subtract(endMean).subtract(center).getNorm() - params[RADIUS], 2D); // ReportingUtils.logMessage("value(" + Arrays.toString(params) + "): endMean=" + endMean.toString() + ", err=" + err); return err; } }; SimplexOptimizer opt = new SimplexOptimizer(1e-6, -1); NelderMeadSimplex nm = new NelderMeadSimplex(steps); opt.setSimplex(nm); double[] result = null; try { result = opt.optimize(5000000, MRF, GoalType.MINIMIZE, params).getPoint(); error = Math.sqrt(MRF.value(result)); } catch(Throwable t) { ReportingUtils.logError(t, "Optimization failed!"); } ReportingUtils.logMessage("Fit: " + Arrays.toString(result)); center = new Vector3D(result[XC], result[YC], result[ZC]).add(mean); radius = result[RADIUS]; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "FitSphere"
"public FitSphere(final Vector3D[] points) { Vector3D mean = Vector3D.ZERO; for(Vector3D point : points) mean = mean.add(point.scalarMultiply(1D/(double)points.length)); ReportingUtils.logMessage("MEAN: " + mean.toString()); final Vector3D endMean = new Vector3D(mean.getX(), mean.getY(), mean.getZ()); double[] params = new double[PARAMLEN]; params[RADIUS] = 0.5*points[0].subtract(points[points.length-1]).getNorm(); Vector3D centerGuess = points[points.length/2].subtract(mean).add(mean.subtract(points[points.length/2]).normalize().scalarMultiply(params[RADIUS])); params[XC] = centerGuess.getX(); params[YC] = centerGuess.getY(); params[ZC] = centerGuess.getZ(); double[] steps = new double[PARAMLEN]; steps[XC] = steps[YC] = steps[ZC] = 0.001; steps[RADIUS] = 0.00001; ReportingUtils.logMessage("Initial parameters: " + Arrays.toString(params) + ", steps: " + Arrays.toString(steps)); MultivariateRealFunction MRF = new MultivariateRealFunction() { @Override public double value(double[] params) { Vector3D center = new Vector3D(params[XC], params[YC], params[ZC]); double err = 0; for(Vector3D point : points) err += Math.pow(point.subtract(endMean).subtract(center).getNorm() - params[RADIUS], 2D); // ReportingUtils.logMessage("value(" + Arrays.toString(params) + "): endMean=" + endMean.toString() + ", err=" + err); return err; } }; SimplexOptimizer opt = new SimplexOptimizer(1e-6, -1); NelderMeadSimplex nm = new NelderMeadSimplex(steps); opt.setSimplex(nm); double[] result = null; try { result = opt.optimize(5000000, MRF, GoalType.MINIMIZE, params).getPoint(); } catch(Throwable t) { ReportingUtils.logError(t, "Optimization failed!"); } ReportingUtils.logMessage("Fit: " + Arrays.toString(result)); center = new Vector3D(result[XC], result[YC], result[ZC]).add(mean); radius = result[RADIUS]; <MASK>error = Math.sqrt(MRF.value(result));</MASK> }"
Inversion-Mutation
megadiff
"public static String emitJavascriptCall(String name, String[] arguments, boolean quote) { CharWrap togo = new CharWrap(); togo.append(" ").append(name).append('('); for (int i = 0; i < arguments.length; ++i) { if (quote) togo.append('"'); togo.append(arguments[i]); if (quote) togo.append('"'); if (i != arguments.length - 1) { togo.append(", "); } } togo.append(");\n"); return togo.toString(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "emitJavascriptCall"
"public static String emitJavascriptCall(String name, String[] arguments, boolean quote) { CharWrap togo = new CharWrap(); togo.append(" ").append(name).append('('); for (int i = 0; i < arguments.length; ++i) { <MASK>if (quote) togo.append('"');</MASK> togo.append(arguments[i]); if (i != arguments.length - 1) { togo.append(", "); } <MASK>if (quote) togo.append('"');</MASK> } togo.append(");\n"); return togo.toString(); }"
Inversion-Mutation
megadiff
"@Override public void click() { final Boolean newValue = (value == null) ? true : !value; setValue(newValue, true); super.click(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "click"
"@Override public void click() { <MASK>super.click();</MASK> final Boolean newValue = (value == null) ? true : !value; setValue(newValue, true); }"
Inversion-Mutation
megadiff
"public List<SecurityAuditEvent> getEvents(String username, Integer skipEvents, Integer numEvents, Date startTime, Date endTime) { List<SecurityAuditEvent> events = new ArrayList<SecurityAuditEvent>(); Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = GET_EVENTS; boolean addedOne = false; if (username != null) { sql += " WHERE username = ?"; addedOne = true; } if (startTime != null) { if (!addedOne) { sql += " WHERE"; } else { sql += " AND"; } sql += " entryStamp >= ?"; addedOne = true; } if (endTime != null) { if (!addedOne) { sql += " WHERE"; } else { sql += " AND"; } sql += " entryStamp <= ?"; } sql += " ORDER BY entryStamp DESC"; try { con = DbConnectionManager.getConnection(); pstmt = DbConnectionManager.createScrollablePreparedStatement(con, sql); rs = pstmt.executeQuery(); if (skipEvents != null) { DbConnectionManager.scrollResultSet(rs, skipEvents); } if (numEvents != null) { DbConnectionManager.setFetchSize(rs, numEvents); } int i = 1; if (username != null) { pstmt.setString(i, username); i++; } if (startTime != null) { pstmt.setLong(i, startTime.getTime()); i++; } if (endTime != null) { pstmt.setLong(i, endTime.getTime()); } int count = 0; while (rs.next() && count < numEvents) { SecurityAuditEvent event = new SecurityAuditEvent(); event.setMsgID(rs.getLong(1)); event.setUsername(rs.getString(2)); event.setEventStamp(new Date(rs.getLong(3))); event.setSummary(rs.getString(4)); event.setNode(rs.getString(5)); event.setDetails(rs.getString(6)); events.add(event); count++; } } catch (SQLException e) { Log.error(e.getMessage(), e); } finally { DbConnectionManager.closeConnection(rs, pstmt, con); } return events; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getEvents"
"public List<SecurityAuditEvent> getEvents(String username, Integer skipEvents, Integer numEvents, Date startTime, Date endTime) { List<SecurityAuditEvent> events = new ArrayList<SecurityAuditEvent>(); Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = GET_EVENTS; boolean addedOne = false; if (username != null) { sql += " WHERE username = ?"; addedOne = true; } if (startTime != null) { if (!addedOne) { sql += " WHERE"; } else { sql += " AND"; } sql += " entryStamp >= ?"; addedOne = true; } if (endTime != null) { if (!addedOne) { sql += " WHERE"; } else { sql += " AND"; } sql += " entryStamp <= ?"; } sql += " ORDER BY entryStamp DESC"; try { con = DbConnectionManager.getConnection(); pstmt = DbConnectionManager.createScrollablePreparedStatement(con, sql); if (skipEvents != null) { DbConnectionManager.scrollResultSet(rs, skipEvents); } if (numEvents != null) { DbConnectionManager.setFetchSize(rs, numEvents); } int i = 1; if (username != null) { pstmt.setString(i, username); i++; } if (startTime != null) { pstmt.setLong(i, startTime.getTime()); i++; } if (endTime != null) { pstmt.setLong(i, endTime.getTime()); } <MASK>rs = pstmt.executeQuery();</MASK> int count = 0; while (rs.next() && count < numEvents) { SecurityAuditEvent event = new SecurityAuditEvent(); event.setMsgID(rs.getLong(1)); event.setUsername(rs.getString(2)); event.setEventStamp(new Date(rs.getLong(3))); event.setSummary(rs.getString(4)); event.setNode(rs.getString(5)); event.setDetails(rs.getString(6)); events.add(event); count++; } } catch (SQLException e) { Log.error(e.getMessage(), e); } finally { DbConnectionManager.closeConnection(rs, pstmt, con); } return events; }"
Inversion-Mutation
megadiff
"private void resumeThread(boolean fireNotification) throws DebugException { if (!isSuspended() || (isPerformingEvaluation() && !isInvokingMethod())) { return; } try { setRunning(true); setSuspendedQuiet(false); if (fireNotification) { fireResumeEvent(DebugEvent.CLIENT_REQUEST); } preserveStackFrames(); getUnderlyingThread().resume(); } catch (VMDisconnectedException e) { disconnected(); } catch (RuntimeException e) { setRunning(false); fireSuspendEvent(DebugEvent.CLIENT_REQUEST); targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_resuming"), 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 "resumeThread"
"private void resumeThread(boolean fireNotification) throws DebugException { if (!isSuspended() || (isPerformingEvaluation() && !isInvokingMethod())) { return; } try { setRunning(true); setSuspendedQuiet(false); <MASK>preserveStackFrames();</MASK> if (fireNotification) { fireResumeEvent(DebugEvent.CLIENT_REQUEST); } getUnderlyingThread().resume(); } catch (VMDisconnectedException e) { disconnected(); } catch (RuntimeException e) { setRunning(false); fireSuspendEvent(DebugEvent.CLIENT_REQUEST); targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_resuming"), new String[] {e.toString()}), e); //$NON-NLS-1$ } }"
Inversion-Mutation
megadiff
"protected OrderByTableColumn[] createTableColumns() { OrderByTableColumn[] columns = new OrderByTableColumn[] { new OrderByTableColumn(USER_NAME_PROPERTY, USER_NAME_PROPERTY, USER_NAME_PROPERTY), new OrderByTableColumn(LAST_NAME_PROPERTY, LAST_NAME_PROPERTY, LAST_NAME_PROPERTY), new OrderByTableColumn(FIRST_NAME_PROPERTY, FIRST_NAME_PROPERTY, FIRST_NAME_PROPERTY), new OrderByTableColumn("aliases", "aliasesString") }; return columns; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createTableColumns"
"protected OrderByTableColumn[] createTableColumns() { OrderByTableColumn[] columns = new OrderByTableColumn[] { new OrderByTableColumn(USER_NAME_PROPERTY, USER_NAME_PROPERTY, USER_NAME_PROPERTY), <MASK>new OrderByTableColumn(FIRST_NAME_PROPERTY, FIRST_NAME_PROPERTY, FIRST_NAME_PROPERTY),</MASK> new OrderByTableColumn(LAST_NAME_PROPERTY, LAST_NAME_PROPERTY, LAST_NAME_PROPERTY), new OrderByTableColumn("aliases", "aliasesString") }; return columns; }"
Inversion-Mutation
megadiff
"public CHSNodeMap(ContentEntity n, int depth, ResourceDefinition rp) throws SDataException { String lock = ContentHostingService.AUTH_RESOURCE_HIDDEN; sessionManager = Kernel.sessionManager(); String userId = sessionManager.getCurrentSessionUserId(); boolean canSeeHidden = Kernel.securityService().unlock(userId, lock, n.getReference(), n.getGroups()); if (!canSeeHidden && !n.isAvailable()) { throw new SDataAccessException(403, "Permission denied on item"); } contentHostingService = Kernel.contentHostingService(); authZGroupService = Kernel.authzGroupService(); entityManager = Kernel.entityManager(); depth--; put("mixinNodeType", getMixinTypes(n)); put("properties", getProperties(n)); put("name", getName(n)); if (rp != null) { put("path", rp.getExternalPath(n.getId())); } put("permissions", getPermissions(n)); if (n instanceof ContentResource) { put("primaryNodeType", "nt:file"); addFile((ContentResource) n); } else { put("primaryNodeType", "nt:folder"); addFolder((ContentCollection)n, rp, depth); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "CHSNodeMap"
"public CHSNodeMap(ContentEntity n, int depth, ResourceDefinition rp) throws SDataException { String lock = ContentHostingService.AUTH_RESOURCE_HIDDEN; String userId = sessionManager.getCurrentSessionUserId(); boolean canSeeHidden = Kernel.securityService().unlock(userId, lock, n.getReference(), n.getGroups()); if (!canSeeHidden && !n.isAvailable()) { throw new SDataAccessException(403, "Permission denied on item"); } contentHostingService = Kernel.contentHostingService(); authZGroupService = Kernel.authzGroupService(); entityManager = Kernel.entityManager(); <MASK>sessionManager = Kernel.sessionManager();</MASK> depth--; put("mixinNodeType", getMixinTypes(n)); put("properties", getProperties(n)); put("name", getName(n)); if (rp != null) { put("path", rp.getExternalPath(n.getId())); } put("permissions", getPermissions(n)); if (n instanceof ContentResource) { put("primaryNodeType", "nt:file"); addFile((ContentResource) n); } else { put("primaryNodeType", "nt:folder"); addFolder((ContentCollection)n, rp, depth); } }"
Inversion-Mutation
megadiff
"public JspHelper() { fsn = FSNamesystem.getFSNamesystem(); if (DataNode.getDataNode() != null) { nameNodeAddr = DataNode.getDataNode().getNameNodeAddr(); } else { nameNodeAddr = fsn.getDFSNameNodeAddress(); } UnixUserGroupInformation.saveToConf(conf, UnixUserGroupInformation.UGI_PROPERTY_NAME, webUGI); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "JspHelper"
"public JspHelper() { if (DataNode.getDataNode() != null) { nameNodeAddr = DataNode.getDataNode().getNameNodeAddr(); } else { <MASK>fsn = FSNamesystem.getFSNamesystem();</MASK> nameNodeAddr = fsn.getDFSNameNodeAddress(); } UnixUserGroupInformation.saveToConf(conf, UnixUserGroupInformation.UGI_PROPERTY_NAME, webUGI); }"
Inversion-Mutation
megadiff
"@Override protected void onCreate(Bundle savedInstanceState) { ThemeService.applyTheme(this); super.onCreate(savedInstanceState); DependencyInjectionService.getInstance().inject(this); int contentView = getContentView(); if (contentView == R.layout.task_list_wrapper_activity) swipeEnabled = true; setContentView(contentView); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); actionBar.setCustomView(getHeaderView()); listsNav = actionBar.getCustomView().findViewById(R.id.lists_nav); listsNavDisclosure = (ImageView) actionBar.getCustomView().findViewById(R.id.list_disclosure_arrow); lists = (TextView) actionBar.getCustomView().findViewById(R.id.list_title); mainMenu = (ImageView) actionBar.getCustomView().findViewById(R.id.main_menu); personStatus = (TextView) actionBar.getCustomView().findViewById(R.id.person_image); commentsButton = (Button) actionBar.getCustomView().findViewById(R.id.comments); if (ThemeService.getUnsimplifiedTheme() == R.style.Theme_White_Alt) commentsButton.setTextColor(getResources().getColor(R.color.blue_theme_color)); initializeFragments(actionBar); createMainMenuPopover(); mainMenu.setOnClickListener(mainMenuClickListener); commentsButton.setOnClickListener(commentsButtonClickListener); personStatus.setOnClickListener(friendStatusClickListener); Bundle extras = getIntent().getExtras(); if (extras != null) extras = (Bundle) extras.clone(); if (extras == null) extras = new Bundle(); Filter savedFilter = getIntent().getParcelableExtra(TaskListFragment.TOKEN_FILTER); if (Intent.ACTION_SEARCH.equals(getIntent().getAction())) { String query = getIntent().getStringExtra(SearchManager.QUERY).trim(); String title = getString(R.string.FLA_search_filter, query); savedFilter = new Filter(title, title, new QueryTemplate().where(Task.TITLE.like( "%" + //$NON-NLS-1$ query + "%")), //$NON-NLS-1$ null); } if (savedFilter == null) { savedFilter = getDefaultFilter(); extras.putAll(configureIntentAndExtrasWithFilter(getIntent(), savedFilter)); } extras.putParcelable(TaskListFragment.TOKEN_FILTER, savedFilter); if (swipeIsEnabled()) { setupPagerAdapter(); } setupTasklistFragmentWithFilter(savedFilter, extras); if (savedFilter != null) setListsTitle(savedFilter.title); if (getIntent().hasExtra(TOKEN_SOURCE)) { trackActivitySource(); } // Have to call this here because sometimes StartupService // isn't called (i.e. if the app was silently alive in the background) abTestEventReportingService.trackUserRetention(this); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCreate"
"@Override protected void onCreate(Bundle savedInstanceState) { <MASK>super.onCreate(savedInstanceState);</MASK> ThemeService.applyTheme(this); DependencyInjectionService.getInstance().inject(this); int contentView = getContentView(); if (contentView == R.layout.task_list_wrapper_activity) swipeEnabled = true; setContentView(contentView); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); actionBar.setCustomView(getHeaderView()); listsNav = actionBar.getCustomView().findViewById(R.id.lists_nav); listsNavDisclosure = (ImageView) actionBar.getCustomView().findViewById(R.id.list_disclosure_arrow); lists = (TextView) actionBar.getCustomView().findViewById(R.id.list_title); mainMenu = (ImageView) actionBar.getCustomView().findViewById(R.id.main_menu); personStatus = (TextView) actionBar.getCustomView().findViewById(R.id.person_image); commentsButton = (Button) actionBar.getCustomView().findViewById(R.id.comments); if (ThemeService.getUnsimplifiedTheme() == R.style.Theme_White_Alt) commentsButton.setTextColor(getResources().getColor(R.color.blue_theme_color)); initializeFragments(actionBar); createMainMenuPopover(); mainMenu.setOnClickListener(mainMenuClickListener); commentsButton.setOnClickListener(commentsButtonClickListener); personStatus.setOnClickListener(friendStatusClickListener); Bundle extras = getIntent().getExtras(); if (extras != null) extras = (Bundle) extras.clone(); if (extras == null) extras = new Bundle(); Filter savedFilter = getIntent().getParcelableExtra(TaskListFragment.TOKEN_FILTER); if (Intent.ACTION_SEARCH.equals(getIntent().getAction())) { String query = getIntent().getStringExtra(SearchManager.QUERY).trim(); String title = getString(R.string.FLA_search_filter, query); savedFilter = new Filter(title, title, new QueryTemplate().where(Task.TITLE.like( "%" + //$NON-NLS-1$ query + "%")), //$NON-NLS-1$ null); } if (savedFilter == null) { savedFilter = getDefaultFilter(); extras.putAll(configureIntentAndExtrasWithFilter(getIntent(), savedFilter)); } extras.putParcelable(TaskListFragment.TOKEN_FILTER, savedFilter); if (swipeIsEnabled()) { setupPagerAdapter(); } setupTasklistFragmentWithFilter(savedFilter, extras); if (savedFilter != null) setListsTitle(savedFilter.title); if (getIntent().hasExtra(TOKEN_SOURCE)) { trackActivitySource(); } // Have to call this here because sometimes StartupService // isn't called (i.e. if the app was silently alive in the background) abTestEventReportingService.trackUserRetention(this); }"
Inversion-Mutation
megadiff
"public void readConfigFromFile(final File file) { try { pipe.readFromFile(file); } catch (final IOException exc) { Log.error(exc); } catch (final PipeException exc) { Log.error(exc); } updatePipeLabel(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "readConfigFromFile"
"public void readConfigFromFile(final File file) { try { pipe.readFromFile(file); <MASK>updatePipeLabel();</MASK> } catch (final IOException exc) { Log.error(exc); } catch (final PipeException exc) { Log.error(exc); } }"
Inversion-Mutation
megadiff
"public void run() { // should be while game is not over try { // get the multicast group InetAddress group = InetAddress.getByName(MCAST_ADDRESS); socket.joinGroup(group); while (moreQuotes) { byte[] buf = new byte[6]; // receive request DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); buf = packet.getData(); // update the server address // get the packet type and data int packetType = buf[0] & 0xFF; //System.out.println("PACKET("+packetType+")");//,"+data1+","+data2+","+data3+"): "); if( Client.isPlaying && packet.getAddress().equals(Client.address) ) { if( PType.PPOS.ordinal() == packetType ) { int xpos = 100*( (int)(buf[1]&0x000000FF) ) + ( (int)(buf[2]&0x000000FF) ); int ypos = 100*( (int)(buf[3]&0x000000FF) ) + ( (int)(buf[4]&0x000000FF) ); GameState.getInstance().getPacMan().position( xpos, ypos ); } else if( PType.GPOS.ordinal() == packetType ) { int xpos = 100*( (int)(buf[2]&0x000000FF) ) + ( (int)(buf[3]&0x000000FF) ); int ypos = 100*( (int)(buf[4]&0x000000FF) ) + ( (int)(buf[5]&0x000000FF) ); GhostType gtype = GhostType.BLINKY; switch( (buf[1] & 0x000000FF )) { case 0://blinky gtype = GhostType.BLINKY; break; case 1://clyde gtype = GhostType.CLYDE; break; case 2://inky gtype = GhostType.INKY; break; case 3://pinky gtype = GhostType.PINKY; break; } // update the position GameState.getInstance().getGhosts().getObjectAt( capitalize(gtype.name()) ).position( xpos, ypos); } else if( PType.PILLD.ordinal() == packetType ) { //destroy pill int x = 100*((int)(buf[1]&0xFF)) + ((int)(buf[2]&0xFF)); int y = 100*((int)(buf[3]&0xFF)) + ((int)(buf[4]&0xFF)); //Pill pill = new Pill(x,y); GameState.getInstance().getPills().destroy(x,y);//pill); } else if( PType.PILLA.ordinal() == packetType ) { // add a pill int x = 100*((int)(buf[1]&0xFF)) + ((int)(buf[2]&0xFF)); int y = 100*((int)(buf[3]&0xFF)) + ((int)(buf[4]&0xFF)); GameState.getInstance().getPills().addArtifact(x, y); } else if( PType.PPILLD.ordinal() == packetType ) { // delete power pill int x = 100*((int)(buf[1]&0xFF)) + ((int)(buf[2]&0xFF)); int y = 100*((int)(buf[3]&0xFF)) + ((int)(buf[4]&0xFF)); //PowerPellet pellet = new PowerPellet(x,y); GameState.getInstance().getPellets().destroy(x, y);//pellet); } else if( PType.PPILLA.ordinal() == packetType ) { // add powerpill int x = 100*((int)(buf[1]&0xFF)) + ((int)(buf[2]&0xFF)); int y = 100*((int)(buf[3]&0xFF)) + ((int)(buf[4]&0xFF)); GameState.getInstance().getPellets().addArtifact(x, y); } else if( PType.LIVES.ordinal() == packetType ) { // set lives count int lives = (buf[1]&0xFF); GameState.getInstance().setLives( lives ); } else if( PType.AFRUIT.ordinal() == packetType ) { int initialScore = 0; int x = 100*((int)(buf[1]&0xFF)) + ((int)(buf[2]&0xFF)); int y = 100*((int)(buf[3]&0xFF)) + ((int)(buf[4]&0xFF)); Fruit fruit = new Fruit(x,y,initialScore); GameState.getInstance().setFruit(fruit); GameState.getInstance().getFruit().draw(); } else if( PType.DFRUIT.ordinal() == packetType ) { //int x = 100*((int)(buf[1]&0xFF)) + ((int)(buf[2]&0xFF)); //int y = 100*((int)(buf[3]&0xFF)) + ((int)(buf[4]&0xFF)); GameState.getInstance().getFruit().hide(); } /*else if( PType.LEVEL.ordinal() == packetType ) { // set current level GameState.getInstance().setLevel( (buf[1]&0xFF) ); // TODO: we need to actually change the level, if it is not the current }*/ else if(PType.DGHOST.ordinal() == packetType ) { Collection<Ghost> c = GameState.getInstance().getGhosts().getObjects(); for(Ghost g : c) { g.scatter(); } } else if(PType.AGHOST.ordinal()== packetType ) { Collection<Ghost> c = GameState.getInstance().getGhosts().getObjects(); for(Ghost g : c) { g.unScatter(); } } else if( PType.GMOVE.ordinal() == packetType ) { // another ghost moved. (We may or may not use this to also update the current player as consistency) GhostType gtype = GhostType.BLINKY; Direction dir = Direction.UP; // get direction switch( (buf[1] & 0xFF )) { case 0://up dir = Direction.UP; break; case 1://down dir = Direction.DOWN; break; case 2://left dir = Direction.LEFT; break; case 3://right dir = Direction.RIGHT; break; } // get the ghost switch( (buf[2] & 0xFF )) { case 0://blinky gtype = GhostType.BLINKY; break; case 1://clyde gtype = GhostType.CLYDE; break; case 2://inky gtype = GhostType.INKY; break; case 3://pinky gtype = GhostType.PINKY; break; } // move the ghost GameState.getInstance().getGhosts().getObjectAt( capitalize(gtype.name()) ).setDirection(dir); } else if( PType.PMOVE.ordinal() == packetType ) { // pacman made a move Direction dir = Direction.UP; // what direction did he move? switch( (buf[1] & 0x000000FF )) { case 0://up dir = Direction.UP; break; case 1://down dir = Direction.DOWN; break; case 2://left dir = Direction.LEFT; break; case 3://right dir = Direction.RIGHT; break; } // set the direction GameController.getInstance().setPacManDirection(dir); } else if( PType.JOIN.ordinal() == packetType ) { // notify us that another ghost has joined // readd them to the board or something // what ghost just joined? switch( (buf[1] & 0x000000FF )) { case 0://blinky joined break; case 1:// clyde joined break; case 2:// inky joined break; case 3:// pinky joined break; } // TODO: add them for the client } else if( PType.LEAVE.ordinal() == packetType ) { // notify that a ghost has left the game // if the ghost type is the same as the client, then client drops out. if( (buf[1]&0x000000FF)==Client.ghostType.ordinal() ) { // the ghost leaving is the current player moreQuotes = false; System.out.println("You were dropped from the server, or you just left."); break; } else { // someone else is leaving // TODO: Process the drop } } else if( PType.SCORE.ordinal() == packetType ) { // receive a score update int newScore = 100*( (int)(buf[1]&0x000000FF) ) + ( (int)(buf[2]&0x000000FF) ); GameState.getInstance().setScore(newScore); } else if( PType.GAMEOVER.ordinal() == packetType ) { // game ended moreQuotes = false; GameController.getInstance().getPacInstance().showGameOverScreen(); } } else if( !Client.isPlaying ) { if( PType.SPOTFREE.ordinal() == packetType && !Client.isPlaying ) { // tells the player that a spot is open on the server switch( (buf[1] & 0x000000FF )) { case 0://blinky Client.ghostType = GhostType.BLINKY; break; case 1://clyde Client.ghostType = GhostType.CLYDE; break; case 2://inky Client.ghostType = GhostType.INKY; break; case 3://p Client.ghostType = GhostType.PINKY; break; } Client.isPlaying = true; // Force the server address Client.address = packet.getAddress(); System.out.println("Joining game on "+Client.address.getHostAddress()+", playing as "+Client.ghostType.name() ); // notify the server we are joinging joinGame(); // setup the player or something, go hooray? GameController.getInstance().startGame(); GameController.getInstance().getPacInstance().showGameScreen(); // set the ghosts direction GameState.getInstance().getGhosts().getObjectAt(capitalize(Client.ghostType.name())).setDirection(Direction.UP); } } } socket.leaveGroup(group); socket.close(); System.exit(0); } catch(Exception e) { e.printStackTrace(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"public void run() { // should be while game is not over try { // get the multicast group InetAddress group = InetAddress.getByName(MCAST_ADDRESS); socket.joinGroup(group); while (moreQuotes) { byte[] buf = new byte[6]; // receive request DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); buf = packet.getData(); // update the server address // get the packet type and data int packetType = buf[0] & 0xFF; //System.out.println("PACKET("+packetType+")");//,"+data1+","+data2+","+data3+"): "); if( Client.isPlaying && packet.getAddress().equals(Client.address) ) { if( PType.PPOS.ordinal() == packetType ) { int xpos = 100*( (int)(buf[1]&0x000000FF) ) + ( (int)(buf[2]&0x000000FF) ); int ypos = 100*( (int)(buf[3]&0x000000FF) ) + ( (int)(buf[4]&0x000000FF) ); GameState.getInstance().getPacMan().position( xpos, ypos ); } else if( PType.GPOS.ordinal() == packetType ) { int xpos = 100*( (int)(buf[2]&0x000000FF) ) + ( (int)(buf[3]&0x000000FF) ); int ypos = 100*( (int)(buf[4]&0x000000FF) ) + ( (int)(buf[5]&0x000000FF) ); GhostType gtype = GhostType.BLINKY; switch( (buf[1] & 0x000000FF )) { case 0://blinky gtype = GhostType.BLINKY; break; case 1://clyde gtype = GhostType.CLYDE; break; case 2://inky gtype = GhostType.INKY; break; case 3://pinky gtype = GhostType.PINKY; break; } // update the position GameState.getInstance().getGhosts().getObjectAt( capitalize(gtype.name()) ).position( xpos, ypos); } else if( PType.PILLD.ordinal() == packetType ) { //destroy pill int x = 100*((int)(buf[1]&0xFF)) + ((int)(buf[2]&0xFF)); int y = 100*((int)(buf[3]&0xFF)) + ((int)(buf[4]&0xFF)); //Pill pill = new Pill(x,y); GameState.getInstance().getPills().destroy(x,y);//pill); } else if( PType.PILLA.ordinal() == packetType ) { // add a pill int x = 100*((int)(buf[1]&0xFF)) + ((int)(buf[2]&0xFF)); int y = 100*((int)(buf[3]&0xFF)) + ((int)(buf[4]&0xFF)); GameState.getInstance().getPills().addArtifact(x, y); } else if( PType.PPILLD.ordinal() == packetType ) { // delete power pill int x = 100*((int)(buf[1]&0xFF)) + ((int)(buf[2]&0xFF)); int y = 100*((int)(buf[3]&0xFF)) + ((int)(buf[4]&0xFF)); //PowerPellet pellet = new PowerPellet(x,y); GameState.getInstance().getPellets().destroy(x, y);//pellet); } else if( PType.PPILLA.ordinal() == packetType ) { // add powerpill int x = 100*((int)(buf[1]&0xFF)) + ((int)(buf[2]&0xFF)); int y = 100*((int)(buf[3]&0xFF)) + ((int)(buf[4]&0xFF)); GameState.getInstance().getPellets().addArtifact(x, y); } else if( PType.LIVES.ordinal() == packetType ) { // set lives count int lives = (buf[1]&0xFF); GameState.getInstance().setLives( lives ); } else if( PType.AFRUIT.ordinal() == packetType ) { int initialScore = 0; int x = 100*((int)(buf[1]&0xFF)) + ((int)(buf[2]&0xFF)); int y = 100*((int)(buf[3]&0xFF)) + ((int)(buf[4]&0xFF)); Fruit fruit = new Fruit(x,y,initialScore); GameState.getInstance().setFruit(fruit); GameState.getInstance().getFruit().draw(); } else if( PType.DFRUIT.ordinal() == packetType ) { //int x = 100*((int)(buf[1]&0xFF)) + ((int)(buf[2]&0xFF)); //int y = 100*((int)(buf[3]&0xFF)) + ((int)(buf[4]&0xFF)); GameState.getInstance().getFruit().hide(); } /*else if( PType.LEVEL.ordinal() == packetType ) { // set current level GameState.getInstance().setLevel( (buf[1]&0xFF) ); // TODO: we need to actually change the level, if it is not the current }*/ else if(PType.DGHOST.ordinal() == packetType ) { Collection<Ghost> c = GameState.getInstance().getGhosts().getObjects(); for(Ghost g : c) { g.scatter(); } } else if(PType.AGHOST.ordinal()== packetType ) { Collection<Ghost> c = GameState.getInstance().getGhosts().getObjects(); for(Ghost g : c) { g.unScatter(); } } else if( PType.GMOVE.ordinal() == packetType ) { // another ghost moved. (We may or may not use this to also update the current player as consistency) GhostType gtype = GhostType.BLINKY; Direction dir = Direction.UP; // get direction switch( (buf[1] & 0xFF )) { case 0://up dir = Direction.UP; break; case 1://down dir = Direction.DOWN; break; case 2://left dir = Direction.LEFT; break; case 3://right dir = Direction.RIGHT; break; } // get the ghost switch( (buf[2] & 0xFF )) { case 0://blinky gtype = GhostType.BLINKY; break; case 1://clyde gtype = GhostType.CLYDE; break; case 2://inky gtype = GhostType.INKY; break; case 3://pinky gtype = GhostType.PINKY; break; } // move the ghost GameState.getInstance().getGhosts().getObjectAt( capitalize(gtype.name()) ).setDirection(dir); } else if( PType.PMOVE.ordinal() == packetType ) { // pacman made a move Direction dir = Direction.UP; // what direction did he move? switch( (buf[1] & 0x000000FF )) { case 0://up dir = Direction.UP; break; case 1://down dir = Direction.DOWN; break; case 2://left dir = Direction.LEFT; break; case 3://right dir = Direction.RIGHT; break; } // set the direction GameController.getInstance().setPacManDirection(dir); } else if( PType.JOIN.ordinal() == packetType ) { // notify us that another ghost has joined // readd them to the board or something // what ghost just joined? switch( (buf[1] & 0x000000FF )) { case 0://blinky joined break; case 1:// clyde joined break; case 2:// inky joined break; case 3:// pinky joined break; } // TODO: add them for the client } else if( PType.LEAVE.ordinal() == packetType ) { // notify that a ghost has left the game // if the ghost type is the same as the client, then client drops out. if( (buf[1]&0x000000FF)==Client.ghostType.ordinal() ) { // the ghost leaving is the current player moreQuotes = false; System.out.println("You were dropped from the server, or you just left."); break; } else { // someone else is leaving // TODO: Process the drop } } else if( PType.SCORE.ordinal() == packetType ) { // receive a score update int newScore = 100*( (int)(buf[1]&0x000000FF) ) + ( (int)(buf[2]&0x000000FF) ); GameState.getInstance().setScore(newScore); } else if( PType.GAMEOVER.ordinal() == packetType ) { // game ended moreQuotes = false; GameController.getInstance().getPacInstance().showGameOverScreen(); } } else if( !Client.isPlaying ) { if( PType.SPOTFREE.ordinal() == packetType && !Client.isPlaying ) { // tells the player that a spot is open on the server switch( (buf[1] & 0x000000FF )) { case 0://blinky Client.ghostType = GhostType.BLINKY; break; case 1://clyde Client.ghostType = GhostType.CLYDE; break; case 2://inky Client.ghostType = GhostType.INKY; break; case 3://p Client.ghostType = GhostType.PINKY; break; } Client.isPlaying = true; <MASK>System.out.println("Joining game on "+Client.address.getHostAddress()+", playing as "+Client.ghostType.name() );</MASK> // Force the server address Client.address = packet.getAddress(); // notify the server we are joinging joinGame(); // setup the player or something, go hooray? GameController.getInstance().startGame(); GameController.getInstance().getPacInstance().showGameScreen(); // set the ghosts direction GameState.getInstance().getGhosts().getObjectAt(capitalize(Client.ghostType.name())).setDirection(Direction.UP); } } } socket.leaveGroup(group); socket.close(); System.exit(0); } catch(Exception e) { e.printStackTrace(); } }"
Inversion-Mutation
megadiff
"@Override public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception { if (args.length < 1 || args.length > 2) { sender.sendMessage("Usage: /" + commandLabel + " [player] [jailname]"); return; } User p; try { p = User.get(server.matchPlayer(args[0]).get(0)); } catch (Exception ex) { sender.sendMessage("§cThat player does not exist."); return; } if (p.isOp() || p.isAuthorized("essentials.jail.exempt")) { sender.sendMessage("§cYou may not jail that person"); return; } if (args.length == 2 && !p.isJailed()) { User.charge(sender, this); sender.sendMessage("§7Player " + p.getName() + " " + (p.toggleJailed() ? "jailed." : "unjailed.")); p.sendMessage("§7You have been jailed"); Essentials.getJail().sendToJail(p, args[1]); p.currentJail = (args[1]); return; } if (args.length == 2 && p.isJailed() && !args[1].equalsIgnoreCase(p.currentJail)) { sender.sendMessage("§cPerson is already in jail "+ p.currentJail); return; } if (args.length == 1 || (args.length == 2 && args[1].equalsIgnoreCase(p.currentJail))) { if (!p.isJailed()) { sender.sendMessage("Usage: /" + commandLabel + " [player] [jailname]"); return; } sender.sendMessage("§7Player " + p.getName() + " " + (p.toggleJailed() ? "jailed." : "unjailed.")); p.sendMessage("§7You have been released"); p.currentJail = ""; p.teleportBack(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"@Override public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception { if (args.length < 1 || args.length > 2) { sender.sendMessage("Usage: /" + commandLabel + " [player] [jailname]"); return; } User p; try { p = User.get(server.matchPlayer(args[0]).get(0)); } catch (Exception ex) { sender.sendMessage("§cThat player does not exist."); return; } if (p.isOp() || p.isAuthorized("essentials.jail.exempt")) { sender.sendMessage("§cYou may not jail that person"); return; } if (args.length == 2 && !p.isJailed()) { User.charge(sender, this); sender.sendMessage("§7Player " + p.getName() + " " + (p.toggleJailed() ? "jailed." : "unjailed.")); p.sendMessage("§7You have been jailed"); Essentials.getJail().sendToJail(p, args[1]); p.currentJail = (args[1]); return; } if (args.length == 2 && p.isJailed() && !args[1].equalsIgnoreCase(p.currentJail)) { sender.sendMessage("§cPerson is already in jail "+ p.currentJail); return; } if (args.length == 1 || (args.length == 2 && args[1].equalsIgnoreCase(p.currentJail))) { if (!p.isJailed()) { sender.sendMessage("Usage: /" + commandLabel + " [player] [jailname]"); return; } sender.sendMessage("§7Player " + p.getName() + " " + (p.toggleJailed() ? "jailed." : "unjailed.")); p.sendMessage("§7You have been released"); <MASK>p.teleportBack();</MASK> p.currentJail = ""; } }"
Inversion-Mutation
megadiff
"public void unload() throws IOException, InterruptedException { synchronized (indexMutex) { if( pageFile.isLoaded() ) { metadata.state = CLOSED_STATE; metadata.firstInProgressTransactionLocation = getFirstInProgressTxLocation(); pageFile.tx().execute(new Transaction.Closure<IOException>() { public void execute(Transaction tx) throws IOException { tx.store(metadata.page, metadataMarshaller, true); } }); } } close(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "unload"
"public void unload() throws IOException, InterruptedException { synchronized (indexMutex) { if( pageFile.isLoaded() ) { metadata.state = CLOSED_STATE; metadata.firstInProgressTransactionLocation = getFirstInProgressTxLocation(); pageFile.tx().execute(new Transaction.Closure<IOException>() { public void execute(Transaction tx) throws IOException { tx.store(metadata.page, metadataMarshaller, true); } }); <MASK>close();</MASK> } } }"
Inversion-Mutation
megadiff
"private Pretty(CompilationInfo info, String text, TokenSequence<JFXTokenId> tokens, JavaFXTreePath path, CodeStyle cs, int startOffset, int endOffset) { this.doc = info.getDocument(); this.root = path.getCompilationUnit(); this.fText = text; this.sp = info.getTrees().getSourcePositions(); this.cs = cs; this.rightMargin = cs.getRightMargin(); this.tabSize = cs.getTabSize(); this.indentSize = cs.getIndentSize(); this.continuationIndentSize = cs.getContinuationIndentSize(); this.expandTabToSpaces = cs.expandTabToSpaces(); this.wrapDepth = 0; this.lastBlankLines = -1; this.lastBlankLinesTokenIndex = -1; this.lastBlankLinesDiff = null; Tree tree = path.getLeaf(); this.indent = tokens != null ? getIndentLevel(tokens, path) : 0; this.col = this.indent; this.tokens = tokens; if (tree.getJavaFXKind() == JavaFXKind.COMPILATION_UNIT) { tokens.moveEnd(); tokens.movePrevious(); } else { tokens.move((int) getEndPos(tree)); if (!tokens.moveNext()) { tokens.movePrevious(); } } this.endPos = tokens.offset(); if (tree.getJavaFXKind() == JavaFXKind.COMPILATION_UNIT) { tokens.moveStart(); } else { tokens.move((int) sp.getStartPosition(path.getCompilationUnit(), tree)); } tokens.moveNext(); this.startOffset = startOffset; this.endOffset = endOffset; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "Pretty"
"private Pretty(CompilationInfo info, String text, TokenSequence<JFXTokenId> tokens, JavaFXTreePath path, CodeStyle cs, int startOffset, int endOffset) { this.doc = info.getDocument(); this.fText = text; this.sp = info.getTrees().getSourcePositions(); this.cs = cs; this.rightMargin = cs.getRightMargin(); this.tabSize = cs.getTabSize(); this.indentSize = cs.getIndentSize(); this.continuationIndentSize = cs.getContinuationIndentSize(); this.expandTabToSpaces = cs.expandTabToSpaces(); this.wrapDepth = 0; this.lastBlankLines = -1; this.lastBlankLinesTokenIndex = -1; this.lastBlankLinesDiff = null; Tree tree = path.getLeaf(); this.indent = tokens != null ? getIndentLevel(tokens, path) : 0; this.col = this.indent; this.tokens = tokens; if (tree.getJavaFXKind() == JavaFXKind.COMPILATION_UNIT) { tokens.moveEnd(); tokens.movePrevious(); } else { tokens.move((int) getEndPos(tree)); if (!tokens.moveNext()) { tokens.movePrevious(); } } this.endPos = tokens.offset(); if (tree.getJavaFXKind() == JavaFXKind.COMPILATION_UNIT) { tokens.moveStart(); } else { tokens.move((int) sp.getStartPosition(path.getCompilationUnit(), tree)); } tokens.moveNext(); <MASK>this.root = path.getCompilationUnit();</MASK> this.startOffset = startOffset; this.endOffset = endOffset; }"
Inversion-Mutation
megadiff
"@Override public void onEnable() { instance = this; configManager = new ConfigManager(); groupMediator = new GroupMediator(); jaLogger = new JukeAlertLogger(); snitchManager = new SnitchManager(); registerEvents(); registerCommands(); snitchManager.loadSnitches(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onEnable"
"@Override public void onEnable() { instance = this; configManager = new ConfigManager(); jaLogger = new JukeAlertLogger(); snitchManager = new SnitchManager(); <MASK>groupMediator = new GroupMediator();</MASK> registerEvents(); registerCommands(); snitchManager.loadSnitches(); }"
Inversion-Mutation
megadiff
"public void deselectUser(String postId){ bodyHtml = ""; if(mThreadView != null){ this.getActivity().runOnUiThread(new Runnable() { @Override public void run() { aq.find(R.id.thread_userpost_notice).gone(); mThreadView.loadUrl("javascript:loadpagehtml()"); } }); } if(TextUtils.isEmpty(postId) || postId.length() < 3){ mUserId = 0; mPostByUsername = null; setPage(savedPage); mLastPage = 0; mPostJump = ""; syncThread(); }else{ openThread(AwfulURL.parse(generatePostUrl(postId))); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "deselectUser"
"public void deselectUser(String postId){ bodyHtml = ""; <MASK>aq.find(R.id.thread_userpost_notice).gone();</MASK> if(mThreadView != null){ this.getActivity().runOnUiThread(new Runnable() { @Override public void run() { mThreadView.loadUrl("javascript:loadpagehtml()"); } }); } if(TextUtils.isEmpty(postId) || postId.length() < 3){ mUserId = 0; mPostByUsername = null; setPage(savedPage); mLastPage = 0; mPostJump = ""; syncThread(); }else{ openThread(AwfulURL.parse(generatePostUrl(postId))); } }"
Inversion-Mutation
megadiff
"@Override public boolean onCreateOptionsMenu(Menu menu) { this.menu = menu; // favorites button MenuItem fav = menu.add(0, R.id.mnu_favorites, 0, R.string.menu_favorites); fav.setIcon(R.drawable.mo_star_b5); fav.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); // menu button SubMenu sub = menu.addSubMenu(0, R.id.mnu_sub, 0, R.string.menu); sub.setIcon(R.drawable.ic_core_unstyled_action_overflow); sub.add(0, R.id.mnu_donation, 0, R.string.menu_donation); sub.add(0, R.id.mnu_settings, 0, R.string.menu_settings); sub.add(0, R.id.mnu_info, 0, R.string.menu_info); sub.getItem().setShowAsAction( MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); return true; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCreateOptionsMenu"
"@Override public boolean onCreateOptionsMenu(Menu menu) { this.menu = menu; // favorites button MenuItem fav = menu.add(0, R.id.mnu_favorites, 0, R.string.menu_favorites); fav.setIcon(R.drawable.mo_star_b5); fav.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); // menu button SubMenu sub = menu.addSubMenu(0, R.id.mnu_sub, 0, R.string.menu); sub.setIcon(R.drawable.ic_core_unstyled_action_overflow); <MASK>sub.add(0, R.id.mnu_settings, 0, R.string.menu_settings);</MASK> sub.add(0, R.id.mnu_donation, 0, R.string.menu_donation); sub.add(0, R.id.mnu_info, 0, R.string.menu_info); sub.getItem().setShowAsAction( MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); return true; }"
Inversion-Mutation
megadiff
"public JSONQueryParser(String queryJSON) throws JSONException { JSONObject query = new JSONObject(queryJSON); JSONArray regionArray = new JSONArray(); readSetQuery = new HashMap<String, String>(); readsQuery = new HashMap<String, String>(); featureMapQuery = new HashMap<String, String>(); featureSetMapQuery = new HashMap<String, String>(); regionMapQuery = new HashMap<String, String>(); //Generate missing keys if they are blank in the query. do{ JSONObject emptyObject = new JSONObject("{}"); JSONArray emptyArray = new JSONArray("[]"); if (!query.has("features")){ query.put("features", emptyObject); } else if (!query.has("feature_sets")){ query.put("feature_sets", emptyObject); } else if (!query.has("reads")){ query.put("reads", emptyObject); } else if (!query.has("read_sets")){ query.put("read_sets", emptyObject); } else if (!query.has("regions")){ query.put("regions", emptyArray); } } while (query.length() != 5); //READ THE JSON INPUT FILE /** "OutKey": { "InKey": "jsonObInner.get(InKey)" }*/ Iterator<String> outerKeys = query.keys(); while (outerKeys.hasNext()) { String outKey = outerKeys.next(); if (query.get(outKey) instanceof JSONObject) { JSONObject jsonObInner = query.getJSONObject(outKey); Iterator<String> innerKeys = jsonObInner.keys(); while (innerKeys.hasNext()) { String inKey = innerKeys.next(); if (outKey.equals("read_sets")) { readSetQuery.put(inKey, jsonObInner.getString(inKey)); } if (outKey.equals("reads")) { readsQuery.put(inKey, jsonObInner.getString(inKey)); } if (outKey.equals("feature_sets")){ featureSetMapQuery.put(inKey, jsonObInner.getString(inKey)); } if (outKey.equals("features")){ featureMapQuery.put(inKey, jsonObInner.getString(inKey)); } } innerKeys = null; } else if (query.get(outKey) instanceof JSONArray) { JSONArray jsonArInner = query.getJSONArray(outKey); if(outKey.equals("regions")) { regionArray = query.getJSONArray(outKey); for (int i=0; i< regionArray.length(); i++) { String region = regionArray .get(i) .toString(); if (region.contains(":") == false) { //i.e. selects "22" from "chr22" String chromosomeID = region.substring( region.indexOf("r")+1, region.length()); regionMapQuery.put(chromosomeID.toString(), "."); } else if (region.contains(":") == true) { //i.e. selects "22" from "chr22:1-99999" String chromosomeID = region.substring( region.indexOf("r")+1, region.indexOf(":")); String range = region.substring( region.indexOf(":")+1, region.length()); regionMapQuery.put(chromosomeID.toString(), range.toString()); } } } } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "JSONQueryParser"
"public JSONQueryParser(String queryJSON) throws JSONException { JSONObject query = new JSONObject(queryJSON); <MASK>Iterator<String> outerKeys = query.keys();</MASK> JSONArray regionArray = new JSONArray(); readSetQuery = new HashMap<String, String>(); readsQuery = new HashMap<String, String>(); featureMapQuery = new HashMap<String, String>(); featureSetMapQuery = new HashMap<String, String>(); regionMapQuery = new HashMap<String, String>(); //Generate missing keys if they are blank in the query. do{ JSONObject emptyObject = new JSONObject("{}"); JSONArray emptyArray = new JSONArray("[]"); if (!query.has("features")){ query.put("features", emptyObject); } else if (!query.has("feature_sets")){ query.put("feature_sets", emptyObject); } else if (!query.has("reads")){ query.put("reads", emptyObject); } else if (!query.has("read_sets")){ query.put("read_sets", emptyObject); } else if (!query.has("regions")){ query.put("regions", emptyArray); } } while (query.length() != 5); //READ THE JSON INPUT FILE /** "OutKey": { "InKey": "jsonObInner.get(InKey)" }*/ while (outerKeys.hasNext()) { String outKey = outerKeys.next(); if (query.get(outKey) instanceof JSONObject) { JSONObject jsonObInner = query.getJSONObject(outKey); Iterator<String> innerKeys = jsonObInner.keys(); while (innerKeys.hasNext()) { String inKey = innerKeys.next(); if (outKey.equals("read_sets")) { readSetQuery.put(inKey, jsonObInner.getString(inKey)); } if (outKey.equals("reads")) { readsQuery.put(inKey, jsonObInner.getString(inKey)); } if (outKey.equals("feature_sets")){ featureSetMapQuery.put(inKey, jsonObInner.getString(inKey)); } if (outKey.equals("features")){ featureMapQuery.put(inKey, jsonObInner.getString(inKey)); } } innerKeys = null; } else if (query.get(outKey) instanceof JSONArray) { JSONArray jsonArInner = query.getJSONArray(outKey); if(outKey.equals("regions")) { regionArray = query.getJSONArray(outKey); for (int i=0; i< regionArray.length(); i++) { String region = regionArray .get(i) .toString(); if (region.contains(":") == false) { //i.e. selects "22" from "chr22" String chromosomeID = region.substring( region.indexOf("r")+1, region.length()); regionMapQuery.put(chromosomeID.toString(), "."); } else if (region.contains(":") == true) { //i.e. selects "22" from "chr22:1-99999" String chromosomeID = region.substring( region.indexOf("r")+1, region.indexOf(":")); String range = region.substring( region.indexOf(":")+1, region.length()); regionMapQuery.put(chromosomeID.toString(), range.toString()); } } } } } }"
Inversion-Mutation
megadiff
"void dispatchEvent(int type) { switch (type) { case SimulationListener.kStartEvent: m_SimButtons.updateButtons(); m_MapButtons.updateButtons(); m_AgentDisplay.updateButtons(); return; case SimulationListener.kStopEvent: m_VisualWorld.setRepaint(); m_VisualWorld.redraw(); m_SimButtons.updateButtons(); m_MapButtons.updateButtons(); m_AgentDisplay.updateButtons(); return; case SimulationListener.kErrorMessageEvent: MessageBox mb = new MessageBox(m_Shell, SWT.ICON_ERROR | SWT.OK | SWT.WRAP); mb.setMessage(m_Simulation.getLastErrorMessage()); mb.setText("Eaters Error"); mb.open(); return; case SimulationListener.kUpdateEvent: m_VisualWorld.redraw(); updateFoodAndScoreCount(); m_AgentDisplay.worldChangeEvent(); return; case SimulationListener.kResetEvent: updateWorldGroup(); EatersVisualWorld.remapFoodColors(m_Simulation.getEatersWorld().getFood()); m_VisualWorld.setRepaint(); m_VisualWorld.redraw(); updateFoodAndScoreCount(); m_SimButtons.updateButtons(); m_AgentDisplay.worldChangeEvent(); return; case SimulationListener.kAgentCreatedEvent: m_VisualWorld.setRepaint(); m_VisualWorld.redraw(); EatersVisualWorld.remapEntityColors(m_Simulation.getEatersWorld().getEaters()); updateFoodAndScoreCount(); m_SimButtons.updateButtons(); m_AgentDisplay.agentEvent(); return; case SimulationListener.kAgentDestroyedEvent: m_VisualWorld.setRepaint(); m_VisualWorld.redraw(); EatersVisualWorld.remapEntityColors(m_Simulation.getEatersWorld().getEaters()); m_SimButtons.updateButtons(); m_AgentDisplay.agentEvent(); return; default: m_Logger.log("Invalid event type received: " + new Integer(type)); return; } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "dispatchEvent"
"void dispatchEvent(int type) { switch (type) { case SimulationListener.kStartEvent: m_SimButtons.updateButtons(); m_MapButtons.updateButtons(); m_AgentDisplay.updateButtons(); return; case SimulationListener.kStopEvent: m_VisualWorld.setRepaint(); m_VisualWorld.redraw(); m_SimButtons.updateButtons(); m_MapButtons.updateButtons(); m_AgentDisplay.updateButtons(); return; case SimulationListener.kErrorMessageEvent: MessageBox mb = new MessageBox(m_Shell, SWT.ICON_ERROR | SWT.OK | SWT.WRAP); mb.setMessage(m_Simulation.getLastErrorMessage()); mb.setText("Eaters Error"); mb.open(); return; case SimulationListener.kUpdateEvent: m_VisualWorld.redraw(); updateFoodAndScoreCount(); m_AgentDisplay.worldChangeEvent(); return; case SimulationListener.kResetEvent: updateWorldGroup(); m_VisualWorld.setRepaint(); m_VisualWorld.redraw(); <MASK>EatersVisualWorld.remapFoodColors(m_Simulation.getEatersWorld().getFood());</MASK> updateFoodAndScoreCount(); m_SimButtons.updateButtons(); m_AgentDisplay.worldChangeEvent(); return; case SimulationListener.kAgentCreatedEvent: m_VisualWorld.setRepaint(); m_VisualWorld.redraw(); EatersVisualWorld.remapEntityColors(m_Simulation.getEatersWorld().getEaters()); updateFoodAndScoreCount(); m_SimButtons.updateButtons(); m_AgentDisplay.agentEvent(); return; case SimulationListener.kAgentDestroyedEvent: m_VisualWorld.setRepaint(); m_VisualWorld.redraw(); EatersVisualWorld.remapEntityColors(m_Simulation.getEatersWorld().getEaters()); m_SimButtons.updateButtons(); m_AgentDisplay.agentEvent(); return; default: m_Logger.log("Invalid event type received: " + new Integer(type)); return; } }"
Inversion-Mutation
megadiff
"public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_store_slider); session = Session.getInstance(this); mContext = getApplicationContext(); mContentViews = new ArrayList<View>(); privateMode = false; //pagerControlStringRef = new int[] {R.string.search_store, R.string.all_store, R.string.near_store}; control = (PagerControl) findViewById(R.id.PagerControl); control.setContentViews(mContentViews); swipeView = (SwipeView) findViewById(R.id.SwipeView); view1 = (StoreSearchView) findViewById(R.id.ListView1); view2 = (StoreListView) findViewById(R.id.ListView2); view3 = (StoreNearListView) findViewById(R.id.ListView3); view1.setTag(R.string.title, getResources().getText(R.string.search_store).toString()); view2.setTag(R.string.title, getResources().getText(R.string.all_store).toString()); view3.setTag(R.string.title, getResources().getText(R.string.near_store).toString()); mContentViews.add(view1); mContentViews.add(view2); mContentViews.add(view3); view1.setActivity(this); view2.setActivity(this); view3.setActivity(this); initPages(); swipeView.addOnScrollListener(this); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCreate"
"public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_store_slider); session = Session.getInstance(this); mContext = getApplicationContext(); mContentViews = new ArrayList<View>(); privateMode = false; //pagerControlStringRef = new int[] {R.string.search_store, R.string.all_store, R.string.near_store}; control = (PagerControl) findViewById(R.id.PagerControl); control.setContentViews(mContentViews); swipeView = (SwipeView) findViewById(R.id.SwipeView); view1 = (StoreSearchView) findViewById(R.id.ListView1); view2 = (StoreListView) findViewById(R.id.ListView2); view3 = (StoreNearListView) findViewById(R.id.ListView3); view1.setTag(R.string.title, getResources().getText(R.string.search_store).toString()); view2.setTag(R.string.title, getResources().getText(R.string.all_store).toString()); view3.setTag(R.string.title, getResources().getText(R.string.near_store).toString()); <MASK>mContentViews.add(view3);</MASK> mContentViews.add(view1); mContentViews.add(view2); view1.setActivity(this); view2.setActivity(this); view3.setActivity(this); initPages(); swipeView.addOnScrollListener(this); }"
Inversion-Mutation
megadiff
"protected void handleTouchesUp() { for (Touch t : previousTouchState) { if (!currentTouchState.contains(t.sessionID)) { // the touch existed, but no longer exists, so it went up SMTUtilities.invoke(touchUp, applet, t); for (Zone zone : t.getAssignedZones()) { doTouchUp(zone, t); if (touchPrevZone.get(t) == zone) { doPress(zone, t); } } touchPrevZone.remove(t); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handleTouchesUp"
"protected void handleTouchesUp() { for (Touch t : previousTouchState) { if (!currentTouchState.contains(t.sessionID)) { // the touch existed, but no longer exists, so it went up SMTUtilities.invoke(touchUp, applet, t); for (Zone zone : t.getAssignedZones()) { if (touchPrevZone.get(t) == zone) { doPress(zone, t); } <MASK>doTouchUp(zone, t);</MASK> } touchPrevZone.remove(t); } } }"
Inversion-Mutation
megadiff
"protected MavenSession newMavenSession(MavenProject project, List<MavenProject> projects) throws Exception { MavenExecutionRequest request = newMavenExecutionRequest(new File(project.getBasedir(), "pom.xml")); MavenExecutionResult result = new DefaultMavenExecutionResult(); DefaultRepositorySystemSession repositorySession = new DefaultRepositorySystemSession(); MavenSession session = new MavenSession(getContainer(), repositorySession, request, result); session.setProjects(projects); session.setCurrentProject(project); return session; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "newMavenSession"
"protected MavenSession newMavenSession(MavenProject project, List<MavenProject> projects) throws Exception { MavenExecutionRequest request = newMavenExecutionRequest(new File(project.getBasedir(), "pom.xml")); MavenExecutionResult result = new DefaultMavenExecutionResult(); DefaultRepositorySystemSession repositorySession = new DefaultRepositorySystemSession(); MavenSession session = new MavenSession(getContainer(), repositorySession, request, result); <MASK>session.setCurrentProject(project);</MASK> session.setProjects(projects); return session; }"
Inversion-Mutation
megadiff
"@Override public View getView(int position, View convertView, final ViewGroup parent) { LinearLayout taskView; final Task task = getItem(position); final String taskText = task.getText(); boolean taskChecked = task.isChecked(); boolean taskArchived = task.isArchived(); if(convertView == null) { taskView = new LinearLayout(getContext()); LayoutInflater inflater = (LayoutInflater)getContext() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(resource, taskView, true); } else { taskView = (LinearLayout)convertView; } CheckBox taskCheckBox = (CheckBox)taskView.findViewById(R.id.task_check_box); taskCheckBox.setChecked(taskChecked); taskCheckBox.setOnClickListener(new OnTaskCheckListener(this, task)); final EditText editText = (EditText)taskView.findViewById(R.id.task_edit_text); editText.setText(formatTaskText(taskText)); final ImageButton taskButton = (ImageButton) taskView.findViewById(R.id.task_button); taskButton.setTag(R.drawable.ic_action_remove); taskButton.setOnClickListener(new OnTaskDeleteListener(this, task, editText)); editText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(hasFocus){ EditText focusedEditText = (EditText) v; Editable htmlText = focusedEditText.getText(); String newText = Html.fromHtml(htmlText.toString()).toString(); focusedEditText.setText(newText); taskButton.setImageResource(R.drawable.ic_action_confirm); taskButton.setTag(R.drawable.ic_action_confirm); log.info("remove removed"); } else { log.info("confirm removed"); taskButton.setImageResource(R.drawable.ic_action_remove); taskButton.setTag(R.drawable.ic_action_remove); } } }); // editText.addTextChangedListener(new TextWatcher(){ // public void afterTextChanged(Editable s) { // if(editText.isFocused()){ // // } // } // public void beforeTextChanged(CharSequence s, int start, int count, int after){ } // public void onTextChanged(CharSequence s, int start, int before, int count){} // }); // editText.setOnEditorActionListener(new OnEditorActionListener() { // // @Override // public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { // if (actionId == EditorInfo.IME_ACTION_SEARCH || // actionId == EditorInfo.IME_ACTION_DONE || // event.getAction() == KeyEvent.ACTION_DOWN && // event.getKeyCode() == KeyEvent.KEYCODE_ENTER) { // // v.setVisibility(View.GONE); // ViewGroup row = (ViewGroup) v.getParent(); // for (int itemPos = 0; itemPos < row.getChildCount(); itemPos++) { // View view = row.getChildAt(itemPos); // log.info("focusChanged: "+itemPos); // if (view instanceof TextView) { // view.setVisibility(View.VISIBLE); // } // } // // return true; // consume. // } // return false; // pass on to other listeners. // } // }); // // TextView showText = (TextView) taskView.findViewById(R.id.task_show_text); // showText.setText(taskText); // showText.setOnClickListener(new OnClickListener() { // // @Override // public void onClick(View v) { // v.setVisibility(View.GONE); // ViewGroup row = (ViewGroup) v.getParent(); // for (int itemPos = 0; itemPos < row.getChildCount(); itemPos++) { // log.info("clicked: "+itemPos); // View view = row.getChildAt(itemPos); // log.info(view.getClass().toString()); // if (view instanceof EditText) { // log.info("LAL"); // view.setVisibility(View.VISIBLE); // view.requestFocus(); // } // } // } // }); return taskView; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getView"
"@Override public View getView(int position, View convertView, final ViewGroup parent) { LinearLayout taskView; final Task task = getItem(position); final String taskText = task.getText(); boolean taskChecked = task.isChecked(); boolean taskArchived = task.isArchived(); if(convertView == null) { taskView = new LinearLayout(getContext()); LayoutInflater inflater = (LayoutInflater)getContext() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(resource, taskView, true); } else { taskView = (LinearLayout)convertView; } CheckBox taskCheckBox = (CheckBox)taskView.findViewById(R.id.task_check_box); taskCheckBox.setChecked(taskChecked); taskCheckBox.setOnClickListener(new OnTaskCheckListener(this, task)); final EditText editText = (EditText)taskView.findViewById(R.id.task_edit_text); editText.setText(formatTaskText(taskText)); final ImageButton taskButton = (ImageButton) taskView.findViewById(R.id.task_button); <MASK>taskButton.setOnClickListener(new OnTaskDeleteListener(this, task, editText));</MASK> taskButton.setTag(R.drawable.ic_action_remove); editText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(hasFocus){ EditText focusedEditText = (EditText) v; Editable htmlText = focusedEditText.getText(); String newText = Html.fromHtml(htmlText.toString()).toString(); focusedEditText.setText(newText); taskButton.setImageResource(R.drawable.ic_action_confirm); taskButton.setTag(R.drawable.ic_action_confirm); log.info("remove removed"); } else { log.info("confirm removed"); taskButton.setImageResource(R.drawable.ic_action_remove); taskButton.setTag(R.drawable.ic_action_remove); } } }); // editText.addTextChangedListener(new TextWatcher(){ // public void afterTextChanged(Editable s) { // if(editText.isFocused()){ // // } // } // public void beforeTextChanged(CharSequence s, int start, int count, int after){ } // public void onTextChanged(CharSequence s, int start, int before, int count){} // }); // editText.setOnEditorActionListener(new OnEditorActionListener() { // // @Override // public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { // if (actionId == EditorInfo.IME_ACTION_SEARCH || // actionId == EditorInfo.IME_ACTION_DONE || // event.getAction() == KeyEvent.ACTION_DOWN && // event.getKeyCode() == KeyEvent.KEYCODE_ENTER) { // // v.setVisibility(View.GONE); // ViewGroup row = (ViewGroup) v.getParent(); // for (int itemPos = 0; itemPos < row.getChildCount(); itemPos++) { // View view = row.getChildAt(itemPos); // log.info("focusChanged: "+itemPos); // if (view instanceof TextView) { // view.setVisibility(View.VISIBLE); // } // } // // return true; // consume. // } // return false; // pass on to other listeners. // } // }); // // TextView showText = (TextView) taskView.findViewById(R.id.task_show_text); // showText.setText(taskText); // showText.setOnClickListener(new OnClickListener() { // // @Override // public void onClick(View v) { // v.setVisibility(View.GONE); // ViewGroup row = (ViewGroup) v.getParent(); // for (int itemPos = 0; itemPos < row.getChildCount(); itemPos++) { // log.info("clicked: "+itemPos); // View view = row.getChildAt(itemPos); // log.info(view.getClass().toString()); // if (view instanceof EditText) { // log.info("LAL"); // view.setVisibility(View.VISIBLE); // view.requestFocus(); // } // } // } // }); return taskView; }"
Inversion-Mutation
megadiff
"public CoreTexture2D( @Nonnull final CoreGL gl, @Nonnull final BufferFactory bufferFactory, final int textureId, final int target, final int level, final int internalFormat, final int width, final int height, final int border, final int format, final int type, @Nonnull final Buffer data, final int magFilter, final int minFilter) { this.gl = gl; this.textureId = createTexture( textureId, target, level, internalFormat, width, height, border, format, type, data, magFilter, minFilter); textureIdBuffer = bufferFactory.createNativeOrderedIntBuffer(1); textureTarget = target; this.width = width; this.height = height; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "CoreTexture2D"
"public CoreTexture2D( @Nonnull final CoreGL gl, @Nonnull final BufferFactory bufferFactory, final int textureId, final int target, final int level, final int internalFormat, final int width, final int height, final int border, final int format, final int type, @Nonnull final Buffer data, final int magFilter, final int minFilter) { this.textureId = createTexture( textureId, target, level, internalFormat, width, height, border, format, type, data, magFilter, minFilter); <MASK>this.gl = gl;</MASK> textureIdBuffer = bufferFactory.createNativeOrderedIntBuffer(1); textureTarget = target; this.width = width; this.height = height; }"
Inversion-Mutation
megadiff
"private void load() { synchronized(CodeEntry.class) { if(lpe != null) return; ClassLoader loader = loader(false); lpe = new TreeMap<String, Class<?>>(); try { for(Map.Entry<String, String> e : pe.entrySet()) { String name = e.getKey(); String clnm = e.getValue(); Class<?> cl = loader.loadClass(clnm); lpe.put(name, cl); } } catch(ClassNotFoundException e) { throw(new LoadException(e, Resource.this)); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "load"
"private void load() { synchronized(CodeEntry.class) { if(lpe != null) return; <MASK>lpe = new TreeMap<String, Class<?>>();</MASK> ClassLoader loader = loader(false); try { for(Map.Entry<String, String> e : pe.entrySet()) { String name = e.getKey(); String clnm = e.getValue(); Class<?> cl = loader.loadClass(clnm); lpe.put(name, cl); } } catch(ClassNotFoundException e) { throw(new LoadException(e, Resource.this)); } } }"