type
stringclasses
1 value
dataset
stringclasses
1 value
input
stringlengths
75
160k
instruction
stringlengths
117
171
output
stringlengths
88
168k
Inversion-Mutation
megadiff
"@Override public void configure() { createDefaultPresenter(); createAndHandleHistory(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "configure"
"@Override public void configure() { <MASK>createAndHandleHistory();</MASK> createDefaultPresenter(); }"
Inversion-Mutation
megadiff
"private Map<String, EObject> initMetaElementsInAllResources() { Map<String, EObject> eClassifiers = new HashMap<String, EObject>(); for (Resource res : getReferencedResources()) { initMetaElements(eClassifiers, res.getContents().iterator(), null); } initMetaElements(eClassifiers, getResource().getContents().iterator(), null); return eClassifiers; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "initMetaElementsInAllResources"
"private Map<String, EObject> initMetaElementsInAllResources() { Map<String, EObject> eClassifiers = new HashMap<String, EObject>(); <MASK>initMetaElements(eClassifiers, getResource().getContents().iterator(), null);</MASK> for (Resource res : getReferencedResources()) { initMetaElements(eClassifiers, res.getContents().iterator(), null); } return eClassifiers; }"
Inversion-Mutation
megadiff
"public GUI(JDesktopPane desktop) { myGUI = this; mySimulation = null; myDesktopPane = desktop; if (menuPlugins == null) { menuPlugins = new JMenu("Plugins"); menuPlugins.removeAll(); /* COOJA/GUI plugins at top, simulation plugins in middle, mote plugins at bottom */ menuPlugins.addSeparator(); menuPlugins.addSeparator(); } if (menuMotePluginClasses == null) { menuMotePluginClasses = new Vector<Class<? extends Plugin>>(); } /* Help panel */ quickHelpTextPane = new JTextPane(); quickHelpTextPane.setContentType("text/html"); quickHelpTextPane.setEditable(false); quickHelpTextPane.setVisible(false); quickHelpScroll = new JScrollPane(quickHelpTextPane, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); quickHelpScroll.setPreferredSize(new Dimension(200, 0)); quickHelpScroll.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(Color.GRAY), BorderFactory.createEmptyBorder(0, 3, 0, 0) )); quickHelpScroll.setVisible(false); loadQuickHelp("KEYBOARD_SHORTCUTS"); // Load default and overwrite with user settings (if any) loadExternalToolsDefaultSettings(); loadExternalToolsUserSettings(); /* Debugging - Break on repaints outside EDT */ /*RepaintManager.setCurrentManager(new RepaintManager() { public void addDirtyRegion(JComponent comp, int a, int b, int c, int d) { if(!java.awt.EventQueue.isDispatchThread()) { throw new RuntimeException("Repainting outside EDT"); } super.addDirtyRegion(comp, a, b, c, d); } });*/ // Register default project directories String defaultProjectDirs = getExternalToolsSetting("DEFAULT_PROJECTDIRS", null); if (defaultProjectDirs != null && defaultProjectDirs.length() > 0) { String[] arr = defaultProjectDirs.split(";"); for (String p : arr) { File projectDir = restorePortablePath(new File(p)); currentProjects.add(new COOJAProject(projectDir)); } } /* Parse current project configuration */ try { reparseProjectConfig(); } catch (ParseProjectsException e) { logger.fatal("Error when loading projects: " + e.getMessage(), e); if (isVisualized()) { JOptionPane.showMessageDialog(GUI.getTopParentContainer(), "All COOJA projects could not load.\n\n" + "To manage COOJA projects:\n" + "Menu->Settings->COOJA projects", "Reconfigure COOJA projects", JOptionPane.INFORMATION_MESSAGE); showErrorDialog(getTopParentContainer(), "COOJA projects load error", e, false); } } // Start all standard GUI plugins for (Class<? extends Plugin> pluginClass : pluginClasses) { int pluginType = pluginClass.getAnnotation(PluginType.class).value(); if (pluginType == PluginType.COOJA_STANDARD_PLUGIN) { tryStartPlugin(pluginClass, this, null, null); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "GUI"
"public GUI(JDesktopPane desktop) { myGUI = this; mySimulation = null; myDesktopPane = desktop; if (menuPlugins == null) { menuPlugins = new JMenu("Plugins"); menuPlugins.removeAll(); /* COOJA/GUI plugins at top, simulation plugins in middle, mote plugins at bottom */ menuPlugins.addSeparator(); menuPlugins.addSeparator(); } if (menuMotePluginClasses == null) { menuMotePluginClasses = new Vector<Class<? extends Plugin>>(); } /* Help panel */ quickHelpTextPane = new JTextPane(); quickHelpTextPane.setContentType("text/html"); quickHelpTextPane.setEditable(false); quickHelpTextPane.setVisible(false); quickHelpScroll = new JScrollPane(quickHelpTextPane, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); quickHelpScroll.setPreferredSize(new Dimension(200, 0)); quickHelpScroll.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(Color.GRAY), BorderFactory.createEmptyBorder(0, 3, 0, 0) )); quickHelpScroll.setVisible(false); loadQuickHelp("KEYBOARD_SHORTCUTS"); // Load default and overwrite with user settings (if any) loadExternalToolsDefaultSettings(); loadExternalToolsUserSettings(); /* Debugging - Break on repaints outside EDT */ /*RepaintManager.setCurrentManager(new RepaintManager() { public void addDirtyRegion(JComponent comp, int a, int b, int c, int d) { if(!java.awt.EventQueue.isDispatchThread()) { throw new RuntimeException("Repainting outside EDT"); } super.addDirtyRegion(comp, a, b, c, d); } });*/ // Register default project directories String defaultProjectDirs = getExternalToolsSetting("DEFAULT_PROJECTDIRS", null); if (defaultProjectDirs != null && defaultProjectDirs.length() > 0) { String[] arr = defaultProjectDirs.split(";"); for (String p : arr) { File projectDir = restorePortablePath(new File(p)); currentProjects.add(new COOJAProject(projectDir)); } } /* Parse current project configuration */ try { reparseProjectConfig(); } catch (ParseProjectsException e) { logger.fatal("Error when loading projects: " + e.getMessage(), e); if (isVisualized()) { JOptionPane.showMessageDialog(GUI.getTopParentContainer(), "All COOJA projects could not load.\n\n" + "To manage COOJA projects:\n" + "Menu->Settings->COOJA projects", "Reconfigure COOJA projects", JOptionPane.INFORMATION_MESSAGE); } <MASK>showErrorDialog(getTopParentContainer(), "COOJA projects load error", e, false);</MASK> } // Start all standard GUI plugins for (Class<? extends Plugin> pluginClass : pluginClasses) { int pluginType = pluginClass.getAnnotation(PluginType.class).value(); if (pluginType == PluginType.COOJA_STANDARD_PLUGIN) { tryStartPlugin(pluginClass, this, null, null); } } }"
Inversion-Mutation
megadiff
"protected void execute( IContent content, IReportItemExecutor executor ) throws BirtException { assert executor != null; while ( executor.hasNextChild( ) ) { IReportItemExecutor childExecutor = executor.getNextChild( ); if ( childExecutor != null ) { IContent childContent = childExecutor.execute( ); if ( childContent != null ) { if ( !content.getChildren( ).contains( childContent ) ) { content.getChildren( ).add( childContent ); } } execute( childContent, childExecutor ); childExecutor.close( ); if ( childContent != null ) { if ( !executor.hasNextChild( ) ) { childContent.setLastChild( true ); } else { childContent.setLastChild( false ); } } } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "execute"
"protected void execute( IContent content, IReportItemExecutor executor ) throws BirtException { assert executor != null; while ( executor.hasNextChild( ) ) { IReportItemExecutor childExecutor = executor.getNextChild( ); if ( childExecutor != null ) { IContent childContent = childExecutor.execute( ); if ( childContent != null ) { if ( !content.getChildren( ).contains( childContent ) ) { content.getChildren( ).add( childContent ); } } execute( childContent, childExecutor ); if ( childContent != null ) { if ( !executor.hasNextChild( ) ) { childContent.setLastChild( true ); } else { childContent.setLastChild( false ); } } <MASK>childExecutor.close( );</MASK> } } }"
Inversion-Mutation
megadiff
"public Long[][] sortHashMapIntoArray() { Set<Long> patterns = patternSeen.keySet(); Long[][] initialPatternSeen = new Long[patterns.size()][2]; int index = 0; for(Long pattern : patterns) { initialPatternSeen[index][0] = pattern; initialPatternSeen[index][1] = patternSeen.get(pattern)[0]; index++; } for (int j = 0; j < initialPatternSeen.length; j++) { int maxindex = j; long maxvalue = initialPatternSeen[maxindex][1]; for (int i = j; i < initialPatternSeen.length; i++) { if (initialPatternSeen[i][1] > maxvalue) { maxindex = i; maxvalue = initialPatternSeen[i][1]; } } Long[] swapValue = initialPatternSeen[maxindex]; initialPatternSeen[maxindex] = initialPatternSeen[j]; initialPatternSeen[j] = swapValue; } return initialPatternSeen; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "sortHashMapIntoArray"
"public Long[][] sortHashMapIntoArray() { Set<Long> patterns = patternSeen.keySet(); Long[][] initialPatternSeen = new Long[patterns.size()][2]; int index = 0; for(Long pattern : patterns) { initialPatternSeen[index][0] = pattern; initialPatternSeen[index][1] = patternSeen.get(pattern)[0]; index++; } for (int j = 0; j < initialPatternSeen.length; j++) { int maxindex = j; long maxvalue = initialPatternSeen[maxindex][1]; for (int i = j; i < initialPatternSeen.length; i++) { if (initialPatternSeen[i][1] > maxvalue) { <MASK>maxvalue = initialPatternSeen[i][1];</MASK> maxindex = i; } } Long[] swapValue = initialPatternSeen[maxindex]; initialPatternSeen[maxindex] = initialPatternSeen[j]; initialPatternSeen[j] = swapValue; } return initialPatternSeen; }"
Inversion-Mutation
megadiff
"@Override public void onCreate(Bundle savedInstanceState) { SetupData.restore(savedInstanceState); super.onCreate(savedInstanceState); if (DEBUG_SETUP_FLOWS) { Log.d(getClass().getName(), SetupData.debugString()); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCreate"
"@Override public void onCreate(Bundle savedInstanceState) { <MASK>super.onCreate(savedInstanceState);</MASK> SetupData.restore(savedInstanceState); if (DEBUG_SETUP_FLOWS) { Log.d(getClass().getName(), SetupData.debugString()); } }"
Inversion-Mutation
megadiff
"@Override public void write(byte[] b, int off, int len) throws IOException { if (b == null) { throw new NullPointerException(); } else if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } if (WRITE_TYPE.isCache()) { if (mCanCache) { int tLen = len; int tOff = off; while (tLen > 0) { if (mCurrentBlockLeftByte == 0) { getNextBlock(); } if (mCurrentBlockLeftByte > tLen) { mCurrentBlockOutStream.write(b, tOff, tLen); mCurrentBlockLeftByte -= tLen; mWrittenBytes += tLen; tOff += tLen; tLen = 0; } else { mCurrentBlockOutStream.write(b, tOff, (int) mCurrentBlockLeftByte); tOff += mCurrentBlockLeftByte; tLen -= mCurrentBlockLeftByte; mWrittenBytes += mCurrentBlockLeftByte; mCurrentBlockLeftByte = 0; } } } else if (WRITE_TYPE.isMustCache()) { throw new IOException("Can not cache: " + WRITE_TYPE); } } if (WRITE_TYPE.isThrough()) { mCheckpointOutputStream.write(b, off, len); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "write"
"@Override public void write(byte[] b, int off, int len) throws IOException { if (b == null) { throw new NullPointerException(); } else if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } if (WRITE_TYPE.isCache()) { if (mCanCache) { int tLen = len; int tOff = off; while (tLen > 0) { if (mCurrentBlockLeftByte == 0) { getNextBlock(); } if (mCurrentBlockLeftByte > tLen) { mCurrentBlockOutStream.write(b, tOff, tLen); mCurrentBlockLeftByte -= tLen; tOff += tLen; tLen = 0; <MASK>mWrittenBytes += tLen;</MASK> } else { mCurrentBlockOutStream.write(b, tOff, (int) mCurrentBlockLeftByte); tOff += mCurrentBlockLeftByte; tLen -= mCurrentBlockLeftByte; mWrittenBytes += mCurrentBlockLeftByte; mCurrentBlockLeftByte = 0; } } } else if (WRITE_TYPE.isMustCache()) { throw new IOException("Can not cache: " + WRITE_TYPE); } } if (WRITE_TYPE.isThrough()) { mCheckpointOutputStream.write(b, off, len); } }"
Inversion-Mutation
megadiff
"public UnilateralSortMerger(MemoryManager memoryManager, IOManager ioManager, long totalMemory, long maxWriteMem, int numSortBuffers, int maxNumFileHandles, Comparator<Key>[] keyComparators, int[] keyPositions, Class<? extends Key>[] keyClasses, MutableObjectIterator<PactRecord> input, AbstractInvokable parentTask, float startSpillingFraction) throws IOException, MemoryAllocationException { // sanity checks if (memoryManager == null | ioManager == null | keyComparators == null | keyPositions == null | keyClasses == null) { throw new NullPointerException(); } if (parentTask == null) { throw new NullPointerException("Parent Task must not be null."); } if (maxNumFileHandles < 2) { throw new IllegalArgumentException("Merger cannot work with less than two file handles."); } if (keyComparators.length < 1) { throw new IllegalArgumentException("There must be at least one sort column and hence one comparator."); } if (keyComparators.length != keyPositions.length || keyPositions.length != keyClasses.length) { throw new IllegalArgumentException("The number of comparators, key columns and key types must match."); } if (totalMemory < MIN_SORT_MEM + MIN_WRITE_MEM) { throw new IllegalArgumentException("Too little memory provided to Sort-Merger to perform task."); } this.maxNumFileHandles = maxNumFileHandles; this.memoryManager = memoryManager; this.ioManager = ioManager; this.keyComparators = keyComparators; this.keyPositions = keyPositions; this.keyClasses = keyClasses; this.parent = parentTask; this.memoryToReleaseAtShutdown = new ArrayList<List<MemorySegment>>(); this.channelsToDeleteAtShutdown = new ArrayList<Channel.ID>(); this.openChannels = new ArrayList<BlockChannelAccess<?,?>>(); // determine the size of the I/O buffers. the size must be chosen such that we can accommodate // the desired number of merges, plus the writing, from the total memory if (maxWriteMem != 0) { if (maxWriteMem != -1 && maxWriteMem < MIN_WRITE_MEM) { throw new IllegalArgumentException("The specified maximum write memory is to low. " + "Required are at least " + MIN_WRITE_MEM + " bytes."); } // determine how the reading side limits the buffer size, because we buffers for the readers // during the merging phase final int minBuffers = NUM_WRITE_BUFFERS + maxNumFileHandles; final int desiredBuffers = NUM_WRITE_BUFFERS + 2 * maxNumFileHandles; int bufferSize = (int) (totalMemory / desiredBuffers); if (bufferSize < MIN_IO_BUFFER_SIZE) { bufferSize = MIN_IO_BUFFER_SIZE; if (totalMemory / minBuffers < MIN_IO_BUFFER_SIZE) { maxNumFileHandles = (int) (totalMemory / MIN_IO_BUFFER_SIZE) - NUM_WRITE_BUFFERS; if (LOG.isWarnEnabled()) LOG.warn("Reducing maximal merge fan-in to " + maxNumFileHandles + " due to memory limitations."); } } else { bufferSize = Math.min(MAX_IO_BUFFER_SIZE, MathUtils.roundDownToPowerOf2(bufferSize)); } if (maxWriteMem < 0) { maxWriteMem = Math.max(totalMemory / 64, MIN_WRITE_MEM); } this.ioBufferSize = Math.min(bufferSize, MathUtils.roundDownToPowerOf2((int) (maxWriteMem / NUM_WRITE_BUFFERS))); maxWriteMem = NUM_WRITE_BUFFERS * this.ioBufferSize; } else { // no I/O happening this.ioBufferSize = -1; } final long sortMem = totalMemory - maxWriteMem; final long numSortMemSegments = sortMem / SORT_MEM_SEGMENT_SIZE; // decide how many sort buffers to use if (numSortBuffers < 1) { if (sortMem > 96 * 1024 * 1024) { numSortBuffers = 3; } else if (numSortMemSegments >= 2 * MIN_NUM_SORT_MEM_SEGMENTS) { numSortBuffers = 2; } else { numSortBuffers = 1; } } final int numSegmentsPerSortBuffer = numSortMemSegments / numSortBuffers > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) (numSortMemSegments / numSortBuffers); if (LOG.isDebugEnabled()) { LOG.debug("Instantiating unilateral sort-merger with " + maxWriteMem + " bytes of write cache and " + sortMem + " bytes of sorting/merging memory. Dividing sort memory over " + numSortBuffers + " buffers (" + numSegmentsPerSortBuffer + " pages with " + SORT_MEM_SEGMENT_SIZE + " bytes) , merging maximally " + maxNumFileHandles + " streams at once."); } // circular queues pass buffers between the threads final CircularQueues circularQueues = new CircularQueues(); this.sortBuffers = new ArrayList<NormalizedKeySorter<?>>(numSortBuffers); // allocate the sort buffers and fill empty queue with them for (int i = 0; i < numSortBuffers; i++) { final List<MemorySegment> sortSegments = memoryManager.allocateStrict(parentTask, numSegmentsPerSortBuffer, SORT_MEM_SEGMENT_SIZE); final PactRecordAccessors accessors = new PactRecordAccessors(keyPositions, keyClasses); final NormalizedKeySorter<PactRecord> buffer = new NormalizedKeySorter<PactRecord>(accessors, sortSegments); this.sortBuffers.add(buffer); // add to empty queue CircularElement element = new CircularElement(i, buffer); circularQueues.empty.add(element); } // exception handling ExceptionHandler<IOException> exceptionHandler = new ExceptionHandler<IOException>() { public void handleException(IOException exception) { // forward exception if (!closed) { setResultIteratorException(exception); close(); } } }; // start the thread that reads the input channels this.readThread = getReadingThread(exceptionHandler, input, circularQueues, parentTask, ((long) (startSpillingFraction * sortMem))); // start the thread that sorts the buffers this.sortThread = getSortingThread(exceptionHandler, circularQueues, parentTask); // start the thread that handles spilling to secondary storage this.spillThread = getSpillingThread(exceptionHandler, circularQueues, memoryManager, ioManager, sortMem, parentTask); startThreads(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "UnilateralSortMerger"
"public UnilateralSortMerger(MemoryManager memoryManager, IOManager ioManager, long totalMemory, long maxWriteMem, int numSortBuffers, int maxNumFileHandles, Comparator<Key>[] keyComparators, int[] keyPositions, Class<? extends Key>[] keyClasses, MutableObjectIterator<PactRecord> input, AbstractInvokable parentTask, float startSpillingFraction) throws IOException, MemoryAllocationException { // sanity checks if (memoryManager == null | ioManager == null | keyComparators == null | keyPositions == null | keyClasses == null) { throw new NullPointerException(); } if (parentTask == null) { throw new NullPointerException("Parent Task must not be null."); } if (maxNumFileHandles < 2) { throw new IllegalArgumentException("Merger cannot work with less than two file handles."); } if (keyComparators.length < 1) { throw new IllegalArgumentException("There must be at least one sort column and hence one comparator."); } if (keyComparators.length != keyPositions.length || keyPositions.length != keyClasses.length) { throw new IllegalArgumentException("The number of comparators, key columns and key types must match."); } if (totalMemory < MIN_SORT_MEM + MIN_WRITE_MEM) { throw new IllegalArgumentException("Too little memory provided to Sort-Merger to perform task."); } this.maxNumFileHandles = maxNumFileHandles; this.memoryManager = memoryManager; this.ioManager = ioManager; this.keyComparators = keyComparators; this.keyPositions = keyPositions; this.keyClasses = keyClasses; this.parent = parentTask; this.memoryToReleaseAtShutdown = new ArrayList<List<MemorySegment>>(); this.channelsToDeleteAtShutdown = new ArrayList<Channel.ID>(); this.openChannels = new ArrayList<BlockChannelAccess<?,?>>(); // determine the size of the I/O buffers. the size must be chosen such that we can accommodate // the desired number of merges, plus the writing, from the total memory if (maxWriteMem != 0) { if (maxWriteMem != -1 && maxWriteMem < MIN_WRITE_MEM) { throw new IllegalArgumentException("The specified maximum write memory is to low. " + "Required are at least " + MIN_WRITE_MEM + " bytes."); } // determine how the reading side limits the buffer size, because we buffers for the readers // during the merging phase final int minBuffers = NUM_WRITE_BUFFERS + maxNumFileHandles; final int desiredBuffers = NUM_WRITE_BUFFERS + 2 * maxNumFileHandles; int bufferSize = (int) (totalMemory / desiredBuffers); if (bufferSize < MIN_IO_BUFFER_SIZE) { bufferSize = MIN_IO_BUFFER_SIZE; if (totalMemory / minBuffers < MIN_IO_BUFFER_SIZE) { maxNumFileHandles = (int) (totalMemory / MIN_IO_BUFFER_SIZE) - NUM_WRITE_BUFFERS; if (LOG.isWarnEnabled()) LOG.warn("Reducing maximal merge fan-in to " + maxNumFileHandles + " due to memory limitations."); } } else { bufferSize = Math.min(MAX_IO_BUFFER_SIZE, MathUtils.roundDownToPowerOf2(bufferSize)); } if (maxWriteMem < 0) { maxWriteMem = Math.max(totalMemory / 64, MIN_WRITE_MEM); } this.ioBufferSize = Math.min(bufferSize, MathUtils.roundDownToPowerOf2((int) (maxWriteMem / NUM_WRITE_BUFFERS))); maxWriteMem = NUM_WRITE_BUFFERS * this.ioBufferSize; } else { // no I/O happening this.ioBufferSize = -1; } final long sortMem = totalMemory - maxWriteMem; final long numSortMemSegments = sortMem / SORT_MEM_SEGMENT_SIZE; // decide how many sort buffers to use if (numSortBuffers < 1) { if (sortMem > 96 * 1024 * 1024) { numSortBuffers = 3; } else if (numSortMemSegments >= 2 * MIN_NUM_SORT_MEM_SEGMENTS) { numSortBuffers = 2; } else { numSortBuffers = 1; } } final int numSegmentsPerSortBuffer = numSortMemSegments / numSortBuffers > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) (numSortMemSegments / numSortBuffers); if (LOG.isDebugEnabled()) { LOG.debug("Instantiating unilateral sort-merger with " + maxWriteMem + " bytes of write cache and " + sortMem + " bytes of sorting/merging memory. Dividing sort memory over " + numSortBuffers + " buffers (" + numSegmentsPerSortBuffer + " pages with " + SORT_MEM_SEGMENT_SIZE + " bytes) , merging maximally " + maxNumFileHandles + " streams at once."); } // circular queues pass buffers between the threads final CircularQueues circularQueues = new CircularQueues(); this.sortBuffers = new ArrayList<NormalizedKeySorter<?>>(numSortBuffers); <MASK>final PactRecordAccessors accessors = new PactRecordAccessors(keyPositions, keyClasses);</MASK> // allocate the sort buffers and fill empty queue with them for (int i = 0; i < numSortBuffers; i++) { final List<MemorySegment> sortSegments = memoryManager.allocateStrict(parentTask, numSegmentsPerSortBuffer, SORT_MEM_SEGMENT_SIZE); final NormalizedKeySorter<PactRecord> buffer = new NormalizedKeySorter<PactRecord>(accessors, sortSegments); this.sortBuffers.add(buffer); // add to empty queue CircularElement element = new CircularElement(i, buffer); circularQueues.empty.add(element); } // exception handling ExceptionHandler<IOException> exceptionHandler = new ExceptionHandler<IOException>() { public void handleException(IOException exception) { // forward exception if (!closed) { setResultIteratorException(exception); close(); } } }; // start the thread that reads the input channels this.readThread = getReadingThread(exceptionHandler, input, circularQueues, parentTask, ((long) (startSpillingFraction * sortMem))); // start the thread that sorts the buffers this.sortThread = getSortingThread(exceptionHandler, circularQueues, parentTask); // start the thread that handles spilling to secondary storage this.spillThread = getSpillingThread(exceptionHandler, circularQueues, memoryManager, ioManager, sortMem, parentTask); startThreads(); }"
Inversion-Mutation
megadiff
"private void showDiff(RevCommit c) throws IOException { final RevTree a = c.getParent(0).getTree(); final RevTree b = c.getTree(); if (showNameAndStatusOnly) Diff.nameStatus(out, diffFmt.scan(a, b)); else { out.flush(); diffFmt.format(a, b); diffFmt.flush(); } out.println(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "showDiff"
"private void showDiff(RevCommit c) throws IOException { final RevTree a = c.getParent(0).getTree(); final RevTree b = c.getTree(); if (showNameAndStatusOnly) Diff.nameStatus(out, diffFmt.scan(a, b)); else { diffFmt.format(a, b); diffFmt.flush(); } out.println(); <MASK>out.flush();</MASK> }"
Inversion-Mutation
megadiff
"public static String getServerLocation() { if (!initialized) { try { //make sure the http registry is started ensureBundleStarted(EQUINOX_HTTP_JETTY); ensureBundleStarted(EQUINOX_HTTP_REGISTRY); //get the webide bundle started via lazy activation. org.eclipse.orion.server.authentication.Activator.getDefault(); Activator.getDefault(); ConfiguratorActivator.getDefault(); webapp = new WebApplication(); webapp.start(null); initialize(); } catch (Exception e) { e.printStackTrace(); return null; } } return "http://" + serverHost + ':' + String.valueOf(serverPort); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getServerLocation"
"public static String getServerLocation() { if (!initialized) { try { <MASK>initialize();</MASK> //make sure the http registry is started ensureBundleStarted(EQUINOX_HTTP_JETTY); ensureBundleStarted(EQUINOX_HTTP_REGISTRY); //get the webide bundle started via lazy activation. org.eclipse.orion.server.authentication.Activator.getDefault(); Activator.getDefault(); ConfiguratorActivator.getDefault(); webapp = new WebApplication(); webapp.start(null); } catch (Exception e) { e.printStackTrace(); return null; } } return "http://" + serverHost + ':' + String.valueOf(serverPort); }"
Inversion-Mutation
megadiff
"public void configure() throws CoreException { /*since we reuse the dynamic web project,we need to identify it when adding the project nature to do that we keep this variable as a switch*/ JavaUtils.isWebApp = true; addJavaProjectNature(); try { updatePom(); } catch (Exception e) { log.error(e.getMessage(), e); } JavaUtils.isWebApp = false; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "configure"
"public void configure() throws CoreException { /*since we reuse the dynamic web project,we need to identify it when adding the project nature to do that we keep this variable as a switch*/ JavaUtils.isWebApp = true; addJavaProjectNature(); <MASK>JavaUtils.isWebApp = false;</MASK> try { updatePom(); } catch (Exception e) { log.error(e.getMessage(), e); } }"
Inversion-Mutation
megadiff
"@Override public void execute() { if (addProduct != null) { addProduct.execute(); product = addProduct.getProduct(); } if (!addedItems.isEmpty()) { for (Item item : addedItems) { container.add(item); itemManager.manage(item); BarcodePrinter.getInstance().addItemToBatch(item); } } else { for (int i = 0; i < count; i++) { Item item = new Item(product, container, entryDate, itemManager); addedItems.add(item); BarcodePrinter.getInstance().addItemToBatch(item); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "execute"
"@Override public void execute() { if (addProduct != null) { addProduct.execute(); product = addProduct.getProduct(); } if (!addedItems.isEmpty()) { for (Item item : addedItems) { <MASK>itemManager.manage(item);</MASK> container.add(item); BarcodePrinter.getInstance().addItemToBatch(item); } } else { for (int i = 0; i < count; i++) { Item item = new Item(product, container, entryDate, itemManager); addedItems.add(item); BarcodePrinter.getInstance().addItemToBatch(item); } } }"
Inversion-Mutation
megadiff
"@Override protected void closeWebSocket() throws WebSocketException { transitionTo(State.CLOSING); pipeline.sendUpstream(this, null, new CloseFrame()); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "closeWebSocket"
"@Override protected void closeWebSocket() throws WebSocketException { <MASK>pipeline.sendUpstream(this, null, new CloseFrame());</MASK> transitionTo(State.CLOSING); }"
Inversion-Mutation
megadiff
"private void visitClassInternal(ClassNode node) { visitAnnotations(node); VariableScope scope = scopes.peek(); TypeLookupResult result = null; result = new TypeLookupResult(node, node, node, TypeConfidence.EXACT, scope); VisitStatus status = handleRequestor(node, requestor, result); switch (status) { case CONTINUE: break; case CANCEL_BRANCH: return; case STOP_VISIT: throw new VisitCompleted(); } if (!node.isEnum()) { visitGenerics(node); visitClassReference(node.getUnresolvedSuperClass()); } for (ClassNode intr : node.getInterfaces()) { visitClassReference(intr); } // add all methods to the scope because when they are // referenced without parens, they appear // as VariableExpressions in the code VariableScope currentScope = scope; // don't use Java 5 style for loop here because Groovy 1.6.x does not // have type parameters for its getMethods() method. for (Iterator methodIter = node.getMethods().iterator(); methodIter.hasNext();) { MethodNode method = (MethodNode) methodIter.next(); currentScope.addVariable(method.getName(), method.getReturnType(), method.getDeclaringClass()); } // visit <clinit> body because this is where static field initializers are placed MethodNode clinit = node.getMethod("<clinit>", new Parameter[0]); if (clinit != null && clinit.getCode() instanceof BlockStatement) { for (Statement element : (Iterable<Statement>) ((BlockStatement) clinit.getCode()).getStatements()) { element.visit(this); } } for (Statement element : (Iterable<Statement>) node.getObjectInitializerStatements()) { element.visit(this); } // visit synthetic no-arg constructors because that's where the non-static initializers are for (ConstructorNode constructor : (Iterable<ConstructorNode>) node.getDeclaredConstructors()) { if (constructor.isSynthetic() && (constructor.getParameters() == null || constructor.getParameters().length == 0)) { visitConstructor(constructor); } } // don't visit contents, the visitJDT methods are used instead }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "visitClassInternal"
"private void visitClassInternal(ClassNode node) { visitAnnotations(node); TypeLookupResult result = null; <MASK>VariableScope scope = scopes.peek();</MASK> result = new TypeLookupResult(node, node, node, TypeConfidence.EXACT, scope); VisitStatus status = handleRequestor(node, requestor, result); switch (status) { case CONTINUE: break; case CANCEL_BRANCH: return; case STOP_VISIT: throw new VisitCompleted(); } if (!node.isEnum()) { visitGenerics(node); visitClassReference(node.getUnresolvedSuperClass()); } for (ClassNode intr : node.getInterfaces()) { visitClassReference(intr); } // add all methods to the scope because when they are // referenced without parens, they appear // as VariableExpressions in the code VariableScope currentScope = scope; // don't use Java 5 style for loop here because Groovy 1.6.x does not // have type parameters for its getMethods() method. for (Iterator methodIter = node.getMethods().iterator(); methodIter.hasNext();) { MethodNode method = (MethodNode) methodIter.next(); currentScope.addVariable(method.getName(), method.getReturnType(), method.getDeclaringClass()); } // visit <clinit> body because this is where static field initializers are placed MethodNode clinit = node.getMethod("<clinit>", new Parameter[0]); if (clinit != null && clinit.getCode() instanceof BlockStatement) { for (Statement element : (Iterable<Statement>) ((BlockStatement) clinit.getCode()).getStatements()) { element.visit(this); } } for (Statement element : (Iterable<Statement>) node.getObjectInitializerStatements()) { element.visit(this); } // visit synthetic no-arg constructors because that's where the non-static initializers are for (ConstructorNode constructor : (Iterable<ConstructorNode>) node.getDeclaredConstructors()) { if (constructor.isSynthetic() && (constructor.getParameters() == null || constructor.getParameters().length == 0)) { visitConstructor(constructor); } } // don't visit contents, the visitJDT methods are used instead }"
Inversion-Mutation
megadiff
"private static IScope getContainingScopeOrNull(IASTName name) { if (name == null) { return null; } IASTNode parent = name.getParent(); try { if (parent instanceof ICPPASTTemplateId) { name = (IASTName) parent; parent = name.getParent(); } ICPPASTTemplateDeclaration tmplDecl = CPPTemplates.getTemplateDeclaration(name); if (tmplDecl != null) return tmplDecl.getScope(); if (parent instanceof ICPPASTQualifiedName) { final ICPPASTQualifiedName qname= (ICPPASTQualifiedName) parent; final IASTName[] names = qname.getNames(); int i = 0; for (; i < names.length; i++) { if (names[i] == name) break; } if (i == 0) { if (qname.isFullyQualified()) { return parent.getTranslationUnit().getScope(); } for (int j=1; j < names.length; j++) { tmplDecl = CPPTemplates.getTemplateDeclaration(names[j]); if (tmplDecl != null) { return getContainingScope(tmplDecl); } } } if (i > 0) { IBinding binding = names[i-1].resolveBinding(); while (binding instanceof ITypedef) { IType t = ((ITypedef)binding).getType(); if (t instanceof IBinding) binding = (IBinding) t; else break; } boolean done= true; IScope scope= null; if (binding instanceof ICPPClassType) { scope= ((ICPPClassType)binding).getCompositeScope(); } else if (binding instanceof ICPPNamespace) { scope= ((ICPPNamespace)binding).getNamespaceScope(); } else if (binding instanceof ICPPUnknownBinding) { scope= ((ICPPUnknownBinding)binding).getUnknownScope(); } else if (binding instanceof IProblemBinding) { if (binding instanceof ICPPScope) scope= (IScope) binding; } else { done= false; } if (done) { if (scope == null) { return new CPPScope.CPPScopeProblem(names[i - 1], IProblemBinding.SEMANTIC_BAD_SCOPE, names[i-1].toCharArray()); } return scope; } } } else if (parent instanceof ICPPASTFieldReference) { final ICPPASTFieldReference fieldReference = (ICPPASTFieldReference)parent; IASTExpression owner = fieldReference.getFieldOwner(); IType type = getExpressionType(owner); if (fieldReference.isPointerDereference()) { // bug 205964: as long as the type is a class type, recurse. // Be defensive and allow a max of 10 levels. for (int j = 0; j < 10; j++) { type= getUltimateTypeUptoPointers(type); if (type instanceof ICPPClassType) { ICPPFunction op = CPPSemantics.findOperator(fieldReference, (ICPPClassType) type); if (op != null) { type = op.getType().getReturnType(); } } else { break; } } } type = getUltimateType(type, false); if (type instanceof ICPPClassType) { return ((ICPPClassType) type).getCompositeScope(); } } else if (parent instanceof IASTGotoStatement || parent instanceof IASTLabelStatement) { while (!(parent instanceof IASTFunctionDefinition)) { parent = parent.getParent(); } IASTFunctionDefinition fdef = (IASTFunctionDefinition) parent; return ((ICPPASTFunctionDeclarator)fdef.getDeclarator()).getFunctionScope(); } } catch (DOMException e) { IProblemBinding problem = e.getProblem(); if (problem instanceof ICPPScope) return problem; return new CPPScope.CPPScopeProblem(problem.getASTNode(), problem.getID(), problem.getNameCharArray()); } return getContainingScope(parent); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getContainingScopeOrNull"
"private static IScope getContainingScopeOrNull(IASTName name) { if (name == null) { return null; } IASTNode parent = name.getParent(); try { if (parent instanceof ICPPASTTemplateId) { name = (IASTName) parent; parent = name.getParent(); } ICPPASTTemplateDeclaration tmplDecl = CPPTemplates.getTemplateDeclaration(name); if (tmplDecl != null) return tmplDecl.getScope(); if (parent instanceof ICPPASTQualifiedName) { final ICPPASTQualifiedName qname= (ICPPASTQualifiedName) parent; final IASTName[] names = qname.getNames(); int i = 0; for (; i < names.length; i++) { if (names[i] == name) break; } if (i == 0) { if (qname.isFullyQualified()) { return parent.getTranslationUnit().getScope(); } for (int j=1; j < names.length; j++) { tmplDecl = CPPTemplates.getTemplateDeclaration(names[j]); if (tmplDecl != null) { return getContainingScope(tmplDecl); } } } if (i > 0) { IBinding binding = names[i-1].resolveBinding(); while (binding instanceof ITypedef) { IType t = ((ITypedef)binding).getType(); if (t instanceof IBinding) binding = (IBinding) t; else break; } boolean done= true; IScope scope= null; if (binding instanceof ICPPClassType) { scope= ((ICPPClassType)binding).getCompositeScope(); } else if (binding instanceof ICPPNamespace) { scope= ((ICPPNamespace)binding).getNamespaceScope(); } else if (binding instanceof ICPPUnknownBinding) { scope= ((ICPPUnknownBinding)binding).getUnknownScope(); } else if (binding instanceof IProblemBinding) { if (binding instanceof ICPPScope) scope= (IScope) binding; } else { done= false; } if (done) { if (scope == null) { return new CPPScope.CPPScopeProblem(names[i - 1], IProblemBinding.SEMANTIC_BAD_SCOPE, names[i-1].toCharArray()); } return scope; } } } else if (parent instanceof ICPPASTFieldReference) { final ICPPASTFieldReference fieldReference = (ICPPASTFieldReference)parent; IASTExpression owner = fieldReference.getFieldOwner(); IType type = getExpressionType(owner); if (fieldReference.isPointerDereference()) { <MASK>type= getUltimateTypeUptoPointers(type);</MASK> // bug 205964: as long as the type is a class type, recurse. // Be defensive and allow a max of 10 levels. for (int j = 0; j < 10; j++) { if (type instanceof ICPPClassType) { ICPPFunction op = CPPSemantics.findOperator(fieldReference, (ICPPClassType) type); if (op != null) { type = op.getType().getReturnType(); } } else { break; } } } type = getUltimateType(type, false); if (type instanceof ICPPClassType) { return ((ICPPClassType) type).getCompositeScope(); } } else if (parent instanceof IASTGotoStatement || parent instanceof IASTLabelStatement) { while (!(parent instanceof IASTFunctionDefinition)) { parent = parent.getParent(); } IASTFunctionDefinition fdef = (IASTFunctionDefinition) parent; return ((ICPPASTFunctionDeclarator)fdef.getDeclarator()).getFunctionScope(); } } catch (DOMException e) { IProblemBinding problem = e.getProblem(); if (problem instanceof ICPPScope) return problem; return new CPPScope.CPPScopeProblem(problem.getASTNode(), problem.getID(), problem.getNameCharArray()); } return getContainingScope(parent); }"
Inversion-Mutation
megadiff
"@Override protected String getInsertStatement(InsertOrUpdateStatement insertOrUpdateStatement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer sql = new StringBuffer(super.getInsertStatement(insertOrUpdateStatement, database, sqlGeneratorChain)); sql.deleteCharAt(sql.lastIndexOf(";")); StringBuffer updateClause = new StringBuffer("ON DUPLICATE KEY UPDATE "); String[] pkFields=insertOrUpdateStatement.getPrimaryKey().split(","); HashSet<String> hashPkFields = new HashSet<String>(Arrays.asList(pkFields)); boolean hasFields = false; for(String columnKey:insertOrUpdateStatement.getColumnValues().keySet()) { if (!hashPkFields.contains(columnKey)) { hasFields = true; updateClause.append(columnKey).append(" = "); updateClause.append(convertToString(insertOrUpdateStatement.getColumnValue(columnKey),database)); updateClause.append(","); } } if(hasFields) { // append the updateClause onto the end of the insert statement updateClause.deleteCharAt(updateClause.lastIndexOf(",")); sql.append(updateClause); } else { // insert IGNORE keyword into insert statement sql.insert(sql.indexOf("INSERT ")+"INSERT ".length(), "IGNORE "); } return sql.toString(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getInsertStatement"
"@Override protected String getInsertStatement(InsertOrUpdateStatement insertOrUpdateStatement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer sql = new StringBuffer(super.getInsertStatement(insertOrUpdateStatement, database, sqlGeneratorChain)); sql.deleteCharAt(sql.lastIndexOf(";")); StringBuffer updateClause = new StringBuffer("ON DUPLICATE KEY UPDATE "); String[] pkFields=insertOrUpdateStatement.getPrimaryKey().split(","); HashSet<String> hashPkFields = new HashSet<String>(Arrays.asList(pkFields)); boolean hasFields = false; for(String columnKey:insertOrUpdateStatement.getColumnValues().keySet()) { if (!hashPkFields.contains(columnKey)) { hasFields = true; updateClause.append(columnKey).append(" = "); updateClause.append(convertToString(insertOrUpdateStatement.getColumnValue(columnKey),database)); updateClause.append(","); } } <MASK>updateClause.deleteCharAt(updateClause.lastIndexOf(","));</MASK> if(hasFields) { // append the updateClause onto the end of the insert statement sql.append(updateClause); } else { // insert IGNORE keyword into insert statement sql.insert(sql.indexOf("INSERT ")+"INSERT ".length(), "IGNORE "); } return sql.toString(); }"
Inversion-Mutation
megadiff
"public void executeAfpEngine(AfpProcessProgress progress){ if (afpNode != null ){ parameters = new HashMap<String, String>(); parameters.put(ControlFileProperties.SITE_SPACING, "2"); parameters.put(ControlFileProperties.CELL_SPACING, "0"); parameters.put(ControlFileProperties.REG_NBR_SPACING, "1"); parameters.put(ControlFileProperties.MIN_NEIGBOUR_SPACING, "0"); parameters.put(ControlFileProperties.SECOND_NEIGHBOUR_SPACING, "1"); parameters.put(ControlFileProperties.QUALITY, "100"); parameters.put(ControlFileProperties.G_MAX_RT_PER_CELL, "5"); parameters.put(ControlFileProperties.G_MAX_RT_PER_SITE, "5"); parameters.put(ControlFileProperties.HOPPING_TYPE, "1"); parameters.put(ControlFileProperties.NUM_GROUPS, "6"); parameters.put(ControlFileProperties.CELL_CARDINALITY, "61"); StringBuffer carriers = new StringBuffer(); int cnt =0; boolean first = true; for(int i=0; i< frequencyBands.length;i++) { if(frequencyBands[i]) { String freq = this.availableFreq[i]; String[] franges = freq.split(","); String[] freqList = rangeArraytoArray(franges); for(String f: freqList) { if(!first) { carriers.append(","); } carriers.append(f); cnt++; first = false; } } } parameters.put(ControlFileProperties.CARRIERS, carriers.toString()); parameters.put(ControlFileProperties.USE_GROUPING, "1"); parameters.put(ControlFileProperties.EXIST_CLIQUES, "0"); parameters.put(ControlFileProperties.RECALCULATE_ALL, "1" ); parameters.put(ControlFileProperties.USE_TRAFFIC, "1"); parameters.put(ControlFileProperties.USE_SO_NEIGHBOURS, "1"); parameters.put(ControlFileProperties.DECOMPOSE_CLIQUES, "0"); afpJob = new AfpProcessExecutor("Execute Afp Process", datasetNode,this.afpNode, service, parameters); afpJob.setProgress(progress); //afpJob.schedule(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "executeAfpEngine"
"public void executeAfpEngine(AfpProcessProgress progress){ if (afpNode != null ){ parameters = new HashMap<String, String>(); parameters.put(ControlFileProperties.SITE_SPACING, "2"); parameters.put(ControlFileProperties.CELL_SPACING, "0"); parameters.put(ControlFileProperties.REG_NBR_SPACING, "1"); parameters.put(ControlFileProperties.MIN_NEIGBOUR_SPACING, "0"); parameters.put(ControlFileProperties.SECOND_NEIGHBOUR_SPACING, "1"); parameters.put(ControlFileProperties.QUALITY, "100"); parameters.put(ControlFileProperties.G_MAX_RT_PER_CELL, "5"); parameters.put(ControlFileProperties.G_MAX_RT_PER_SITE, "5"); parameters.put(ControlFileProperties.HOPPING_TYPE, "1"); parameters.put(ControlFileProperties.NUM_GROUPS, "6"); parameters.put(ControlFileProperties.CELL_CARDINALITY, "61"); StringBuffer carriers = new StringBuffer(); int cnt =0; for(int i=0; i< frequencyBands.length;i++) { if(frequencyBands[i]) { String freq = this.availableFreq[i]; String[] franges = freq.split(","); <MASK>boolean first = true;</MASK> String[] freqList = rangeArraytoArray(franges); for(String f: freqList) { if(!first) { carriers.append(","); } carriers.append(f); cnt++; first = false; } } } parameters.put(ControlFileProperties.CARRIERS, carriers.toString()); parameters.put(ControlFileProperties.USE_GROUPING, "1"); parameters.put(ControlFileProperties.EXIST_CLIQUES, "0"); parameters.put(ControlFileProperties.RECALCULATE_ALL, "1" ); parameters.put(ControlFileProperties.USE_TRAFFIC, "1"); parameters.put(ControlFileProperties.USE_SO_NEIGHBOURS, "1"); parameters.put(ControlFileProperties.DECOMPOSE_CLIQUES, "0"); afpJob = new AfpProcessExecutor("Execute Afp Process", datasetNode,this.afpNode, service, parameters); afpJob.setProgress(progress); //afpJob.schedule(); } }"
Inversion-Mutation
megadiff
"private void parseObjectBlock(SunflowAPI api) throws ParserException, IOException { p.checkNextToken("{"); boolean noInstance = false; Matrix4 transform = null; String name = null; String[] shaders = null; String[] modifiers = null; if (p.peekNextToken("noinstance")) { // this indicates that the geometry is to be created, but not // instanced into the scene noInstance = true; } else { // these are the parameters to be passed to the instance if (p.peekNextToken("shaders")) { int n = p.getNextInt(); shaders = new String[n]; for (int i = 0; i < n; i++) shaders[i] = p.getNextToken(); } else { p.checkNextToken("shader"); shaders = new String[] { p.getNextToken() }; } if (p.peekNextToken("modifiers")) { int n = p.getNextInt(); modifiers = new String[n]; for (int i = 0; i < n; i++) modifiers[i] = p.getNextToken(); } else if (p.peekNextToken("modifier")) modifiers = new String[] { p.getNextToken() }; if (p.peekNextToken("transform")) transform = parseMatrix(); } if (p.peekNextToken("accel")) api.parameter("accel", p.getNextToken()); p.checkNextToken("type"); String type = p.getNextToken(); if (p.peekNextToken("name")) name = p.getNextToken(); else name = api.getUniqueName(type); if (type.equals("mesh")) { UI.printWarning(Module.API, "Deprecated object type: mesh"); UI.printInfo(Module.API, "Reading mesh: %s ...", name); int numVertices = p.getNextInt(); int numTriangles = p.getNextInt(); float[] points = new float[numVertices * 3]; float[] normals = new float[numVertices * 3]; float[] uvs = new float[numVertices * 2]; for (int i = 0; i < numVertices; i++) { p.checkNextToken("v"); points[3 * i + 0] = p.getNextFloat(); points[3 * i + 1] = p.getNextFloat(); points[3 * i + 2] = p.getNextFloat(); normals[3 * i + 0] = p.getNextFloat(); normals[3 * i + 1] = p.getNextFloat(); normals[3 * i + 2] = p.getNextFloat(); uvs[2 * i + 0] = p.getNextFloat(); uvs[2 * i + 1] = p.getNextFloat(); } int[] triangles = new int[numTriangles * 3]; for (int i = 0; i < numTriangles; i++) { p.checkNextToken("t"); triangles[i * 3 + 0] = p.getNextInt(); triangles[i * 3 + 1] = p.getNextInt(); triangles[i * 3 + 2] = p.getNextInt(); } // create geometry api.parameter("triangles", triangles); api.parameter("points", "point", "vertex", points); api.parameter("normals", "vector", "vertex", normals); api.parameter("uvs", "texcoord", "vertex", uvs); api.geometry(name, new TriangleMesh()); } else if (type.equals("flat-mesh")) { UI.printWarning(Module.API, "Deprecated object type: flat-mesh"); UI.printInfo(Module.API, "Reading flat mesh: %s ...", name); int numVertices = p.getNextInt(); int numTriangles = p.getNextInt(); float[] points = new float[numVertices * 3]; float[] uvs = new float[numVertices * 2]; for (int i = 0; i < numVertices; i++) { p.checkNextToken("v"); points[3 * i + 0] = p.getNextFloat(); points[3 * i + 1] = p.getNextFloat(); points[3 * i + 2] = p.getNextFloat(); p.getNextFloat(); p.getNextFloat(); p.getNextFloat(); uvs[2 * i + 0] = p.getNextFloat(); uvs[2 * i + 1] = p.getNextFloat(); } int[] triangles = new int[numTriangles * 3]; for (int i = 0; i < numTriangles; i++) { p.checkNextToken("t"); triangles[i * 3 + 0] = p.getNextInt(); triangles[i * 3 + 1] = p.getNextInt(); triangles[i * 3 + 2] = p.getNextInt(); } // create geometry api.parameter("triangles", triangles); api.parameter("points", "point", "vertex", points); api.parameter("uvs", "texcoord", "vertex", uvs); api.geometry(name, new TriangleMesh()); } else if (type.equals("sphere")) { UI.printInfo(Module.API, "Reading sphere ..."); api.geometry(name, new Sphere()); if (transform == null && !noInstance) { // legacy method of specifying transformation for spheres p.checkNextToken("c"); float x = p.getNextFloat(); float y = p.getNextFloat(); float z = p.getNextFloat(); p.checkNextToken("r"); float radius = p.getNextFloat(); api.parameter("transform", Matrix4.translation(x, y, z).multiply(Matrix4.scale(radius))); api.parameter("shaders", shaders); if (modifiers != null) api.parameter("modifiers", modifiers); api.instance(name + ".instance", name); noInstance = true; // disable future auto-instancing because // instance has already been created } } else if (type.equals("banchoff")) { UI.printInfo(Module.API, "Reading banchoff ..."); api.geometry(name, new BanchoffSurface()); } else if (type.equals("torus")) { UI.printInfo(Module.API, "Reading torus ..."); p.checkNextToken("r"); api.parameter("radiusInner", p.getNextFloat()); api.parameter("radiusOuter", p.getNextFloat()); api.geometry(name, new Torus()); } else if (type.equals("plane")) { UI.printInfo(Module.API, "Reading plane ..."); p.checkNextToken("p"); api.parameter("center", parsePoint()); if (p.peekNextToken("n")) { api.parameter("normal", parseVector()); } else { p.checkNextToken("p"); api.parameter("point1", parsePoint()); p.checkNextToken("p"); api.parameter("point2", parsePoint()); } api.geometry(name, new Plane()); } else if (type.equals("cornellbox")) { UI.printInfo(Module.API, "Reading cornell box ..."); if (transform != null) UI.printWarning(Module.API, "Instancing is not supported on cornell box -- ignoring transform"); p.checkNextToken("corner0"); api.parameter("corner0", parsePoint()); p.checkNextToken("corner1"); api.parameter("corner1", parsePoint()); p.checkNextToken("left"); api.parameter("leftColor", parseColor()); p.checkNextToken("right"); api.parameter("rightColor", parseColor()); p.checkNextToken("top"); api.parameter("topColor", parseColor()); p.checkNextToken("bottom"); api.parameter("bottomColor", parseColor()); p.checkNextToken("back"); api.parameter("backColor", parseColor()); p.checkNextToken("emit"); api.parameter("radiance", parseColor()); if (p.peekNextToken("samples")) api.parameter("samples", p.getNextInt()); new CornellBox().init(name, api); noInstance = true; // instancing is handled natively by the init // method } else if (type.equals("generic-mesh")) { UI.printInfo(Module.API, "Reading generic mesh: %s ... ", name); // parse vertices p.checkNextToken("points"); int np = p.getNextInt(); api.parameter("points", "point", "vertex", parseFloatArray(np * 3)); // parse triangle indices p.checkNextToken("triangles"); int nt = p.getNextInt(); api.parameter("triangles", parseIntArray(nt * 3)); // parse normals p.checkNextToken("normals"); if (p.peekNextToken("vertex")) api.parameter("normals", "vector", "vertex", parseFloatArray(np * 3)); else if (p.peekNextToken("facevarying")) api.parameter("normals", "vector", "facevarying", parseFloatArray(nt * 9)); else p.checkNextToken("none"); // parse texture coordinates p.checkNextToken("uvs"); if (p.peekNextToken("vertex")) api.parameter("uvs", "texcoord", "vertex", parseFloatArray(np * 2)); else if (p.peekNextToken("facevarying")) api.parameter("uvs", "texcoord", "facevarying", parseFloatArray(nt * 6)); else p.checkNextToken("none"); if (p.peekNextToken("face_shaders")) api.parameter("faceshaders", parseIntArray(nt)); api.geometry(name, new TriangleMesh()); } else if (type.equals("hair")) { UI.printInfo(Module.API, "Reading hair curves: %s ... ", name); p.checkNextToken("segments"); api.parameter("segments", p.getNextInt()); p.checkNextToken("width"); api.parameter("widths", p.getNextFloat()); p.checkNextToken("points"); api.parameter("points", "point", "vertex", parseFloatArray(p.getNextInt())); api.geometry(name, new Hair()); } else if (type.equals("janino-tesselatable")) { UI.printInfo(Module.API, "Reading procedural primitive: %s ... ", name); String code = p.getNextCodeBlock(); try { Tesselatable tess = (Tesselatable) ClassBodyEvaluator.createFastClassBodyEvaluator(new Scanner(null, new StringReader(code)), Tesselatable.class, ClassLoader.getSystemClassLoader()); api.geometry(name, tess); } catch (CompileException e) { UI.printDetailed(Module.API, "Compiling: %s", code); UI.printError(Module.API, "%s", e.getMessage()); e.printStackTrace(); noInstance = true; } catch (ParseException e) { UI.printDetailed(Module.API, "Compiling: %s", code); UI.printError(Module.API, "%s", e.getMessage()); e.printStackTrace(); noInstance = true; } catch (ScanException e) { UI.printDetailed(Module.API, "Compiling: %s", code); UI.printError(Module.API, "%s", e.getMessage()); e.printStackTrace(); noInstance = true; } catch (IOException e) { UI.printDetailed(Module.API, "Compiling: %s", code); UI.printError(Module.API, "%s", e.getMessage()); e.printStackTrace(); noInstance = true; } } else if (type.equals("teapot")) { UI.printInfo(Module.API, "Reading teapot: %s ... ", name); boolean hasTesselationArguments = false; if (p.peekNextToken("subdivs")) { api.parameter("subdivs", p.getNextInt()); hasTesselationArguments = true; } if (p.peekNextToken("smooth")) { api.parameter("smooth", p.getNextBoolean()); hasTesselationArguments = true; } if (hasTesselationArguments) api.geometry(name, (Tesselatable) new Teapot()); else api.geometry(name, (PrimitiveList) new Teapot()); } else if (type.equals("gumbo")) { UI.printInfo(Module.API, "Reading gumbo: %s ... ", name); boolean hasTesselationArguments = false; if (p.peekNextToken("subdivs")) { api.parameter("subdivs", p.getNextInt()); hasTesselationArguments = true; } if (p.peekNextToken("smooth")) { api.parameter("smooth", p.getNextBoolean()); hasTesselationArguments = true; } if (hasTesselationArguments) api.geometry(name, (Tesselatable) new Gumbo()); else api.geometry(name, (PrimitiveList) new Gumbo()); } else if (type.equals("julia")) { UI.printInfo(Module.API, "Reading julia fractal: %s ... ", name); if (p.peekNextToken("q")) { api.parameter("cw", p.getNextFloat()); api.parameter("cx", p.getNextFloat()); api.parameter("cy", p.getNextFloat()); api.parameter("cz", p.getNextFloat()); } if (p.peekNextToken("iterations")) api.parameter("iterations", p.getNextInt()); if (p.peekNextToken("epsilon")) api.parameter("epsilon", p.getNextFloat()); api.geometry(name, new JuliaFractal()); } else if (type.equals("particles") || type.equals("dlasurface")) { if (type.equals("dlasurface")) UI.printWarning(Module.API, "Deprecated object type: \"dlasurface\" - please use \"particles\" instead"); float[] data; if (p.peekNextToken("filename")) { String filename = api.resolveIncludeFilename(p.getNextToken()); boolean littleEndian = false; if (p.peekNextToken("little_endian")) littleEndian = true; UI.printInfo(Module.USER, "Loading particle file: %s", filename); File file = new File(filename); FileInputStream stream = new FileInputStream(filename); MappedByteBuffer map = stream.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length()); if (littleEndian) map.order(ByteOrder.LITTLE_ENDIAN); FloatBuffer buffer = map.asFloatBuffer(); data = new float[buffer.capacity()]; for (int i = 0; i < data.length; i++) data[i] = buffer.get(i); stream.close(); } else { p.checkNextToken("points"); int n = p.getNextInt(); data = parseFloatArray(n * 3); // read 3n points } api.parameter("particles", "point", "vertex", data); if (p.peekNextToken("num")) api.parameter("num", p.getNextInt()); else api.parameter("num", data.length / 3); p.checkNextToken("radius"); api.parameter("radius", p.getNextFloat()); api.geometry(name, new ParticleSurface()); } else if (type.equals("file-mesh")) { UI.printInfo(Module.API, "Reading file mesh: %s ... ", name); p.checkNextToken("filename"); api.parameter("filename", p.getNextToken()); if (p.peekNextToken("smooth_normals")) api.parameter("smooth_normals", p.getNextBoolean()); api.geometry(name, new FileMesh()); } else if (type.equals("bezier-mesh")) { UI.printInfo(Module.API, "Reading bezier mesh: %s ... ", name); p.checkNextToken("n"); int nu, nv; api.parameter("nu", nu = p.getNextInt()); api.parameter("nv", nv = p.getNextInt()); if (p.peekNextToken("wrap")) { api.parameter("uwrap", p.getNextBoolean()); api.parameter("vwrap", p.getNextBoolean()); } p.checkNextToken("points"); float[] points = new float[3 * nu * nv]; for (int i = 0; i < points.length; i++) points[i] = p.getNextFloat(); api.parameter("points", "point", "vertex", points); if (p.peekNextToken("subdivs")) api.parameter("subdivs", p.getNextInt()); if (p.peekNextToken("smooth")) api.parameter("smooth", p.getNextBoolean()); api.geometry(name, (Tesselatable) new BezierMesh()); } else { UI.printWarning(Module.API, "Unrecognized object type: %s", p.getNextToken()); noInstance = true; } if (!noInstance) { // create instance api.parameter("shaders", shaders); if (modifiers != null) api.parameter("modifiers", modifiers); if (transform != null) api.parameter("transform", transform); api.instance(name + ".instance", name); } p.checkNextToken("}"); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "parseObjectBlock"
"private void parseObjectBlock(SunflowAPI api) throws ParserException, IOException { p.checkNextToken("{"); boolean noInstance = false; Matrix4 transform = null; String name = null; String[] shaders = null; String[] modifiers = null; if (p.peekNextToken("noinstance")) { // this indicates that the geometry is to be created, but not // instanced into the scene noInstance = true; } else { // these are the parameters to be passed to the instance if (p.peekNextToken("shaders")) { int n = p.getNextInt(); shaders = new String[n]; for (int i = 0; i < n; i++) shaders[i] = p.getNextToken(); } else { p.checkNextToken("shader"); shaders = new String[] { p.getNextToken() }; } if (p.peekNextToken("modifiers")) { int n = p.getNextInt(); modifiers = new String[n]; for (int i = 0; i < n; i++) modifiers[i] = p.getNextToken(); } else if (p.peekNextToken("modifier")) modifiers = new String[] { p.getNextToken() }; if (p.peekNextToken("transform")) transform = parseMatrix(); } if (p.peekNextToken("accel")) api.parameter("accel", p.getNextToken()); p.checkNextToken("type"); String type = p.getNextToken(); if (p.peekNextToken("name")) name = p.getNextToken(); else name = api.getUniqueName(type); if (type.equals("mesh")) { UI.printWarning(Module.API, "Deprecated object type: mesh"); UI.printInfo(Module.API, "Reading mesh: %s ...", name); int numVertices = p.getNextInt(); int numTriangles = p.getNextInt(); float[] points = new float[numVertices * 3]; float[] normals = new float[numVertices * 3]; float[] uvs = new float[numVertices * 2]; for (int i = 0; i < numVertices; i++) { p.checkNextToken("v"); points[3 * i + 0] = p.getNextFloat(); points[3 * i + 1] = p.getNextFloat(); points[3 * i + 2] = p.getNextFloat(); normals[3 * i + 0] = p.getNextFloat(); normals[3 * i + 1] = p.getNextFloat(); normals[3 * i + 2] = p.getNextFloat(); uvs[2 * i + 0] = p.getNextFloat(); uvs[2 * i + 1] = p.getNextFloat(); } int[] triangles = new int[numTriangles * 3]; for (int i = 0; i < numTriangles; i++) { p.checkNextToken("t"); triangles[i * 3 + 0] = p.getNextInt(); triangles[i * 3 + 1] = p.getNextInt(); triangles[i * 3 + 2] = p.getNextInt(); } // create geometry api.parameter("triangles", triangles); api.parameter("points", "point", "vertex", points); api.parameter("normals", "vector", "vertex", normals); api.parameter("uvs", "texcoord", "vertex", uvs); api.geometry(name, new TriangleMesh()); } else if (type.equals("flat-mesh")) { UI.printWarning(Module.API, "Deprecated object type: flat-mesh"); UI.printInfo(Module.API, "Reading flat mesh: %s ...", name); int numVertices = p.getNextInt(); int numTriangles = p.getNextInt(); float[] points = new float[numVertices * 3]; float[] uvs = new float[numVertices * 2]; for (int i = 0; i < numVertices; i++) { p.checkNextToken("v"); points[3 * i + 0] = p.getNextFloat(); points[3 * i + 1] = p.getNextFloat(); points[3 * i + 2] = p.getNextFloat(); p.getNextFloat(); p.getNextFloat(); p.getNextFloat(); uvs[2 * i + 0] = p.getNextFloat(); uvs[2 * i + 1] = p.getNextFloat(); } int[] triangles = new int[numTriangles * 3]; for (int i = 0; i < numTriangles; i++) { p.checkNextToken("t"); triangles[i * 3 + 0] = p.getNextInt(); triangles[i * 3 + 1] = p.getNextInt(); triangles[i * 3 + 2] = p.getNextInt(); } // create geometry api.parameter("triangles", triangles); api.parameter("points", "point", "vertex", points); api.parameter("uvs", "texcoord", "vertex", uvs); api.geometry(name, new TriangleMesh()); } else if (type.equals("sphere")) { UI.printInfo(Module.API, "Reading sphere ..."); api.geometry(name, new Sphere()); if (transform == null && !noInstance) { // legacy method of specifying transformation for spheres p.checkNextToken("c"); float x = p.getNextFloat(); float y = p.getNextFloat(); float z = p.getNextFloat(); p.checkNextToken("r"); float radius = p.getNextFloat(); api.parameter("transform", Matrix4.translation(x, y, z).multiply(Matrix4.scale(radius))); api.parameter("shaders", shaders); if (modifiers != null) api.parameter("modifiers", modifiers); api.instance(name + ".instance", name); noInstance = true; // disable future auto-instancing because // instance has already been created } } else if (type.equals("banchoff")) { UI.printInfo(Module.API, "Reading banchoff ..."); api.geometry(name, new BanchoffSurface()); } else if (type.equals("torus")) { UI.printInfo(Module.API, "Reading torus ..."); p.checkNextToken("r"); api.parameter("radiusInner", p.getNextFloat()); api.parameter("radiusOuter", p.getNextFloat()); api.geometry(name, new Torus()); } else if (type.equals("plane")) { UI.printInfo(Module.API, "Reading plane ..."); p.checkNextToken("p"); api.parameter("center", parsePoint()); if (p.peekNextToken("n")) { api.parameter("normal", parseVector()); } else { p.checkNextToken("p"); api.parameter("point1", parsePoint()); p.checkNextToken("p"); api.parameter("point2", parsePoint()); } api.geometry(name, new Plane()); } else if (type.equals("cornellbox")) { UI.printInfo(Module.API, "Reading cornell box ..."); if (transform != null) UI.printWarning(Module.API, "Instancing is not supported on cornell box -- ignoring transform"); p.checkNextToken("corner0"); api.parameter("corner0", parsePoint()); p.checkNextToken("corner1"); api.parameter("corner1", parsePoint()); p.checkNextToken("left"); api.parameter("leftColor", parseColor()); p.checkNextToken("right"); api.parameter("rightColor", parseColor()); p.checkNextToken("top"); api.parameter("topColor", parseColor()); p.checkNextToken("bottom"); api.parameter("bottomColor", parseColor()); p.checkNextToken("back"); api.parameter("backColor", parseColor()); p.checkNextToken("emit"); api.parameter("radiance", parseColor()); if (p.peekNextToken("samples")) api.parameter("samples", p.getNextInt()); new CornellBox().init(name, api); noInstance = true; // instancing is handled natively by the init // method } else if (type.equals("generic-mesh")) { UI.printInfo(Module.API, "Reading generic mesh: %s ... ", name); // parse vertices p.checkNextToken("points"); int np = p.getNextInt(); api.parameter("points", "point", "vertex", parseFloatArray(np * 3)); // parse triangle indices p.checkNextToken("triangles"); int nt = p.getNextInt(); api.parameter("triangles", parseIntArray(nt * 3)); // parse normals p.checkNextToken("normals"); if (p.peekNextToken("vertex")) api.parameter("normals", "vector", "vertex", parseFloatArray(np * 3)); else if (p.peekNextToken("facevarying")) api.parameter("normals", "vector", "facevarying", parseFloatArray(nt * 9)); else p.checkNextToken("none"); // parse texture coordinates p.checkNextToken("uvs"); if (p.peekNextToken("vertex")) api.parameter("uvs", "texcoord", "vertex", parseFloatArray(np * 2)); else if (p.peekNextToken("facevarying")) api.parameter("uvs", "texcoord", "facevarying", parseFloatArray(nt * 6)); else p.checkNextToken("none"); if (p.peekNextToken("face_shaders")) api.parameter("faceshaders", parseIntArray(nt)); api.geometry(name, new TriangleMesh()); } else if (type.equals("hair")) { UI.printInfo(Module.API, "Reading hair curves: %s ... ", name); p.checkNextToken("segments"); api.parameter("segments", p.getNextInt()); p.checkNextToken("width"); api.parameter("widths", p.getNextFloat()); p.checkNextToken("points"); api.parameter("points", "point", "vertex", parseFloatArray(p.getNextInt())); api.geometry(name, new Hair()); } else if (type.equals("janino-tesselatable")) { UI.printInfo(Module.API, "Reading procedural primitive: %s ... ", name); String code = p.getNextCodeBlock(); try { Tesselatable tess = (Tesselatable) ClassBodyEvaluator.createFastClassBodyEvaluator(new Scanner(null, new StringReader(code)), Tesselatable.class, ClassLoader.getSystemClassLoader()); api.geometry(name, tess); } catch (CompileException e) { UI.printDetailed(Module.API, "Compiling: %s", code); UI.printError(Module.API, "%s", e.getMessage()); e.printStackTrace(); noInstance = true; } catch (ParseException e) { UI.printDetailed(Module.API, "Compiling: %s", code); UI.printError(Module.API, "%s", e.getMessage()); e.printStackTrace(); noInstance = true; } catch (ScanException e) { UI.printDetailed(Module.API, "Compiling: %s", code); UI.printError(Module.API, "%s", e.getMessage()); e.printStackTrace(); noInstance = true; } catch (IOException e) { UI.printDetailed(Module.API, "Compiling: %s", code); UI.printError(Module.API, "%s", e.getMessage()); e.printStackTrace(); noInstance = true; } } else if (type.equals("teapot")) { UI.printInfo(Module.API, "Reading teapot: %s ... ", name); boolean hasTesselationArguments = false; if (p.peekNextToken("subdivs")) { api.parameter("subdivs", p.getNextInt()); hasTesselationArguments = true; } if (p.peekNextToken("smooth")) { api.parameter("smooth", p.getNextBoolean()); hasTesselationArguments = true; } if (hasTesselationArguments) api.geometry(name, (Tesselatable) new Teapot()); else api.geometry(name, (PrimitiveList) new Teapot()); } else if (type.equals("gumbo")) { UI.printInfo(Module.API, "Reading gumbo: %s ... ", name); boolean hasTesselationArguments = false; if (p.peekNextToken("subdivs")) { api.parameter("subdivs", p.getNextInt()); hasTesselationArguments = true; } if (p.peekNextToken("smooth")) { api.parameter("smooth", p.getNextBoolean()); hasTesselationArguments = true; } if (hasTesselationArguments) api.geometry(name, (Tesselatable) new Gumbo()); else api.geometry(name, (PrimitiveList) new Gumbo()); } else if (type.equals("julia")) { UI.printInfo(Module.API, "Reading julia fractal: %s ... ", name); if (p.peekNextToken("q")) { api.parameter("cw", p.getNextFloat()); api.parameter("cx", p.getNextFloat()); api.parameter("cy", p.getNextFloat()); api.parameter("cz", p.getNextFloat()); } if (p.peekNextToken("iterations")) api.parameter("iterations", p.getNextInt()); if (p.peekNextToken("epsilon")) api.parameter("epsilon", p.getNextFloat()); api.geometry(name, new JuliaFractal()); } else if (type.equals("particles") || type.equals("dlasurface")) { if (type.equals("dlasurface")) UI.printWarning(Module.API, "Deprecated object type: \"dlasurface\" - please use \"particles\" instead"); float[] data; if (p.peekNextToken("filename")) { String filename = api.resolveIncludeFilename(p.getNextToken()); boolean littleEndian = false; if (p.peekNextToken("little_endian")) littleEndian = true; UI.printInfo(Module.USER, "Loading particle file: %s", filename); File file = new File(filename); FileInputStream stream = new FileInputStream(filename); MappedByteBuffer map = stream.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length()); if (littleEndian) map.order(ByteOrder.LITTLE_ENDIAN); FloatBuffer buffer = map.asFloatBuffer(); data = new float[buffer.capacity()]; for (int i = 0; i < data.length; i++) data[i] = buffer.get(i); stream.close(); <MASK>api.parameter("particles", "point", "vertex", data);</MASK> } else { p.checkNextToken("points"); int n = p.getNextInt(); data = parseFloatArray(n * 3); // read 3n points } if (p.peekNextToken("num")) api.parameter("num", p.getNextInt()); else api.parameter("num", data.length / 3); p.checkNextToken("radius"); api.parameter("radius", p.getNextFloat()); api.geometry(name, new ParticleSurface()); } else if (type.equals("file-mesh")) { UI.printInfo(Module.API, "Reading file mesh: %s ... ", name); p.checkNextToken("filename"); api.parameter("filename", p.getNextToken()); if (p.peekNextToken("smooth_normals")) api.parameter("smooth_normals", p.getNextBoolean()); api.geometry(name, new FileMesh()); } else if (type.equals("bezier-mesh")) { UI.printInfo(Module.API, "Reading bezier mesh: %s ... ", name); p.checkNextToken("n"); int nu, nv; api.parameter("nu", nu = p.getNextInt()); api.parameter("nv", nv = p.getNextInt()); if (p.peekNextToken("wrap")) { api.parameter("uwrap", p.getNextBoolean()); api.parameter("vwrap", p.getNextBoolean()); } p.checkNextToken("points"); float[] points = new float[3 * nu * nv]; for (int i = 0; i < points.length; i++) points[i] = p.getNextFloat(); api.parameter("points", "point", "vertex", points); if (p.peekNextToken("subdivs")) api.parameter("subdivs", p.getNextInt()); if (p.peekNextToken("smooth")) api.parameter("smooth", p.getNextBoolean()); api.geometry(name, (Tesselatable) new BezierMesh()); } else { UI.printWarning(Module.API, "Unrecognized object type: %s", p.getNextToken()); noInstance = true; } if (!noInstance) { // create instance api.parameter("shaders", shaders); if (modifiers != null) api.parameter("modifiers", modifiers); if (transform != null) api.parameter("transform", transform); api.instance(name + ".instance", name); } p.checkNextToken("}"); }"
Inversion-Mutation
megadiff
"public Boolean invoke(File ws, VirtualChannel channel) throws IOException { for (ModuleLocation l : locations) { String moduleName = l.getLocalDir(); File module = new File(ws,moduleName).getCanonicalFile(); // canonicalize to remove ".." and ".". See #474 if(!module.exists()) { listener.getLogger().println("Checking out a fresh workspace because "+module+" doesn't exist"); return false; } try { SVNInfo svnkitInfo = parseSvnInfo(module, authProvider); SvnInfo svnInfo = new SvnInfo(svnkitInfo); String url = l.getURL(); if(!svnInfo.url.equals(url)) { listener.getLogger().println("Checking out a fresh workspace because the workspace is not "+url); return false; } } catch (SVNException e) { if (e.getErrorMessage().getErrorCode()==SVNErrorCode.WC_NOT_DIRECTORY) { listener.getLogger().println("Checking out a fresh workspace because there's no workspace at "+module); } else { listener.getLogger().println("Checking out a fresh workspace because Hudson failed to detect the current workspace "+module); e.printStackTrace(listener.error(e.getMessage())); } return false; } } return true; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "invoke"
"public Boolean invoke(File ws, VirtualChannel channel) throws IOException { for (ModuleLocation l : locations) { String moduleName = l.getLocalDir(); File module = new File(ws,moduleName).getCanonicalFile(); // canonicalize to remove ".." and ".". See #474 if(!module.exists()) { listener.getLogger().println("Checking out a fresh workspace because "+module+" doesn't exist"); <MASK>return false;</MASK> } try { SVNInfo svnkitInfo = parseSvnInfo(module, authProvider); SvnInfo svnInfo = new SvnInfo(svnkitInfo); String url = l.getURL(); if(!svnInfo.url.equals(url)) { listener.getLogger().println("Checking out a fresh workspace because the workspace is not "+url); <MASK>return false;</MASK> } } catch (SVNException e) { if (e.getErrorMessage().getErrorCode()==SVNErrorCode.WC_NOT_DIRECTORY) { listener.getLogger().println("Checking out a fresh workspace because there's no workspace at "+module); } else { listener.getLogger().println("Checking out a fresh workspace because Hudson failed to detect the current workspace "+module); e.printStackTrace(listener.error(e.getMessage())); <MASK>return false;</MASK> } } } return true; }"
Inversion-Mutation
megadiff
"private void delayedCleanupAfterDisconnect() { if (VDBG) log("delayedCleanupAfterDisconnect()... Phone state = " + mCM.getState()); // Clean up any connections in the DISCONNECTED state. // // [Background: Even after a connection gets disconnected, its // Connection object still stays around, in the special // DISCONNECTED state. This is necessary because we we need the // caller-id information from that Connection to properly draw the // "Call ended" state of the CallCard. // But at this point we truly don't need that connection any // more, so tell the Phone that it's now OK to to clean up any // connections still in that state.] mCM.clearDisconnected(); // There are two cases where we should *not* exit the InCallScreen: // (1) Phone is still in use // or // (2) There's an active progress indication (i.e. the "Retrying..." // progress dialog) that we need to continue to display. boolean stayHere = phoneIsInUse() || mApp.inCallUiState.isProgressIndicationActive(); if (stayHere) { if (DBG) log("- delayedCleanupAfterDisconnect: staying on the InCallScreen..."); } else { // Phone is idle! We should exit the in-call UI now. if (DBG) log("- delayedCleanupAfterDisconnect: phone is idle..."); // And (finally!) exit from the in-call screen // (but not if we're already in the process of pausing...) if (mIsForegroundActivity) { if (DBG) log("- delayedCleanupAfterDisconnect: finishing InCallScreen..."); // In some cases we finish the call by taking the user to the // Call Log. Otherwise, we simply call endInCallScreenSession, // which will take us back to wherever we came from. // // UI note: In eclair and earlier, we went to the Call Log // after outgoing calls initiated on the device, but never for // incoming calls. Now we do it for incoming calls too, as // long as the call was answered by the user. (We always go // back where you came from after a rejected or missed incoming // call.) // // And in any case, *never* go to the call log if we're in // emergency mode (i.e. if the screen is locked and a lock // pattern or PIN/password is set), or if we somehow got here // on a non-voice-capable device. if (VDBG) log("- Post-call behavior:"); if (VDBG) log(" - mLastDisconnectCause = " + mLastDisconnectCause); if (VDBG) log(" - isPhoneStateRestricted() = " + isPhoneStateRestricted()); // DisconnectCause values in the most common scenarios: // - INCOMING_MISSED: incoming ringing call times out, or the // other end hangs up while still ringing // - INCOMING_REJECTED: user rejects the call while ringing // - LOCAL: user hung up while a call was active (after // answering an incoming call, or after making an // outgoing call) // - NORMAL: the other end hung up (after answering an incoming // call, or after making an outgoing call) if ((mLastDisconnectCause != Connection.DisconnectCause.INCOMING_MISSED) && (mLastDisconnectCause != Connection.DisconnectCause.INCOMING_REJECTED) && !isPhoneStateRestricted() && PhoneGlobals.sVoiceCapable) { final Intent intent = mApp.createPhoneEndIntentUsingCallOrigin(); ActivityOptions opts = ActivityOptions.makeCustomAnimation(this, R.anim.activity_close_enter, R.anim.activity_close_exit); if (VDBG) { log("- Show Call Log (or Dialtacts) after disconnect. Current intent: " + intent); } try { startActivity(intent, opts.toBundle()); } catch (ActivityNotFoundException e) { // Don't crash if there's somehow no "Call log" at // all on this device. // (This should never happen, though, since we already // checked PhoneApp.sVoiceCapable above, and any // voice-capable device surely *should* have a call // log activity....) Log.w(LOG_TAG, "delayedCleanupAfterDisconnect: " + "transition to call log failed; intent = " + intent); // ...so just return back where we came from.... } // Even if we did go to the call log, note that we still // call endInCallScreenSession (below) to make sure we don't // stay in the activity history. } } endInCallScreenSession(); // Reset the call origin when the session ends and this in-call UI is being finished. mApp.setLatestActiveCallOrigin(null); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "delayedCleanupAfterDisconnect"
"private void delayedCleanupAfterDisconnect() { if (VDBG) log("delayedCleanupAfterDisconnect()... Phone state = " + mCM.getState()); // Clean up any connections in the DISCONNECTED state. // // [Background: Even after a connection gets disconnected, its // Connection object still stays around, in the special // DISCONNECTED state. This is necessary because we we need the // caller-id information from that Connection to properly draw the // "Call ended" state of the CallCard. // But at this point we truly don't need that connection any // more, so tell the Phone that it's now OK to to clean up any // connections still in that state.] mCM.clearDisconnected(); // There are two cases where we should *not* exit the InCallScreen: // (1) Phone is still in use // or // (2) There's an active progress indication (i.e. the "Retrying..." // progress dialog) that we need to continue to display. boolean stayHere = phoneIsInUse() || mApp.inCallUiState.isProgressIndicationActive(); if (stayHere) { if (DBG) log("- delayedCleanupAfterDisconnect: staying on the InCallScreen..."); } else { // Phone is idle! We should exit the in-call UI now. if (DBG) log("- delayedCleanupAfterDisconnect: phone is idle..."); // And (finally!) exit from the in-call screen // (but not if we're already in the process of pausing...) if (mIsForegroundActivity) { if (DBG) log("- delayedCleanupAfterDisconnect: finishing InCallScreen..."); // In some cases we finish the call by taking the user to the // Call Log. Otherwise, we simply call endInCallScreenSession, // which will take us back to wherever we came from. // // UI note: In eclair and earlier, we went to the Call Log // after outgoing calls initiated on the device, but never for // incoming calls. Now we do it for incoming calls too, as // long as the call was answered by the user. (We always go // back where you came from after a rejected or missed incoming // call.) // // And in any case, *never* go to the call log if we're in // emergency mode (i.e. if the screen is locked and a lock // pattern or PIN/password is set), or if we somehow got here // on a non-voice-capable device. if (VDBG) log("- Post-call behavior:"); if (VDBG) log(" - mLastDisconnectCause = " + mLastDisconnectCause); if (VDBG) log(" - isPhoneStateRestricted() = " + isPhoneStateRestricted()); // DisconnectCause values in the most common scenarios: // - INCOMING_MISSED: incoming ringing call times out, or the // other end hangs up while still ringing // - INCOMING_REJECTED: user rejects the call while ringing // - LOCAL: user hung up while a call was active (after // answering an incoming call, or after making an // outgoing call) // - NORMAL: the other end hung up (after answering an incoming // call, or after making an outgoing call) if ((mLastDisconnectCause != Connection.DisconnectCause.INCOMING_MISSED) && (mLastDisconnectCause != Connection.DisconnectCause.INCOMING_REJECTED) && !isPhoneStateRestricted() && PhoneGlobals.sVoiceCapable) { final Intent intent = mApp.createPhoneEndIntentUsingCallOrigin(); ActivityOptions opts = ActivityOptions.makeCustomAnimation(this, R.anim.activity_close_enter, R.anim.activity_close_exit); if (VDBG) { log("- Show Call Log (or Dialtacts) after disconnect. Current intent: " + intent); } try { startActivity(intent, opts.toBundle()); } catch (ActivityNotFoundException e) { // Don't crash if there's somehow no "Call log" at // all on this device. // (This should never happen, though, since we already // checked PhoneApp.sVoiceCapable above, and any // voice-capable device surely *should* have a call // log activity....) Log.w(LOG_TAG, "delayedCleanupAfterDisconnect: " + "transition to call log failed; intent = " + intent); // ...so just return back where we came from.... } // Even if we did go to the call log, note that we still // call endInCallScreenSession (below) to make sure we don't // stay in the activity history. } <MASK>endInCallScreenSession();</MASK> } // Reset the call origin when the session ends and this in-call UI is being finished. mApp.setLatestActiveCallOrigin(null); } }"
Inversion-Mutation
megadiff
"public void promptNew() { promptSave("Would you like to save before starting a new file?"); file = null; saved = true; inputArea.setText(""); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "promptNew"
"public void promptNew() { promptSave("Would you like to save before starting a new file?"); <MASK>inputArea.setText("");</MASK> file = null; saved = true; }"
Inversion-Mutation
megadiff
"public static ProjectData getGlobalProjectData() { if (globalProjectData != null) return globalProjectData; globalProjectData = new ProjectData(); initialize(); return globalProjectData; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getGlobalProjectData"
"public static ProjectData getGlobalProjectData() { if (globalProjectData != null) return globalProjectData; <MASK>initialize();</MASK> globalProjectData = new ProjectData(); return globalProjectData; }"
Inversion-Mutation
megadiff
"private void setLayer(int layerNum, int layerType) { layerUsed = true; layerIsPin = false; Integer layerInt = new Integer(layerNum + (layerType<<16)); Layer layer = (Layer)layerNames.get(layerInt); if (layer == null) { if (IOTool.isGDSInIgnoresUnknownLayers()) { System.out.println("GDS layer " + layerNum + ", type " + layerType + " unknown, ignoring it"); } else { System.out.println("GDS layer " + layerNum + ", type " + layerType + " unknown, using Generic:DRC"); } layerNames.put(layerInt, Generic.tech.drc_lay); layerUsed = false; layerNodeProto = null; } else { layerNodeProto = layer.getNonPseudoLayer().getPureLayerNode(); if (layer == Generic.tech.drc_lay && IOTool.isGDSInIgnoresUnknownLayers()) layerUsed = false; pinNodeProto = Generic.tech.universalPinNode; if (pinLayers.contains(layerInt)) { layerIsPin = true; for (Iterator it = layer.getTechnology().getArcs(); it.hasNext(); ) { ArcProto arc = (ArcProto)it.next(); PortProto pp = layerNodeProto.getPort(0); if (pp != null && pp.connectsTo(arc)) { pinNodeProto = arc.findOverridablePinProto(); break; } } } if (layerNodeProto == null) { System.out.println("Error: no pure layer node for layer "+layer.getName()); layerNames.put(layerInt, Generic.tech.drc_lay); layerUsed = false; } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setLayer"
"private void setLayer(int layerNum, int layerType) { layerUsed = true; layerIsPin = false; Integer layerInt = new Integer(layerNum + (layerType<<16)); Layer layer = (Layer)layerNames.get(layerInt); if (layer == null) { if (IOTool.isGDSInIgnoresUnknownLayers()) { System.out.println("GDS layer " + layerNum + ", type " + layerType + " unknown, ignoring it"); } else { System.out.println("GDS layer " + layerNum + ", type " + layerType + " unknown, using Generic:DRC"); } layerNames.put(layerInt, Generic.tech.drc_lay); layerUsed = false; layerNodeProto = null; } else { if (layer == Generic.tech.drc_lay && IOTool.isGDSInIgnoresUnknownLayers()) layerUsed = false; pinNodeProto = Generic.tech.universalPinNode; if (pinLayers.contains(layerInt)) { layerIsPin = true; for (Iterator it = layer.getTechnology().getArcs(); it.hasNext(); ) { ArcProto arc = (ArcProto)it.next(); PortProto pp = layerNodeProto.getPort(0); if (pp != null && pp.connectsTo(arc)) { pinNodeProto = arc.findOverridablePinProto(); break; } } } <MASK>layerNodeProto = layer.getNonPseudoLayer().getPureLayerNode();</MASK> if (layerNodeProto == null) { System.out.println("Error: no pure layer node for layer "+layer.getName()); layerNames.put(layerInt, Generic.tech.drc_lay); layerUsed = false; } } }"
Inversion-Mutation
megadiff
"public static Node findOrCreateOSSNode(OssType ossType,String ossName,GraphDatabaseService neo) { Node oss; Transaction tx = neo.beginTx(); try { oss = NeoUtils.findRootNodeByName(ossName, neo); if (oss == null) { oss = neo.createNode(); oss.setProperty(INeoConstants.PROPERTY_TYPE_NAME, NodeTypes.OSS.getId()); oss.setProperty(INeoConstants.PROPERTY_NAME_NAME, ossName); ossType.setOssType(oss, neo); String aweProjectName = LoaderUtils.getAweProjectName(); NeoCorePlugin.getDefault().getProjectService().addDataNodeToProject(aweProjectName, oss); //TODO remove this relation! neo.getReferenceNode().createRelationshipTo(oss, GeoNeoRelationshipTypes.CHILD); } assert NodeTypes.OSS.checkNode(oss); tx.success(); } finally { tx.finish(); } return oss; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "findOrCreateOSSNode"
"public static Node findOrCreateOSSNode(OssType ossType,String ossName,GraphDatabaseService neo) { Node oss; Transaction tx = neo.beginTx(); try { oss = NeoUtils.findRootNodeByName(ossName, neo); if (oss == null) { oss = neo.createNode(); oss.setProperty(INeoConstants.PROPERTY_TYPE_NAME, NodeTypes.OSS.getId()); oss.setProperty(INeoConstants.PROPERTY_NAME_NAME, ossName); ossType.setOssType(oss, neo); <MASK>//TODO remove this relation!</MASK> String aweProjectName = LoaderUtils.getAweProjectName(); NeoCorePlugin.getDefault().getProjectService().addDataNodeToProject(aweProjectName, oss); neo.getReferenceNode().createRelationshipTo(oss, GeoNeoRelationshipTypes.CHILD); } assert NodeTypes.OSS.checkNode(oss); tx.success(); } finally { tx.finish(); } return oss; }"
Inversion-Mutation
megadiff
"@TestTargetNew( level = TestLevel.COMPLETE, method = "setDither", args = {boolean.class} ) public void testSetDither() { assertConstantStateNotSet(); assertNull(mDrawableContainer.getCurrent()); mDrawableContainer.setConstantState(mDrawableContainerState); mDrawableContainer.setDither(false); mDrawableContainer.setDither(true); MockDrawable dr = new MockDrawable(); addAndSelectDrawable(dr); // call current drawable's setDither if dither is changed. dr.reset(); mDrawableContainer.setDither(false); assertTrue(dr.hasSetDitherCalled()); // does not call it if dither is not changed. dr.reset(); mDrawableContainer.setDither(true); assertTrue(dr.hasSetDitherCalled()); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "testSetDither"
"@TestTargetNew( level = TestLevel.COMPLETE, method = "setDither", args = {boolean.class} ) public void testSetDither() { assertConstantStateNotSet(); assertNull(mDrawableContainer.getCurrent()); mDrawableContainer.setDither(false); mDrawableContainer.setDither(true); <MASK>mDrawableContainer.setConstantState(mDrawableContainerState);</MASK> MockDrawable dr = new MockDrawable(); addAndSelectDrawable(dr); // call current drawable's setDither if dither is changed. dr.reset(); mDrawableContainer.setDither(false); assertTrue(dr.hasSetDitherCalled()); // does not call it if dither is not changed. dr.reset(); mDrawableContainer.setDither(true); assertTrue(dr.hasSetDitherCalled()); }"
Inversion-Mutation
megadiff
"public void run() { if ( lifecycle != null ) { throw new IllegalStateException( "Can't start new database: the old one isn't shutdown properly." ); } logInfo( "trying to start/connect ..." ); String dbLocation; GraphDatabaseService graphDb = null; switch ( serviceMode ) { case READ_WRITE_EMBEDDED: dbLocation = getDbLocation(); graphDb = new EmbeddedGraphDatabase( dbLocation ); logInfo( "connected to embedded neo4j" ); break; case READ_ONLY_EMBEDDED: dbLocation = getDbLocation(); graphDb = new EmbeddedReadOnlyGraphDatabase( dbLocation ); logInfo( "connected to embedded read-only neo4j" ); break; case REMOTE: try { graphDb = new RemoteGraphDatabase( getResourceUri() ); logInfo( "connected to remote neo4j" ); } catch ( URISyntaxException e ) { ErrorMessage.showDialog( "URI syntax error", e ); } break; } lifecycle = new GraphDatabaseLifecycle( graphDb ); logFine( "starting tx" ); tx = graphDb.beginTx(); fireServiceChangedEvent( GraphDbServiceStatus.STARTED ); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"public void run() { if ( lifecycle != null ) { throw new IllegalStateException( "Can't start new database: the old one isn't shutdown properly." ); } logInfo( "trying to start/connect ..." ); String dbLocation; GraphDatabaseService graphDb = null; switch ( serviceMode ) { case READ_WRITE_EMBEDDED: dbLocation = getDbLocation(); graphDb = new EmbeddedGraphDatabase( dbLocation ); logInfo( "connected to embedded neo4j" ); break; case READ_ONLY_EMBEDDED: dbLocation = getDbLocation(); graphDb = new EmbeddedReadOnlyGraphDatabase( dbLocation ); logInfo( "connected to embedded read-only neo4j" ); break; case REMOTE: try { graphDb = new RemoteGraphDatabase( getResourceUri() ); } catch ( URISyntaxException e ) { ErrorMessage.showDialog( "URI syntax error", e ); } <MASK>logInfo( "connected to remote neo4j" );</MASK> break; } lifecycle = new GraphDatabaseLifecycle( graphDb ); logFine( "starting tx" ); tx = graphDb.beginTx(); fireServiceChangedEvent( GraphDbServiceStatus.STARTED ); }"
Inversion-Mutation
megadiff
"protected void acquirePoint(boolean start, boolean collectDetectors) throws Exception { TreeMap<Integer, Scannable[]> devicesToMoveByLevel; if(collectDetectors) { devicesToMoveByLevel = generateDevicesToMoveByLevel(scannableLevels, allDetectors); } else { devicesToMoveByLevel = scannableLevels; } for (Integer thisLevel : devicesToMoveByLevel.keySet()) { Scannable[] scannablesAtThisLevel = devicesToMoveByLevel.get(thisLevel); // If there is a detector at this level then wait for detector readout thread to complete for (Scannable scannable : scannablesAtThisLevel) { if (scannable instanceof Detector) { waitForDetectorReadoutAndPublishCompletion(); break; } } // trigger at level move start on all Scannables for (Scannable scannable : scannablesAtThisLevel) { if (isScannableToBeMoved(scannable) != null) { if (isScannableToBeMoved(scannable).hasStart()) { scannable.atLevelMoveStart(); } } } // on detectors (technically scannables) that implement DetectorWithReadout call waitForReadoutComplete for (Scannable scannable : scannablesAtThisLevel) { if (scannable instanceof DetectorWithReadout) { if (!detectorWithReadoutDeprecationWarningGiven ) { logger.warn("The DetectorWithReadout interface is deprecated. Set gda.scan.concurrentScan.readoutConcurrently to true instead (after reading the 8.24 release note"); detectorWithReadoutDeprecationWarningGiven = true; } ((DetectorWithReadout) scannable).waitForReadoutCompletion(); } } for (Scannable device : scannablesAtThisLevel) { if (!(device instanceof Detector)) { // does this scan (is a hierarchy of nested scans) operate this scannable? ScanObject scanObject = isScannableToBeMoved(device); if (scanObject != null) { if (start) { scanObject.moveToStart(); } else { scanObject.moveStep(); } } } else { ((Detector) device).collectData(); } } // pause here until all the scannables at this level have finished moving for (Entry<Integer, Scannable[]> entriesByLevel : devicesToMoveByLevel.entrySet()) { Scannable[] scannablesAtLevel = entriesByLevel.getValue(); for (int i = 0; i < scannablesAtLevel.length; i++) { Scannable scn = scannablesAtLevel[i]; scn.waitWhileBusy(); } } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "acquirePoint"
"protected void acquirePoint(boolean start, boolean collectDetectors) throws Exception { TreeMap<Integer, Scannable[]> devicesToMoveByLevel; if(collectDetectors) { devicesToMoveByLevel = generateDevicesToMoveByLevel(scannableLevels, allDetectors); } else { devicesToMoveByLevel = scannableLevels; } for (Integer thisLevel : devicesToMoveByLevel.keySet()) { Scannable[] scannablesAtThisLevel = devicesToMoveByLevel.get(thisLevel); // If there is a detector at this level then wait for detector readout thread to complete for (Scannable scannable : scannablesAtThisLevel) { if (scannable instanceof Detector) { waitForDetectorReadoutAndPublishCompletion(); break; } } // trigger at level move start on all Scannables for (Scannable scannable : scannablesAtThisLevel) { if (isScannableToBeMoved(scannable) != null) { if (isScannableToBeMoved(scannable).hasStart()) { scannable.atLevelMoveStart(); } } } // on detectors (technically scannables) that implement DetectorWithReadout call waitForReadoutComplete for (Scannable scannable : scannablesAtThisLevel) { if (scannable instanceof DetectorWithReadout) { if (!detectorWithReadoutDeprecationWarningGiven ) { logger.warn("The DetectorWithReadout interface is deprecated. Set gda.scan.concurrentScan.readoutConcurrently to true instead (after reading the 8.24 release note"); <MASK>((DetectorWithReadout) scannable).waitForReadoutCompletion();</MASK> detectorWithReadoutDeprecationWarningGiven = true; } } } for (Scannable device : scannablesAtThisLevel) { if (!(device instanceof Detector)) { // does this scan (is a hierarchy of nested scans) operate this scannable? ScanObject scanObject = isScannableToBeMoved(device); if (scanObject != null) { if (start) { scanObject.moveToStart(); } else { scanObject.moveStep(); } } } else { ((Detector) device).collectData(); } } // pause here until all the scannables at this level have finished moving for (Entry<Integer, Scannable[]> entriesByLevel : devicesToMoveByLevel.entrySet()) { Scannable[] scannablesAtLevel = entriesByLevel.getValue(); for (int i = 0; i < scannablesAtLevel.length; i++) { Scannable scn = scannablesAtLevel[i]; scn.waitWhileBusy(); } } } }"
Inversion-Mutation
megadiff
"public void setupWebView() { mDestroyed = false; // create a webview mWebView = new WebView(getBaseActivity()); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.setBackgroundColor(0x00000000); mWebView.getSettings().setAllowFileAccess(true); mWebView.getSettings().setUseWideViewPort(true); mWebView.getSettings().setAppCacheEnabled(false); mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); mWebView.getSettings().setLoadWithOverviewMode(true); mJsInterface = new TopicJSInterface(mWebView, getBaseActivity(), this); mJsInterface.registerScroll(getArguments().getInt(ARG_POST_ID, 0)); mWebView.addJavascriptInterface(mJsInterface, "api"); mWebContainer.addView(mWebView); registerForContextMenu(mWebView); if (mTopic != null) { mWebView.loadDataWithBaseURL("file:///android_asset/", mTopic.getHtmlCache(), "text/html", Network.ENCODING_UTF8, null); } else { mWebView.loadData("", "text/html", Network.ENCODING_UTF8); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setupWebView"
"public void setupWebView() { mDestroyed = false; // create a webview mWebView = new WebView(getBaseActivity()); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setAllowFileAccess(true); mWebView.getSettings().setUseWideViewPort(true); mWebView.getSettings().setAppCacheEnabled(false); mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); mWebView.getSettings().setLoadWithOverviewMode(true); <MASK>mWebView.setBackgroundColor(0x00000000);</MASK> mJsInterface = new TopicJSInterface(mWebView, getBaseActivity(), this); mJsInterface.registerScroll(getArguments().getInt(ARG_POST_ID, 0)); mWebView.addJavascriptInterface(mJsInterface, "api"); mWebContainer.addView(mWebView); registerForContextMenu(mWebView); if (mTopic != null) { mWebView.loadDataWithBaseURL("file:///android_asset/", mTopic.getHtmlCache(), "text/html", Network.ENCODING_UTF8, null); } else { mWebView.loadData("", "text/html", Network.ENCODING_UTF8); } }"
Inversion-Mutation
megadiff
"public void due(final Scheduler scheduler, final long timestamp, final Object object) { final ServiceURL service = (ServiceURL) object; final RemoteServiceRegistration rs = (RemoteServiceRegistration) serviceRegistrations .get(service.toString()); try { System.out.println("RS: " + rs); System.out.println("REQUESTED " + service); System.out.println("REG: " + serviceRegistrations); System.out.println("PROPS: " + rs.getProperties()); advertiser.register(service, rs.getProperties()); final long next = System.currentTimeMillis() + ((service.getLifetime() - 1) * 1000); scheduler.reschedule(service, next); } catch (ServiceLocationException sle) { sle.printStackTrace(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "due"
"public void due(final Scheduler scheduler, final long timestamp, final Object object) { final ServiceURL service = (ServiceURL) object; final RemoteServiceRegistration rs = (RemoteServiceRegistration) serviceRegistrations .get(service.toString()); try { System.out.println("RS: " + rs); <MASK>System.out.println("PROPS: " + rs.getProperties());</MASK> System.out.println("REQUESTED " + service); System.out.println("REG: " + serviceRegistrations); advertiser.register(service, rs.getProperties()); final long next = System.currentTimeMillis() + ((service.getLifetime() - 1) * 1000); scheduler.reschedule(service, next); } catch (ServiceLocationException sle) { sle.printStackTrace(); } }"
Inversion-Mutation
megadiff
"public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (sender instanceof Player) { Player petOwner = (Player) sender; if (MyPetList.hasMyPet(petOwner)) { MyPet myPet = MyPetList.getMyPet(petOwner); myPet.removePet(); myPet.setLocation(petOwner.getLocation()); switch (myPet.createPet()) { case Success: sender.sendMessage(MyPetBukkitUtil.setColors(MyPetLanguage.getString("Msg_Call")).replace("%petname%", myPet.petName)); if (MyPetConfiguration.ENABLE_EVENTS) { getPluginManager().callEvent(new MyPetSpoutEvent(myPet, MyPetSpoutEventReason.Call)); } break; case Canceled: sender.sendMessage(MyPetBukkitUtil.setColors(MyPetLanguage.getString("Msg_SpawnPrevent")).replace("%petname%", myPet.petName)); break; case NoSpace: sender.sendMessage(MyPetBukkitUtil.setColors(MyPetLanguage.getString("Msg_SpawnNoSpace")).replace("%petname%", myPet.petName)); break; case Dead: sender.sendMessage(MyPetBukkitUtil.setColors(MyPetLanguage.getString("Msg_CallDead")).replace("%petname%", myPet.petName).replace("%time%", "" + myPet.respawnTime)); break; } return true; } else { sender.sendMessage(MyPetBukkitUtil.setColors(MyPetLanguage.getString("Msg_DontHavePet"))); } return true; } sender.sendMessage("You can't use this command from server console!"); return true; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCommand"
"public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (sender instanceof Player) { Player petOwner = (Player) sender; if (MyPetList.hasMyPet(petOwner)) { MyPet myPet = MyPetList.getMyPet(petOwner); myPet.removePet(); myPet.setLocation(petOwner.getLocation()); switch (myPet.createPet()) { case Success: if (MyPetConfiguration.ENABLE_EVENTS) { <MASK>sender.sendMessage(MyPetBukkitUtil.setColors(MyPetLanguage.getString("Msg_Call")).replace("%petname%", myPet.petName));</MASK> getPluginManager().callEvent(new MyPetSpoutEvent(myPet, MyPetSpoutEventReason.Call)); } break; case Canceled: sender.sendMessage(MyPetBukkitUtil.setColors(MyPetLanguage.getString("Msg_SpawnPrevent")).replace("%petname%", myPet.petName)); break; case NoSpace: sender.sendMessage(MyPetBukkitUtil.setColors(MyPetLanguage.getString("Msg_SpawnNoSpace")).replace("%petname%", myPet.petName)); break; case Dead: sender.sendMessage(MyPetBukkitUtil.setColors(MyPetLanguage.getString("Msg_CallDead")).replace("%petname%", myPet.petName).replace("%time%", "" + myPet.respawnTime)); break; } return true; } else { sender.sendMessage(MyPetBukkitUtil.setColors(MyPetLanguage.getString("Msg_DontHavePet"))); } return true; } sender.sendMessage("You can't use this command from server console!"); return true; }"
Inversion-Mutation
megadiff
"public static void main(String[] args) { long sTime = System.currentTimeMillis(); System.out.println("OntoStarUrlFetcher started"); File stopFile = new File(Configuration.stopFile); File stoppedFile = new File(Configuration.stoppedFile); File runFile = new File(Configuration.runFile); UrlMySQLInterface db = UrlMySQLInterface.getinstance(); SolrQueryMaker solr = SolrQueryMaker.getInstance(); System.out.println("Fetching URLs starting from " + solr.getSolrStringDate(solr.getDateInMillis()) + "."); boolean upToDate = false; long lastDate = solr.getDateInMillis(); if (lastDate >= System.currentTimeMillis()) { upToDate = true; } while (!stopFile.exists() && !upToDate) { System.out.println("========================= Time: " + getTimestamp(lastDate)); try { db.insertUrls(solr.getNextUrls()); } catch (SolrServerException e) { e.printStackTrace(); } lastDate = solr.getDateInMillis(); if (lastDate >= System.currentTimeMillis()) { upToDate = true; } } try { if (upToDate) { System.out.println("Fetching done."); } else { System.out.println("Received stop command."); } db.closeConnection(); if (!runFile.exists()) { runFile.createNewFile(); } PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(runFile))); writer.println(SolrQueryMaker.getInstance().getDateInMillis()); writer.close(); stoppedFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); System.out.println("Something went wrong during the creation of command files."); } catch (SQLException e) { System.out.println("Cannot close connection."); e.printStackTrace(); } System.out.println("OntoStarUrlFetcher stopped."); long eTime = System.currentTimeMillis(); System.out.println("All done in " + (((double) eTime) - sTime) / 1000 + " seconds."); sTime = UrlMySQLInterface.sTime; eTime = UrlMySQLInterface.eTime; System.out.println("Time to insert URLs: " + (((double) eTime) - sTime) / 1000 + " seconds."); System.err.println("\n============================================\nEnd: " + getTimestamp() + "\n============================================\n"); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "main"
"public static void main(String[] args) { long sTime = System.currentTimeMillis(); System.out.println("OntoStarUrlFetcher started"); File stopFile = new File(Configuration.stopFile); File stoppedFile = new File(Configuration.stoppedFile); File runFile = new File(Configuration.runFile); UrlMySQLInterface db = UrlMySQLInterface.getinstance(); SolrQueryMaker solr = SolrQueryMaker.getInstance(); System.out.println("Fetching URLs starting from " + solr.getSolrStringDate(solr.getDateInMillis()) + "."); boolean upToDate = false; long lastDate = solr.getDateInMillis(); if (lastDate >= System.currentTimeMillis()) { upToDate = true; } while (!stopFile.exists() && !upToDate) { System.out.println("========================= Time: " + getTimestamp(lastDate)); try { db.insertUrls(solr.getNextUrls()); } catch (SolrServerException e) { e.printStackTrace(); } lastDate = solr.getDateInMillis(); if (lastDate >= System.currentTimeMillis()) { upToDate = true; } } try { if (upToDate) { System.out.println("Fetching done."); } else { System.out.println("Received stop command."); } if (!runFile.exists()) { runFile.createNewFile(); } PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(runFile))); writer.println(SolrQueryMaker.getInstance().getDateInMillis()); writer.close(); <MASK>db.closeConnection();</MASK> stoppedFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); System.out.println("Something went wrong during the creation of command files."); } catch (SQLException e) { System.out.println("Cannot close connection."); e.printStackTrace(); } System.out.println("OntoStarUrlFetcher stopped."); long eTime = System.currentTimeMillis(); System.out.println("All done in " + (((double) eTime) - sTime) / 1000 + " seconds."); sTime = UrlMySQLInterface.sTime; eTime = UrlMySQLInterface.eTime; System.out.println("Time to insert URLs: " + (((double) eTime) - sTime) / 1000 + " seconds."); System.err.println("\n============================================\nEnd: " + getTimestamp() + "\n============================================\n"); }"
Inversion-Mutation
megadiff
"public void capturePhoto(View v){ Log.e("Thisisit", "entered capturePhoto"); //if (currentTask == 1 || currentTask == 2) { Log.e("Thisisit", "hello"); String replacementImage = null; //if (currentTask == 1) { replacementImage = "/sdcard/Pictures/NickCage.png"; Log.e("Thisisit", replacementImage); //} //else if (currentTask == 2) { //replacementImage = "/sdcard/Pictures/PhotobombDefuser/TrollFace.png"; //Log.e("Thisisit", "NUMBA 2"); //} for(Rect face:mTracker.badFaces()) { Log.e("OMG IN THE LOOP", "OMGOMGOMG"); Mat selectedArea = mRgba.submat(face); Mat replaceImage = Highgui.imread(replacementImage); replaceImage.copyTo(selectedArea); } //} Bitmap bmp = Bitmap.createBitmap(mRgba.width(), mRgba.height(), Config.ARGB_8888); Utils.matToBitmap(mRgba, bmp); ImageView tv1 = new ImageView(this); tv1.setImageBitmap(bmp); setContentView(tv1); try { String fDate = new SimpleDateFormat("yyyymmddhhmmss").format(new java.util.Date()); File picDir = new File( Environment.getExternalStorageDirectory().toString()+File.separator + "BombDiffuser"); if (! picDir.exists()){ picDir.mkdirs(); if (! picDir.mkdirs()){ Log.d("SavePicture", "failed to create directory"); return; } } ByteArrayOutputStream bytes = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.PNG, 90, bytes); File file = new File(picDir.getPath().toString() + File.separator + "picture"+ fDate + ".png"); Log.i(TAG, picDir.getPath().toString() + File.separator + "picture"+ fDate + ".png"); file.createNewFile(); FileOutputStream out = new FileOutputStream(file); out.write(bytes.toByteArray()); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "capturePhoto"
"public void capturePhoto(View v){ Log.e("Thisisit", "entered capturePhoto"); //if (currentTask == 1 || currentTask == 2) { Log.e("Thisisit", "hello"); String replacementImage = null; //if (currentTask == 1) { replacementImage = "/sdcard/Pictures/NickCage.png"; Log.e("Thisisit", replacementImage); //} //else if (currentTask == 2) { //replacementImage = "/sdcard/Pictures/PhotobombDefuser/TrollFace.png"; //Log.e("Thisisit", "NUMBA 2"); //} for(Rect face:mTracker.badFaces()) { Log.e("OMG IN THE LOOP", "OMGOMGOMG"); Mat selectedArea = mRgba.submat(face); Mat replaceImage = Highgui.imread(replacementImage); replaceImage.copyTo(selectedArea); } //} Bitmap bmp = Bitmap.createBitmap(mRgba.width(), mRgba.height(), Config.ARGB_8888); Utils.matToBitmap(mRgba, bmp); ImageView tv1 = new ImageView(this); tv1.setImageBitmap(bmp); setContentView(tv1); <MASK>String fDate = new SimpleDateFormat("yyyymmddhhmmss").format(new java.util.Date());</MASK> try { File picDir = new File( Environment.getExternalStorageDirectory().toString()+File.separator + "BombDiffuser"); if (! picDir.exists()){ picDir.mkdirs(); if (! picDir.mkdirs()){ Log.d("SavePicture", "failed to create directory"); return; } } ByteArrayOutputStream bytes = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.PNG, 90, bytes); File file = new File(picDir.getPath().toString() + File.separator + "picture"+ fDate + ".png"); Log.i(TAG, picDir.getPath().toString() + File.separator + "picture"+ fDate + ".png"); file.createNewFile(); FileOutputStream out = new FileOutputStream(file); out.write(bytes.toByteArray()); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } }"
Inversion-Mutation
megadiff
"public void writeToStream(OutputStream os) throws IOException { setFullyQualifiedName( FullyQualifiedNameTriplet.TYPE_ATTRIBUTE_GID, FullyQualifiedNameTriplet.FORMAT_CHARSTR, name); setAttributeValue(value); setAttributeQualifier(tleID, 1); byte[] data = new byte[SF_HEADER.length]; copySF(data, Type.ATTRIBUTE, Category.PROCESS_ELEMENT); int tripletDataLength = getTripletDataLength(); byte[] l = BinaryUtils.convert(data.length + tripletDataLength - 1, 2); data[1] = l[0]; data[2] = l[1]; os.write(data); writeTriplets(os); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "writeToStream"
"public void writeToStream(OutputStream os) throws IOException { setFullyQualifiedName( FullyQualifiedNameTriplet.TYPE_ATTRIBUTE_GID, FullyQualifiedNameTriplet.FORMAT_CHARSTR, name); <MASK>setAttributeQualifier(tleID, 1);</MASK> setAttributeValue(value); byte[] data = new byte[SF_HEADER.length]; copySF(data, Type.ATTRIBUTE, Category.PROCESS_ELEMENT); int tripletDataLength = getTripletDataLength(); byte[] l = BinaryUtils.convert(data.length + tripletDataLength - 1, 2); data[1] = l[0]; data[2] = l[1]; os.write(data); writeTriplets(os); }"
Inversion-Mutation
megadiff
"public boolean updateSourceStatusStartup(int id, long queueSize, long doneQueueSize) { MongoDBCollection coll = new MongoDBCollection(db,"sources"); String query = String.format("{\"id\": %1$s}", id); BasicDBObject docsearch = MongoDBHelper.JSON2BasicDBObject(query); synchronized (sourcesCollMonitor) { DBCursor cur = coll.getColl().find(docsearch); if (cur.count()!=1) return false; BasicDBObject doc = (BasicDBObject) cur.next(); BasicDBObject doc2 = (BasicDBObject) doc.copy(); if (doneQueueSize>0 || queueSize>0) { doc2.put("running_crawl_item_processed", doneQueueSize); doc2.put("running_crawl_item_to_process", queueSize); } else { doc2.put("running_crawl_item_processed", 0); doc2.put("running_crawl_item_to_process", 0); } doc2.put("crawl_lasttime_start", new Date()); doc2.put("running_crawl_lastupdate", new Date()); doc2.put("crawl_process_status", ISource.CRAWL_PROCESS_STATUS_CRAWLING); doc2.put("crawl_mode", ISource.CRAWL_PROCESS_MODE_NONE); doc2.put("_poped", false); coll.update(doc, doc2); } return true; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "updateSourceStatusStartup"
"public boolean updateSourceStatusStartup(int id, long queueSize, long doneQueueSize) { MongoDBCollection coll = new MongoDBCollection(db,"sources"); String query = String.format("{\"id\": %1$s}", id); BasicDBObject docsearch = MongoDBHelper.JSON2BasicDBObject(query); synchronized (sourcesCollMonitor) { DBCursor cur = coll.getColl().find(docsearch); if (cur.count()!=1) return false; BasicDBObject doc = (BasicDBObject) cur.next(); BasicDBObject doc2 = (BasicDBObject) doc.copy(); if (doneQueueSize>0 || queueSize>0) { doc2.put("running_crawl_item_processed", doneQueueSize); doc2.put("running_crawl_item_to_process", queueSize); } else { doc2.put("running_crawl_item_processed", 0); doc2.put("running_crawl_item_to_process", 0); <MASK>doc2.put("crawl_lasttime_start", new Date());</MASK> } doc2.put("running_crawl_lastupdate", new Date()); doc2.put("crawl_process_status", ISource.CRAWL_PROCESS_STATUS_CRAWLING); doc2.put("crawl_mode", ISource.CRAWL_PROCESS_MODE_NONE); doc2.put("_poped", false); coll.update(doc, doc2); } return true; }"
Inversion-Mutation
megadiff
"public void printReport() throws DocumentException { Hashtable<ExamPeriod,TreeSet<ExamSectionInfo>> period2courseSections = new Hashtable(); for (ExamAssignmentInfo exam : getExams()) { if (exam.getPeriod()==null) continue; TreeSet<ExamSectionInfo> sections = period2courseSections.get(exam.getPeriod()); if (sections==null) { sections = new TreeSet(); period2courseSections.put(exam.getPeriod(),sections); } sections.addAll(exam.getSections()); } Hashtable<Integer,String> times = new Hashtable(); Hashtable<Integer,String> fixedTimes = new Hashtable(); Hashtable<Integer,String> days = new Hashtable(); TreeSet weeks = new TreeSet(); for (Iterator i=ExamPeriod.findAll(getSession().getUniqueId(), getExamType()).iterator();i.hasNext();) { ExamPeriod period = (ExamPeriod)i.next(); times.put(period.getStartSlot(), period.getStartTimeLabel()); days.put(period.getDateOffset(), period.getStartDateLabel()); fixedTimes.put(period.getStartSlot(), lpad(period.getStartTimeLabel(),'0',6)+" - "+lpad(period.getEndTimeLabel(),'0',6)); } boolean headerPrinted = false; Hashtable totalADay = new Hashtable(); String timesThisPage = null; int nrCols = 0; if (!iTotals) { setHeader(new String[] { "Time Exam Enrl Exam Enrl Exam Enrl Exam Enrl Exam Enrl", "--------------- --------------- ---- --------------- ---- --------------- ---- --------------- ---- --------------- ----" }); printHeader(); } for (int dIdx = 0; dIdx < days.size(); dIdx+=nrCols) { for (Enumeration e=ToolBox.sortEnumeration(times.keys());e.hasMoreElements();) { int time = ((Integer)e.nextElement()).intValue(); String timeStr = (String)times.get(new Integer(time)); String header1 = ""; String header2 = ""; String header3 = ""; Vector periods = new Vector(); int idx = 0; String firstDay = null; int firstDayOffset = 0; String lastDay = null; nrCols = 0; for (Enumeration f=ToolBox.sortEnumeration(days.keys());f.hasMoreElements();idx++) { int day = ((Integer)f.nextElement()).intValue(); String dayStr = days.get(day); if (idx<dIdx || (firstDay!=null && (dayStr.startsWith("Mon") || day>=firstDayOffset+7)) || nrCols==(iTotals?6:5)) continue; if (firstDay==null) {firstDay = dayStr; firstDayOffset = day; } lastDay = dayStr; header1 += mpad(dayStr,20)+" "; header2 += "Exam Enrl "; header3 += "=============== ==== "; ExamPeriod period = null; nrCols++; for (Iterator i=ExamPeriod.findAll(getSession().getUniqueId(), getExamType()).iterator();i.hasNext();) { ExamPeriod p = (ExamPeriod)i.next(); if (time!=p.getStartSlot() || day!=p.getDateOffset()) continue; period = p; break; } periods.add(period); } if (iTotals) setHeader(new String[] {timeStr,header1,header2,header3}); int nextLines = 0; for (Enumeration f=periods.elements();f.hasMoreElements();) { ExamPeriod period = (ExamPeriod)f.nextElement(); if (period==null) continue; TreeSet<ExamSectionInfo> sections = period2courseSections.get(period); if (sections==null) continue; int linesThisSections = 6; for (ExamSectionInfo section : sections) if (iLimit<0 || section.getNrStudents()>=iLimit) linesThisSections ++; nextLines = Math.max(nextLines,linesThisSections); } if (iTotals) { if (!headerPrinted) { printHeader(); setPageName(timeStr+(days.size()>nrCols?" ("+firstDay+" - "+lastDay+")":"")); setCont(timeStr+(days.size()>nrCols?" ("+firstDay+" - "+lastDay+")":"")); timesThisPage = timeStr; } else if (timesThisPage!=null && getLineNumber()+nextLines<=sNrLines) { println(""); println(timeStr); println(header1); println(header2); println(header3); timesThisPage += ", "+timeStr; setPageName(timesThisPage+(days.size()>nrCols?" ("+firstDay+" - "+lastDay+")":"")); setCont(timesThisPage+(days.size()>nrCols?" ("+firstDay+" - "+lastDay+")":"")); } else { newPage(); timesThisPage = timeStr; setPageName(timeStr+(days.size()>nrCols?" ("+firstDay+" - "+lastDay+")":"")); setCont(timeStr+(days.size()>nrCols?" ("+firstDay+" - "+lastDay+")":"")); } } else { if (nextLines==0) continue; setCont(firstDay+" - "+lastDay+" "+fixedTimes.get(time)); setPageName(firstDay+" - "+lastDay+" "+fixedTimes.get(time)); } headerPrinted = true; int max = 0; Vector lines = new Vector(); for (Enumeration f=periods.elements();f.hasMoreElements();) { ExamPeriod period = (ExamPeriod)f.nextElement(); if (period==null) { Vector linesThisPeriod = new Vector(); linesThisPeriod.add(lpad("0",20)); lines.add(linesThisPeriod); continue; } TreeSet<ExamSectionInfo> sections = period2courseSections.get(period); if (sections==null) sections = new TreeSet(); Vector linesThisPeriod = new Vector(); int total = 0; int totalListed = 0; for (ExamSectionInfo section : sections) { total += section.getNrStudents(); if (iLimit>=0 && section.getNrStudents()<iLimit) continue; totalListed += section.getNrStudents(); String code = null; if (iRoomCodes!=null && !iRoomCodes.isEmpty()) { for (ExamRoomInfo room : section.getExamAssignment().getRooms()) { String c = iRoomCodes.get(room.getName()); if (c!=null) code = c; break; } } if (iItype) linesThisPeriod.add( rpad(section.getName(),15)+(code==null||code.length()==0?' ':code.charAt(0))+ lpad(String.valueOf(section.getNrStudents()),4)); else linesThisPeriod.add( rpad(section.getSubject(),4)+" "+ rpad(section.getCourseNbr(),5)+" "+ rpad(section.getSection(),3)+" "+ (code==null||code.length()==0?' ':code.charAt(0))+ lpad(String.valueOf(section.getNrStudents()),4)); } if (iTotals) { if (totalListed!=total) linesThisPeriod.insertElementAt(mpad("("+totalListed+")",13)+" "+lpad(""+total,6), 0); else linesThisPeriod.insertElementAt(lpad(""+total,20), 0); } else { linesThisPeriod.insertElementAt(rpad(period.getStartDateLabel(),13)+" "+lpad(""+total,6), 0); } max = Math.max(max, linesThisPeriod.size()); Integer td = (Integer)totalADay.get(period.getDateOffset()); totalADay.put(period.getDateOffset(),new Integer(total+(td==null?0:td.intValue()))); lines.add(linesThisPeriod); } for (int i=0;i<max;i++) { String line = ""; if (!iTotals) { if (i==0 || iNewPage) line += fixedTimes.get(time) + " "; else line += rpad("",16); } for (Enumeration f=lines.elements();f.hasMoreElements();) { Vector linesThisPeriod = (Vector)f.nextElement(); if (i<linesThisPeriod.size()) line += (String)linesThisPeriod.elementAt(i); else line += rpad("",20); if (f.hasMoreElements()) line += " "; } println(line); } if (!iTotals && !iNewPage) { if (e.hasMoreElements()) println(" --------------- ---- --------------- ---- --------------- ---- --------------- ---- --------------- ----"); else println("--------------- --------------- ---- --------------- ---- --------------- ---- --------------- ---- --------------- ----"); } setCont(null); } if (iTotals) { if (getLineNumber()+5>sNrLines) { newPage(); setPageName("Totals"); } else println(""); println("Total Student Exams"); String line1 = "", line2 = "", line3 = ""; int idx = 0; for (Enumeration f=ToolBox.sortEnumeration(days.keys());f.hasMoreElements();idx++) { Integer day = (Integer)f.nextElement(); if (idx<dIdx || idx>=dIdx+nrCols) continue; line1 += mpad((String)days.get(day),20)+" "; line2 += "=============== ==== "; line3 += lpad(totalADay.get(day)==null?"":totalADay.get(day).toString(),20)+" "; } println(line1); println(line2); println(line3); timesThisPage = null; } } lastPage(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "printReport"
"public void printReport() throws DocumentException { Hashtable<ExamPeriod,TreeSet<ExamSectionInfo>> period2courseSections = new Hashtable(); for (ExamAssignmentInfo exam : getExams()) { if (exam.getPeriod()==null) continue; TreeSet<ExamSectionInfo> sections = period2courseSections.get(exam.getPeriod()); if (sections==null) { sections = new TreeSet(); period2courseSections.put(exam.getPeriod(),sections); } sections.addAll(exam.getSections()); } Hashtable<Integer,String> times = new Hashtable(); Hashtable<Integer,String> fixedTimes = new Hashtable(); Hashtable<Integer,String> days = new Hashtable(); TreeSet weeks = new TreeSet(); for (Iterator i=ExamPeriod.findAll(getSession().getUniqueId(), getExamType()).iterator();i.hasNext();) { ExamPeriod period = (ExamPeriod)i.next(); times.put(period.getStartSlot(), period.getStartTimeLabel()); days.put(period.getDateOffset(), period.getStartDateLabel()); fixedTimes.put(period.getStartSlot(), lpad(period.getStartTimeLabel(),'0',6)+" - "+lpad(period.getEndTimeLabel(),'0',6)); } boolean headerPrinted = false; Hashtable totalADay = new Hashtable(); String timesThisPage = null; int nrCols = 0; if (!iTotals) { setHeader(new String[] { "Time Exam Enrl Exam Enrl Exam Enrl Exam Enrl Exam Enrl", "--------------- --------------- ---- --------------- ---- --------------- ---- --------------- ---- --------------- ----" }); printHeader(); } for (int dIdx = 0; dIdx < days.size(); dIdx+=nrCols) { for (Enumeration e=ToolBox.sortEnumeration(times.keys());e.hasMoreElements();) { int time = ((Integer)e.nextElement()).intValue(); String timeStr = (String)times.get(new Integer(time)); String header1 = ""; String header2 = ""; String header3 = ""; Vector periods = new Vector(); int idx = 0; String firstDay = null; int firstDayOffset = 0; String lastDay = null; nrCols = 0; for (Enumeration f=ToolBox.sortEnumeration(days.keys());f.hasMoreElements();idx++) { int day = ((Integer)f.nextElement()).intValue(); String dayStr = days.get(day); if (idx<dIdx || (firstDay!=null && (dayStr.startsWith("Mon") || day>=firstDayOffset+7)) || nrCols==(iTotals?6:5)) continue; if (firstDay==null) {firstDay = dayStr; firstDayOffset = day; } lastDay = dayStr; header1 += mpad(dayStr,20)+" "; header2 += "Exam Enrl "; header3 += "=============== ==== "; ExamPeriod period = null; nrCols++; for (Iterator i=ExamPeriod.findAll(getSession().getUniqueId(), getExamType()).iterator();i.hasNext();) { ExamPeriod p = (ExamPeriod)i.next(); if (time!=p.getStartSlot() || day!=p.getDateOffset()) continue; period = p; break; } periods.add(period); } if (iTotals) setHeader(new String[] {timeStr,header1,header2,header3}); int nextLines = 0; for (Enumeration f=periods.elements();f.hasMoreElements();) { ExamPeriod period = (ExamPeriod)f.nextElement(); if (period==null) continue; TreeSet<ExamSectionInfo> sections = period2courseSections.get(period); if (sections==null) continue; int linesThisSections = 6; for (ExamSectionInfo section : sections) if (iLimit<0 || section.getNrStudents()>=iLimit) linesThisSections ++; nextLines = Math.max(nextLines,linesThisSections); } <MASK>if (nextLines==0) continue;</MASK> if (iTotals) { if (!headerPrinted) { printHeader(); setPageName(timeStr+(days.size()>nrCols?" ("+firstDay+" - "+lastDay+")":"")); setCont(timeStr+(days.size()>nrCols?" ("+firstDay+" - "+lastDay+")":"")); timesThisPage = timeStr; } else if (timesThisPage!=null && getLineNumber()+nextLines<=sNrLines) { println(""); println(timeStr); println(header1); println(header2); println(header3); timesThisPage += ", "+timeStr; setPageName(timesThisPage+(days.size()>nrCols?" ("+firstDay+" - "+lastDay+")":"")); setCont(timesThisPage+(days.size()>nrCols?" ("+firstDay+" - "+lastDay+")":"")); } else { newPage(); timesThisPage = timeStr; setPageName(timeStr+(days.size()>nrCols?" ("+firstDay+" - "+lastDay+")":"")); setCont(timeStr+(days.size()>nrCols?" ("+firstDay+" - "+lastDay+")":"")); } } else { setCont(firstDay+" - "+lastDay+" "+fixedTimes.get(time)); setPageName(firstDay+" - "+lastDay+" "+fixedTimes.get(time)); } headerPrinted = true; int max = 0; Vector lines = new Vector(); for (Enumeration f=periods.elements();f.hasMoreElements();) { ExamPeriod period = (ExamPeriod)f.nextElement(); if (period==null) { Vector linesThisPeriod = new Vector(); linesThisPeriod.add(lpad("0",20)); lines.add(linesThisPeriod); continue; } TreeSet<ExamSectionInfo> sections = period2courseSections.get(period); if (sections==null) sections = new TreeSet(); Vector linesThisPeriod = new Vector(); int total = 0; int totalListed = 0; for (ExamSectionInfo section : sections) { total += section.getNrStudents(); if (iLimit>=0 && section.getNrStudents()<iLimit) continue; totalListed += section.getNrStudents(); String code = null; if (iRoomCodes!=null && !iRoomCodes.isEmpty()) { for (ExamRoomInfo room : section.getExamAssignment().getRooms()) { String c = iRoomCodes.get(room.getName()); if (c!=null) code = c; break; } } if (iItype) linesThisPeriod.add( rpad(section.getName(),15)+(code==null||code.length()==0?' ':code.charAt(0))+ lpad(String.valueOf(section.getNrStudents()),4)); else linesThisPeriod.add( rpad(section.getSubject(),4)+" "+ rpad(section.getCourseNbr(),5)+" "+ rpad(section.getSection(),3)+" "+ (code==null||code.length()==0?' ':code.charAt(0))+ lpad(String.valueOf(section.getNrStudents()),4)); } if (iTotals) { if (totalListed!=total) linesThisPeriod.insertElementAt(mpad("("+totalListed+")",13)+" "+lpad(""+total,6), 0); else linesThisPeriod.insertElementAt(lpad(""+total,20), 0); } else { linesThisPeriod.insertElementAt(rpad(period.getStartDateLabel(),13)+" "+lpad(""+total,6), 0); } max = Math.max(max, linesThisPeriod.size()); Integer td = (Integer)totalADay.get(period.getDateOffset()); totalADay.put(period.getDateOffset(),new Integer(total+(td==null?0:td.intValue()))); lines.add(linesThisPeriod); } for (int i=0;i<max;i++) { String line = ""; if (!iTotals) { if (i==0 || iNewPage) line += fixedTimes.get(time) + " "; else line += rpad("",16); } for (Enumeration f=lines.elements();f.hasMoreElements();) { Vector linesThisPeriod = (Vector)f.nextElement(); if (i<linesThisPeriod.size()) line += (String)linesThisPeriod.elementAt(i); else line += rpad("",20); if (f.hasMoreElements()) line += " "; } println(line); } if (!iTotals && !iNewPage) { if (e.hasMoreElements()) println(" --------------- ---- --------------- ---- --------------- ---- --------------- ---- --------------- ----"); else println("--------------- --------------- ---- --------------- ---- --------------- ---- --------------- ---- --------------- ----"); } setCont(null); } if (iTotals) { if (getLineNumber()+5>sNrLines) { newPage(); setPageName("Totals"); } else println(""); println("Total Student Exams"); String line1 = "", line2 = "", line3 = ""; int idx = 0; for (Enumeration f=ToolBox.sortEnumeration(days.keys());f.hasMoreElements();idx++) { Integer day = (Integer)f.nextElement(); if (idx<dIdx || idx>=dIdx+nrCols) continue; line1 += mpad((String)days.get(day),20)+" "; line2 += "=============== ==== "; line3 += lpad(totalADay.get(day)==null?"":totalADay.get(day).toString(),20)+" "; } println(line1); println(line2); println(line3); timesThisPage = null; } } lastPage(); }"
Inversion-Mutation
megadiff
"public MyPetAIAggressiveTarget(EntityMyPet petEntity, float range) { this.petEntity = petEntity; this.myPet = petEntity.getMyPet(); this.petOwnerEntity = ((CraftPlayer) myPet.getOwner().getPlayer()).getHandle(); this.range = range; if (myPet.getSkills().hasSkill("Behavior")) { behaviorSkill = (Behavior) myPet.getSkills().getSkill("Behavior"); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "MyPetAIAggressiveTarget"
"public MyPetAIAggressiveTarget(EntityMyPet petEntity, float range) { this.petEntity = petEntity; <MASK>this.petOwnerEntity = ((CraftPlayer) myPet.getOwner().getPlayer()).getHandle();</MASK> this.myPet = petEntity.getMyPet(); this.range = range; if (myPet.getSkills().hasSkill("Behavior")) { behaviorSkill = (Behavior) myPet.getSkills().getSkill("Behavior"); } }"
Inversion-Mutation
megadiff
"private void writeResult(String sql, String s, SQLException e) throws Exception { assertKnownException(e); s = ("> " + s).trim(); String compare = readLine(); if (compare != null && compare.startsWith(">")) { if (!compare.equals(s)) { if (alwaysReconnect && sql.toUpperCase().startsWith("EXPLAIN")) { return; } errors.append("line: "); errors.append(line); errors.append("\n" + "exp: "); errors.append(compare); errors.append("\n" + "got: "); errors.append(s); errors.append("\n"); if (e != null) { TestBase.logError("script", e); } TestBase.logError(errors.toString(), null); if (failFast) { conn.close(); System.exit(1); } } } else { putBack = compare; } write(s); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "writeResult"
"private void writeResult(String sql, String s, SQLException e) throws Exception { assertKnownException(e); s = ("> " + s).trim(); String compare = readLine(); if (compare != null && compare.startsWith(">")) { if (!compare.equals(s)) { if (alwaysReconnect && sql.toUpperCase().startsWith("EXPLAIN")) { return; } errors.append("line: "); errors.append(line); errors.append("\n" + "exp: "); errors.append(compare); errors.append("\n" + "got: "); errors.append(s); errors.append("\n"); if (e != null) { TestBase.logError("script", e); } if (failFast) { <MASK>TestBase.logError(errors.toString(), null);</MASK> conn.close(); System.exit(1); } } } else { putBack = compare; } write(s); }"
Inversion-Mutation
megadiff
"protected final void scanElementDecl() throws IOException, XNIException { // spaces fReportEntity = false; if (!skipSeparator(true, !scanningInternalSubset())) { reportFatalError("MSG_SPACE_REQUIRED_BEFORE_ELEMENT_TYPE_IN_ELEMENTDECL", null); } // element name String name = fEntityScanner.scanName(); if (name == null) { reportFatalError("MSG_ELEMENT_TYPE_REQUIRED_IN_ELEMENTDECL", null); } // spaces if (!skipSeparator(true, !scanningInternalSubset())) { reportFatalError("MSG_SPACE_REQUIRED_BEFORE_CONTENTSPEC_IN_ELEMENTDECL", new Object[]{name}); } // content model if (fDTDContentModelHandler != null) { fDTDContentModelHandler.startContentModel(name); } String contentModel = null; fReportEntity = true; if (fEntityScanner.skipString("EMPTY")) { contentModel = "EMPTY"; // call handler if (fDTDContentModelHandler != null) { fDTDContentModelHandler.empty(); } } else if (fEntityScanner.skipString("ANY")) { contentModel = "ANY"; // call handler if (fDTDContentModelHandler != null) { fDTDContentModelHandler.any(); } } else { if (!fEntityScanner.skipChar('(')) { reportFatalError("MSG_OPEN_PAREN_OR_ELEMENT_TYPE_REQUIRED_IN_CHILDREN", new Object[]{name}); } if (fDTDContentModelHandler != null) { fDTDContentModelHandler.startGroup(); } fStringBuffer.clear(); fStringBuffer.append('('); fMarkUpDepth++; skipSeparator(false, !scanningInternalSubset()); // Mixed content model if (fEntityScanner.skipString("#PCDATA")) { scanMixed(name); } else { // children content scanChildren(name); } contentModel = fStringBuffer.toString(); } // call handler if (fDTDContentModelHandler != null) { fDTDContentModelHandler.endContentModel(); } fReportEntity = false; skipSeparator(false, !scanningInternalSubset()); fReportEntity = true; // end if (!fEntityScanner.skipChar('>')) { reportFatalError("ElementDeclUnterminated", new Object[]{name}); } fMarkUpDepth--; // call handler if (fDTDHandler != null) { fDTDHandler.elementDecl(name, contentModel); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "scanElementDecl"
"protected final void scanElementDecl() throws IOException, XNIException { // spaces fReportEntity = false; if (!skipSeparator(true, !scanningInternalSubset())) { reportFatalError("MSG_SPACE_REQUIRED_BEFORE_ELEMENT_TYPE_IN_ELEMENTDECL", null); } <MASK>fReportEntity = true;</MASK> // element name String name = fEntityScanner.scanName(); if (name == null) { reportFatalError("MSG_ELEMENT_TYPE_REQUIRED_IN_ELEMENTDECL", null); } // spaces if (!skipSeparator(true, !scanningInternalSubset())) { reportFatalError("MSG_SPACE_REQUIRED_BEFORE_CONTENTSPEC_IN_ELEMENTDECL", new Object[]{name}); } // content model if (fDTDContentModelHandler != null) { fDTDContentModelHandler.startContentModel(name); } String contentModel = null; if (fEntityScanner.skipString("EMPTY")) { contentModel = "EMPTY"; // call handler if (fDTDContentModelHandler != null) { fDTDContentModelHandler.empty(); } } else if (fEntityScanner.skipString("ANY")) { contentModel = "ANY"; // call handler if (fDTDContentModelHandler != null) { fDTDContentModelHandler.any(); } } else { if (!fEntityScanner.skipChar('(')) { reportFatalError("MSG_OPEN_PAREN_OR_ELEMENT_TYPE_REQUIRED_IN_CHILDREN", new Object[]{name}); } if (fDTDContentModelHandler != null) { fDTDContentModelHandler.startGroup(); } fStringBuffer.clear(); fStringBuffer.append('('); fMarkUpDepth++; skipSeparator(false, !scanningInternalSubset()); // Mixed content model if (fEntityScanner.skipString("#PCDATA")) { scanMixed(name); } else { // children content scanChildren(name); } contentModel = fStringBuffer.toString(); } // call handler if (fDTDContentModelHandler != null) { fDTDContentModelHandler.endContentModel(); } fReportEntity = false; skipSeparator(false, !scanningInternalSubset()); <MASK>fReportEntity = true;</MASK> // end if (!fEntityScanner.skipChar('>')) { reportFatalError("ElementDeclUnterminated", new Object[]{name}); } fMarkUpDepth--; // call handler if (fDTDHandler != null) { fDTDHandler.elementDecl(name, contentModel); } }"
Inversion-Mutation
megadiff
"public <T extends Holder> T setHolder(Class<?> specializationClass, Holder attribute, Serializable value, int metaLevel, int basePos, boolean existsException, Generic... targets) { // assert attribute.getMetaLevel() >= metaLevel; Generic meta = metaLevel == attribute.getMetaLevel() ? attribute.getMeta() : attribute; T holder = getSelectedHolder(attribute, value, metaLevel, basePos, targets); if (holder == null) return value == null ? null : this.<T> bind(((GenericImpl) meta).bindInstanceNode(value), specializationClass, attribute, basePos, existsException, targets); HomeTreeNode homeTreeNode = ((GenericImpl) meta).findInstanceNode(value); if (!equals(holder.getComponent(basePos))) { if (value == null) return cancel(holder, basePos, true); if (homeTreeNode != null && !(((GenericImpl) holder).equiv(homeTreeNode, new Primaries(homeTreeNode, attribute).toArray(), Statics.insertIntoArray(holder.getComponent(basePos), targets, basePos)))) cancel(holder, basePos, true); return this.<T> bind(((GenericImpl) meta).bindInstanceNode(value), specializationClass, attribute, basePos, existsException, targets); } if (homeTreeNode != null) { if (((GenericImpl) holder).equiv(homeTreeNode, new Primaries(homeTreeNode, attribute).toArray(), Statics.insertIntoArray(this, targets, basePos))) return holder; if (value != null && Arrays.equals(((GenericImpl) holder).components, Statics.insertIntoArray(this, targets, basePos))) { log.info("999999999999999" + holder.info() + attribute.info() + " " + value); return holder.updateValue(value); } } holder.remove(); return this.<T> setHolder(specializationClass, attribute, value, metaLevel, basePos, existsException, targets); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setHolder"
"public <T extends Holder> T setHolder(Class<?> specializationClass, Holder attribute, Serializable value, int metaLevel, int basePos, boolean existsException, Generic... targets) { // assert attribute.getMetaLevel() >= metaLevel; Generic meta = metaLevel == attribute.getMetaLevel() ? attribute.getMeta() : attribute; T holder = getSelectedHolder(attribute, value, metaLevel, basePos, targets); if (holder == null) return value == null ? null : this.<T> bind(((GenericImpl) meta).bindInstanceNode(value), specializationClass, attribute, basePos, existsException, targets); HomeTreeNode homeTreeNode = ((GenericImpl) meta).findInstanceNode(value); if (!equals(holder.getComponent(basePos))) { if (value == null) return cancel(holder, basePos, true); if (homeTreeNode != null && !(((GenericImpl) holder).equiv(homeTreeNode, new Primaries(homeTreeNode, attribute).toArray(), Statics.insertIntoArray(holder.getComponent(basePos), targets, basePos)))) cancel(holder, basePos, true); return this.<T> bind(((GenericImpl) meta).bindInstanceNode(value), specializationClass, attribute, basePos, existsException, targets); } if (homeTreeNode != null) { if (((GenericImpl) holder).equiv(homeTreeNode, new Primaries(homeTreeNode, attribute).toArray(), Statics.insertIntoArray(this, targets, basePos))) return holder; if (value != null && Arrays.equals(((GenericImpl) holder).components, Statics.insertIntoArray(this, targets, basePos))) { log.info("999999999999999" + holder.info() + attribute.info() + " " + value); return holder.updateValue(value); } <MASK>holder.remove();</MASK> } return this.<T> setHolder(specializationClass, attribute, value, metaLevel, basePos, existsException, targets); }"
Inversion-Mutation
megadiff
"public String getErrorsDisplay() { StringBuilder sb = new StringBuilder("<html>"); sb.append("<h3>Input was not valid</h3>"); for ( Map.Entry<String, List<String>> e : errors.entrySet() ) { sb.append("<h4>"); sb.append(e.getKey()).append(":"); sb.append("</h4>"); for ( String s : e.getValue() ) { sb.append("<ul>"); sb.append("<li>"); sb.append(s); sb.append("</li>"); sb.append("</ul>"); } } sb.append("</html>"); System.out.println(sb.toString()); return sb.toString(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getErrorsDisplay"
"public String getErrorsDisplay() { StringBuilder sb = new StringBuilder("<html>"); sb.append("<h3>Input was not valid</h3>"); for ( Map.Entry<String, List<String>> e : errors.entrySet() ) { sb.append("<h4>"); sb.append(e.getKey()).append(":"); sb.append("</h4>"); for ( String s : e.getValue() ) { sb.append("<ul>"); sb.append("<li>"); sb.append(s); sb.append("</li>"); sb.append("</ul>"); } <MASK>sb.append("</html>");</MASK> } System.out.println(sb.toString()); return sb.toString(); }"
Inversion-Mutation
megadiff
"@Override public boolean onTouchEvent(MotionEvent event) { int x = (int)event.getX(); int y = (int)event.getY(); final ZLView view = ZLApplication.Instance().getCurrentView(); switch (event.getAction()) { case MotionEvent.ACTION_UP: if (myPendingDoubleTap) { view.onFingerDoubleTap(); } if (myLongClickPerformed) { view.onFingerReleaseAfterLongPress(x, y); } else { if (myPendingLongClickRunnable != null) { removeCallbacks(myPendingLongClickRunnable); myPendingLongClickRunnable = null; } if (myPendingPress) { if (view.isDoubleTapSupported()) { if (myPendingShortClickRunnable == null) { myPendingShortClickRunnable = new ShortClickRunnable(); } postDelayed(myPendingShortClickRunnable, ViewConfiguration.getDoubleTapTimeout()); } else { view.onFingerSingleTap(x, y); } } else { view.onFingerRelease(x, y); } } myPendingDoubleTap = false; myPendingPress = false; myScreenIsTouched = false; break; case MotionEvent.ACTION_DOWN: if (myPendingShortClickRunnable != null) { removeCallbacks(myPendingShortClickRunnable); myPendingShortClickRunnable = null; myPendingDoubleTap = true; } else { postLongClickRunnable(); myPendingPress = true; } myScreenIsTouched = true; myPressedX = x; myPressedY = y; break; case MotionEvent.ACTION_MOVE: { final int slop = ViewConfiguration.get(getContext()).getScaledTouchSlop(); final boolean isAMove = Math.abs(myPressedX - x) > slop || Math.abs(myPressedY - y) > slop; if (isAMove) { myPendingDoubleTap = false; } if (myLongClickPerformed) { view.onFingerMoveAfterLongPress(x, y); } else { if (myPendingPress) { if (isAMove) { if (myPendingShortClickRunnable != null) { removeCallbacks(myPendingShortClickRunnable); myPendingShortClickRunnable = null; } if (myPendingLongClickRunnable != null) { removeCallbacks(myPendingLongClickRunnable); } view.onFingerPress(myPressedX, myPressedY); myPendingPress = false; } } if (!myPendingPress) { view.onFingerMove(x, y); } } break; } } return true; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onTouchEvent"
"@Override public boolean onTouchEvent(MotionEvent event) { int x = (int)event.getX(); int y = (int)event.getY(); final ZLView view = ZLApplication.Instance().getCurrentView(); switch (event.getAction()) { case MotionEvent.ACTION_UP: if (myPendingDoubleTap) { view.onFingerDoubleTap(); } if (myLongClickPerformed) { view.onFingerReleaseAfterLongPress(x, y); } else { if (myPendingLongClickRunnable != null) { removeCallbacks(myPendingLongClickRunnable); myPendingLongClickRunnable = null; } if (myPendingPress) { if (view.isDoubleTapSupported()) { if (myPendingShortClickRunnable == null) { myPendingShortClickRunnable = new ShortClickRunnable(); } postDelayed(myPendingShortClickRunnable, ViewConfiguration.getDoubleTapTimeout()); } else { view.onFingerSingleTap(x, y); } } else { view.onFingerRelease(x, y); } } myPendingDoubleTap = false; myPendingPress = false; myScreenIsTouched = false; break; case MotionEvent.ACTION_DOWN: if (myPendingShortClickRunnable != null) { removeCallbacks(myPendingShortClickRunnable); myPendingShortClickRunnable = null; myPendingDoubleTap = true; } else { postLongClickRunnable(); } myScreenIsTouched = true; <MASK>myPendingPress = true;</MASK> myPressedX = x; myPressedY = y; break; case MotionEvent.ACTION_MOVE: { final int slop = ViewConfiguration.get(getContext()).getScaledTouchSlop(); final boolean isAMove = Math.abs(myPressedX - x) > slop || Math.abs(myPressedY - y) > slop; if (isAMove) { myPendingDoubleTap = false; } if (myLongClickPerformed) { view.onFingerMoveAfterLongPress(x, y); } else { if (myPendingPress) { if (isAMove) { if (myPendingShortClickRunnable != null) { removeCallbacks(myPendingShortClickRunnable); myPendingShortClickRunnable = null; } if (myPendingLongClickRunnable != null) { removeCallbacks(myPendingLongClickRunnable); } view.onFingerPress(myPressedX, myPressedY); myPendingPress = false; } } if (!myPendingPress) { view.onFingerMove(x, y); } } break; } } return true; }"
Inversion-Mutation
megadiff
"@Override public void onRestoreInstanceState(Parcelable state) { final SavedState savedState = (SavedState) state; mSticker.createSticker(savedState.currentStickerSection); super.onRestoreInstanceState(savedState.getSuperState()); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onRestoreInstanceState"
"@Override public void onRestoreInstanceState(Parcelable state) { final SavedState savedState = (SavedState) state; <MASK>super.onRestoreInstanceState(savedState.getSuperState());</MASK> mSticker.createSticker(savedState.currentStickerSection); }"
Inversion-Mutation
megadiff
"private void handleRefresh() { if (!this.refresh) return; XMLModelNotifier notifier = getModelNotifier(); boolean isChanging = notifier.isChanging(); if (!isChanging) notifier.beginChanging(true); XMLModelParser parser = getModelParser(); setActive(parser); this.document.removeChildNodes(); try { this.refresh = false; parser.replaceStructuredDocumentRegions(getStructuredDocument().getRegionList(), null); } catch (Exception ex) { Logger.logException(ex); } finally { setActive(null); if (!isChanging) notifier.endChanging(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handleRefresh"
"private void handleRefresh() { if (!this.refresh) return; XMLModelNotifier notifier = getModelNotifier(); boolean isChanging = notifier.isChanging(); if (!isChanging) notifier.beginChanging(true); XMLModelParser parser = getModelParser(); setActive(parser); this.document.removeChildNodes(); try { parser.replaceStructuredDocumentRegions(getStructuredDocument().getRegionList(), null); } catch (Exception ex) { Logger.logException(ex); } finally { setActive(null); if (!isChanging) notifier.endChanging(); <MASK>this.refresh = false;</MASK> } }"
Inversion-Mutation
megadiff
"public void refresh(Attack attack){ setButtonsStatus(); Collection<Integer> temp=attack.getaDiceResults(); String tempS=""; for(Integer i: temp){ tempS+=i+";"; } if(tempS.endsWith(";")) tempS.substring(0, tempS.length()-1); thrownAttacker.setText(tempS); tempS=""; temp=attack.getdDiceResults(); for(Integer i: temp){ tempS+=i+";"; } if(tempS.endsWith(";")) tempS.substring(0, tempS.length()-1); thrownDefender.setText(tempS); int deltaA=0, deltaD=0; attack.calcLosses(deltaA, deltaD); lblFromCurrentArmies.setText(attack.getCountryPair().From.getTroops()+""); lblToCurrentArmies.setText(attack.getCountryPair().To.getTroops()+""); lblFromAfterArmies.setText(deltaA+""); lblToAfterArmies.setText(deltaD+""); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "refresh"
"public void refresh(Attack attack){ setButtonsStatus(); Collection<Integer> temp=attack.getaDiceResults(); String tempS=""; for(Integer i: temp){ tempS+=i+";"; } if(tempS.endsWith(";")) tempS.substring(0, tempS.length()-1); tempS=""; <MASK>thrownAttacker.setText(tempS);</MASK> temp=attack.getdDiceResults(); for(Integer i: temp){ tempS+=i+";"; } if(tempS.endsWith(";")) tempS.substring(0, tempS.length()-1); thrownDefender.setText(tempS); int deltaA=0, deltaD=0; attack.calcLosses(deltaA, deltaD); lblFromCurrentArmies.setText(attack.getCountryPair().From.getTroops()+""); lblToCurrentArmies.setText(attack.getCountryPair().To.getTroops()+""); lblFromAfterArmies.setText(deltaA+""); lblToAfterArmies.setText(deltaD+""); }"
Inversion-Mutation
megadiff
"public void setIgnoreList(String player, String reciever){ List<String> recievers=new ArrayList<String>(); if(ignoreList.size()>=1){ recievers= ignoreList.get(player); recievers.add(reciever); ignoreList.clear(); ignoreList.put(player, recievers); Bukkit.getPlayerExact(player).sendMessage("Added player "+ reciever +" to ignore list."); } else { recievers.add(reciever); ignoreList.put(player, recievers); Bukkit.getPlayerExact(player).sendMessage("Added player "+ reciever +" to ignore list."); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setIgnoreList"
"public void setIgnoreList(String player, String reciever){ List<String> recievers=new ArrayList<String>(); if(ignoreList.size()>=1){ recievers= ignoreList.get(player); <MASK>ignoreList.clear();</MASK> recievers.add(reciever); ignoreList.put(player, recievers); Bukkit.getPlayerExact(player).sendMessage("Added player "+ reciever +" to ignore list."); } else { recievers.add(reciever); ignoreList.put(player, recievers); Bukkit.getPlayerExact(player).sendMessage("Added player "+ reciever +" to ignore list."); } }"
Inversion-Mutation
megadiff
"public void createMessage(User currentUser, MessageParser mp, String groupId) throws IOException, MessagingException { ParseObject parseMessage = new ParseObject(MESSAGES_SCHEMA); parseMessage.put("message_id", mp.getMessageId()); parseMessage.put("user_id", currentUser.objectId); parseMessage.put("group_id", groupId); parseMessage.put("from", mp.getFrom()); parseMessage.put("content", mp.getContent()); if (mp.getCharset() != null) { parseMessage.put("charset", mp.getCharset()); } parseMessage.setCharset(mp.getCharset()); parseMessage.saveInBackground(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createMessage"
"public void createMessage(User currentUser, MessageParser mp, String groupId) throws IOException, MessagingException { ParseObject parseMessage = new ParseObject(MESSAGES_SCHEMA); parseMessage.put("message_id", mp.getMessageId()); parseMessage.put("user_id", currentUser.objectId); parseMessage.put("group_id", groupId); parseMessage.put("from", mp.getFrom()); if (mp.getCharset() != null) { parseMessage.put("charset", mp.getCharset()); } <MASK>parseMessage.put("content", mp.getContent());</MASK> parseMessage.setCharset(mp.getCharset()); parseMessage.saveInBackground(); }"
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
"protected void registerContextMenu() { MenuManager contextMenu = new MenuManager(); createContextMenu(contextMenu); contextMenu.add(new GroupMarker( IWorkbenchActionConstants.MB_ADDITIONS)); Control control = getTreeViewer().getControl(); Menu menu = contextMenu.createContextMenu(control); control.setMenu(menu); getSite().registerContextMenu(contextMenu, getTreeViewer()); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "registerContextMenu"
"protected void registerContextMenu() { MenuManager contextMenu = new MenuManager(); createContextMenu(contextMenu); contextMenu.add(new GroupMarker( IWorkbenchActionConstants.MB_ADDITIONS)); <MASK>getSite().registerContextMenu(contextMenu, getTreeViewer());</MASK> Control control = getTreeViewer().getControl(); Menu menu = contextMenu.createContextMenu(control); control.setMenu(menu); }"
Inversion-Mutation
megadiff
"@Override public boolean nextKeyValue() throws IOException, InterruptedException { if (tupleQueue.size() > 0) { tuple = tupleQueue.remove(0); return true; } try { // keep going until the decoder says it found a good one. PcapPacket packet = null; do { packet = is.getPacket(); eth.decode(packet); } while(!valid); long tv_sec = packet.getPacketHeader().getTsSec(); long tv_usec = packet.getPacketHeader().getTsUsec(); long ts = tv_sec * 1000 + tv_usec / 1000; key = new Date(ts).getTime() / 1000; int id = dns.getHeader().getID(); String mode = dns.getHeader().getFlag(Flags.QR)?"question":"response"; for(Record rec : dns.getSectionArray(Section.QUESTION)) { int i = 0; Tuple t = TupleFactory.getInstance().newTuple(7); t.set(i++, id); // transaction id t.set(i++, mode); // mode ('query' or 'response') t.set(i++, rec.getName().toString()); // qname t.set(i++, null); // answer.ip OR null (for ques) t.set(i++, 0); // qttl t.set(i++, srcIP); t.set(i++, dstIP); tupleQueue.add(t); } for(Record rec : dns.getSectionArray(Section.ANSWER)) { int i = 0; Tuple t = TupleFactory.getInstance().newTuple(7); t.set(i++, id); // transaction id t.set(i++, mode); // mode ('query' or 'response') t.set(i++, rec.getName().toString()); // qname if (rec instanceof ARecord) { t.set(i++, ((ARecord)rec).getAddress().getHostAddress()); // answer.ip OR null }else { t.set(i++, null); } t.set(i++, rec.getTTL()); // qttl t.set(i++, srcIP); t.set(i++, dstIP); tupleQueue.add(t); } clear(); if (tupleQueue.size() > 0) { tuple = tupleQueue.remove(0); return true; } else { clear(); is.close(); return false; } } catch (IOException ignored) { ignored.printStackTrace(); clear(); is.close(); return false; } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "nextKeyValue"
"@Override public boolean nextKeyValue() throws IOException, InterruptedException { if (tupleQueue.size() > 0) { tuple = tupleQueue.remove(0); return true; } try { // keep going until the decoder says it found a good one. PcapPacket packet = null; do { packet = is.getPacket(); eth.decode(packet); } while(!valid); long tv_sec = packet.getPacketHeader().getTsSec(); long tv_usec = packet.getPacketHeader().getTsUsec(); long ts = tv_sec * 1000 + tv_usec / 1000; key = new Date(ts).getTime() / 1000; int id = dns.getHeader().getID(); String mode = dns.getHeader().getFlag(Flags.QR)?"question":"response"; for(Record rec : dns.getSectionArray(Section.QUESTION)) { int i = 0; Tuple t = TupleFactory.getInstance().newTuple(7); t.set(i++, id); // transaction id t.set(i++, mode); // mode ('query' or 'response') t.set(i++, rec.getName().toString()); // qname t.set(i++, null); // answer.ip OR null (for ques) t.set(i++, 0); // qttl t.set(i++, srcIP); t.set(i++, dstIP); <MASK>tupleQueue.add(t);</MASK> } for(Record rec : dns.getSectionArray(Section.ANSWER)) { int i = 0; Tuple t = TupleFactory.getInstance().newTuple(7); t.set(i++, id); // transaction id t.set(i++, mode); // mode ('query' or 'response') t.set(i++, rec.getName().toString()); // qname if (rec instanceof ARecord) { t.set(i++, ((ARecord)rec).getAddress().getHostAddress()); // answer.ip OR null }else { t.set(i++, null); } t.set(i++, rec.getTTL()); // qttl <MASK>tupleQueue.add(t);</MASK> t.set(i++, srcIP); t.set(i++, dstIP); } clear(); if (tupleQueue.size() > 0) { tuple = tupleQueue.remove(0); return true; } else { clear(); is.close(); return false; } } catch (IOException ignored) { ignored.printStackTrace(); clear(); is.close(); return false; } }"
Inversion-Mutation
megadiff
"@Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { switch (position) { case 0:// Timeline getActionBar().setTitle("Timeline"); new GetNewsAsyncTask(MainActivity.this).execute(); cleanBackStack(); break; case 1:// Profile setTitle("Profile"); new ProfileAsyncTask(MainActivity.this).execute(); cleanBackStack(); break; case 2:// Messages setTitle("Messages"); new DiscussionHeadersAsyncTask(MainActivity.this).execute(); cleanBackStack(); break; case 3:// Map cleanBackStack(); setTitle("OpenStreetMap"); MapFragment fragment = new MapFragment(); getFragmentManager().beginTransaction().addToBackStack("map").replace(R.id.content_frame, fragment) .commit(); break; case 4: setTitle("My routes"); new RoutesAsyncTask(MainActivity.this).execute(""); cleanBackStack(); break; default:// Take a photo setTitle("Take a photo"); PictureFragment fragmentPicture = new PictureFragment(); getFragmentManager().beginTransaction().addToBackStack("photo") .replace(R.id.content_frame, fragmentPicture).commit(); dispatchTakePictureIntent(ACTION_TAKE_PHOTO_B); } mDrawerLayout.closeDrawer(mDrawerList); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onItemClick"
"@Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { switch (position) { case 0:// Timeline getActionBar().setTitle("Timeline"); new GetNewsAsyncTask(MainActivity.this).execute(); <MASK>cleanBackStack();</MASK> break; case 1:// Profile setTitle("Profile"); new ProfileAsyncTask(MainActivity.this).execute(); <MASK>cleanBackStack();</MASK> break; case 2:// Messages setTitle("Messages"); new DiscussionHeadersAsyncTask(MainActivity.this).execute(); <MASK>cleanBackStack();</MASK> break; case 3:// Map setTitle("OpenStreetMap"); MapFragment fragment = new MapFragment(); getFragmentManager().beginTransaction().addToBackStack("map").replace(R.id.content_frame, fragment) .commit(); <MASK>cleanBackStack();</MASK> break; case 4: setTitle("My routes"); new RoutesAsyncTask(MainActivity.this).execute(""); <MASK>cleanBackStack();</MASK> break; default:// Take a photo setTitle("Take a photo"); PictureFragment fragmentPicture = new PictureFragment(); getFragmentManager().beginTransaction().addToBackStack("photo") .replace(R.id.content_frame, fragmentPicture).commit(); dispatchTakePictureIntent(ACTION_TAKE_PHOTO_B); } mDrawerLayout.closeDrawer(mDrawerList); }"
Inversion-Mutation
megadiff
"private void createProject() { // get the target and try to resolve it. int targetId = mSdkCommandLine.getParamTargetId(); IAndroidTarget[] targets = mSdkManager.getTargets(); if (targetId < 1 || targetId > targets.length) { errorAndExit("Target id is not valid. Use '%s list targets' to get the target ids.", SdkConstants.androidCmdName()); } IAndroidTarget target = targets[targetId - 1]; ProjectCreator creator = new ProjectCreator(mSdkFolder, mSdkCommandLine.isVerbose() ? OutputLevel.VERBOSE : mSdkCommandLine.isSilent() ? OutputLevel.SILENT : OutputLevel.NORMAL, mSdkLog); String projectDir = getProjectLocation(mSdkCommandLine.getParamLocationPath()); String projectName = mSdkCommandLine.getParamName(); String packageName = mSdkCommandLine.getParamProjectPackage(); String activityName = mSdkCommandLine.getParamProjectActivity(); if (projectName != null && !ProjectCreator.RE_PROJECT_NAME.matcher(projectName).matches()) { errorAndExit( "Project name '%1$s' contains invalid characters.\nAllowed characters are: %2$s", projectName, ProjectCreator.CHARS_PROJECT_NAME); return; } if (activityName != null && !ProjectCreator.RE_ACTIVITY_NAME.matcher(activityName).matches()) { errorAndExit( "Activity name '%1$s' contains invalid characters.\nAllowed characters are: %2$s", activityName, ProjectCreator.CHARS_ACTIVITY_NAME); return; } if (packageName != null && !ProjectCreator.RE_PACKAGE_NAME.matcher(packageName).matches()) { errorAndExit( "Package name '%1$s' contains invalid characters.\n" + "A package name must be constitued of two Java identifiers.\n" + "Each identifier allowed characters are: %2$s", packageName, ProjectCreator.CHARS_PACKAGE_NAME); return; } creator.createProject(projectDir, projectName, packageName, activityName, target, false /* isTestProject*/); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createProject"
"private void createProject() { // get the target and try to resolve it. int targetId = mSdkCommandLine.getParamTargetId(); IAndroidTarget[] targets = mSdkManager.getTargets(); if (targetId < 1 || targetId > targets.length) { errorAndExit("Target id is not valid. Use '%s list targets' to get the target ids.", SdkConstants.androidCmdName()); } IAndroidTarget target = targets[targetId - 1]; ProjectCreator creator = new ProjectCreator(mSdkFolder, mSdkCommandLine.isVerbose() ? OutputLevel.VERBOSE : mSdkCommandLine.isSilent() ? OutputLevel.SILENT : OutputLevel.NORMAL, mSdkLog); String projectDir = getProjectLocation(mSdkCommandLine.getParamLocationPath()); String projectName = mSdkCommandLine.getParamName(); String packageName = mSdkCommandLine.getParamProjectPackage(); String activityName = mSdkCommandLine.getParamProjectActivity(); if (projectName != null && !ProjectCreator.RE_PROJECT_NAME.matcher(projectName).matches()) { errorAndExit( "Project name '%1$s' contains invalid characters.\nAllowed characters are: %2$s", projectName, ProjectCreator.CHARS_PROJECT_NAME); return; } if (activityName != null && !ProjectCreator.RE_ACTIVITY_NAME.matcher(activityName).matches()) { errorAndExit( "Activity name '%1$s' contains invalid characters.\nAllowed characters are: %2$s", <MASK>activityName,</MASK> ProjectCreator.CHARS_ACTIVITY_NAME); return; } if (packageName != null && !ProjectCreator.RE_PACKAGE_NAME.matcher(packageName).matches()) { errorAndExit( "Package name '%1$s' contains invalid characters.\n" + "A package name must be constitued of two Java identifiers.\n" + "Each identifier allowed characters are: %2$s", packageName, ProjectCreator.CHARS_PACKAGE_NAME); return; } creator.createProject(projectDir, projectName, <MASK>activityName,</MASK> packageName, target, false /* isTestProject*/); }"
Inversion-Mutation
megadiff
"private void initVariables() { config = this.getConfig(); itemFile = new File(this.getDataFolder() + File.separator + "items.csv"); preview = new PreviewCommand(this); new PreviewListener(this); server = Bukkit.getServer(); undo = new HashMap<String, ClearUndoHolder>(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "initVariables"
"private void initVariables() { config = this.getConfig(); itemFile = new File(this.getDataFolder() + File.separator + "items.csv"); new PreviewListener(this); server = Bukkit.getServer(); <MASK>preview = new PreviewCommand(this);</MASK> undo = new HashMap<String, ClearUndoHolder>(); }"
Inversion-Mutation
megadiff
"public void moveEditWindow(GraphicsConfiguration gc) { if (TopLevel.isMDIMode()) return; // only valid in SDI mode jf.setVisible(false); // hide old Frame //jf.getFocusOwner().setFocusable(false); //System.out.println("Set unfocasable: "+jf.getFocusOwner()); depopulateJFrame(); // remove all components from old Frame TopLevel oldFrame = jf; Cell cell = content.getCell(); // get current cell String cellDescription = (cell == null) ? "no cell" : cell.describe(false); // new title createJFrame(cellDescription, gc); // create new Frame populateJFrame(); // populate new Frame fireCellHistoryStatus(); // update tool bar history buttons oldFrame.finished(); // clear and garbage collect old Frame }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "moveEditWindow"
"public void moveEditWindow(GraphicsConfiguration gc) { if (TopLevel.isMDIMode()) return; // only valid in SDI mode jf.setVisible(false); // hide old Frame //jf.getFocusOwner().setFocusable(false); //System.out.println("Set unfocasable: "+jf.getFocusOwner()); depopulateJFrame(); // remove all components from old Frame TopLevel oldFrame = jf; <MASK>oldFrame.finished(); // clear and garbage collect old Frame</MASK> Cell cell = content.getCell(); // get current cell String cellDescription = (cell == null) ? "no cell" : cell.describe(false); // new title createJFrame(cellDescription, gc); // create new Frame populateJFrame(); // populate new Frame fireCellHistoryStatus(); // update tool bar history buttons }"
Inversion-Mutation
megadiff
"private void updateScreenshot(Tab tab) { // If this is a bookmarked site, add a screenshot to the database. // FIXME: Would like to make sure there is actually something to // draw, but the API for that (WebViewCore.pictureReady()) is not // currently accessible here. WebView view = tab.getWebView(); final String url = tab.getUrl(); final String originalUrl = view.getOriginalUrl(); if (TextUtils.isEmpty(url)) { return; } // Only update thumbnails for web urls (http(s)://), not for // about:, javascript:, data:, etc... // Unless it is a bookmarked site, then always update if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) { return; } final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity), getDesiredThumbnailHeight(mActivity)); if (bm == null) { return; } final ContentResolver cr = mActivity.getContentResolver(); new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... unused) { Cursor cursor = null; try { // TODO: Clean this up cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url); if (cursor != null && cursor.moveToFirst()) { final ByteArrayOutputStream os = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, os); ContentValues values = new ContentValues(); values.put(Images.THUMBNAIL, os.toByteArray()); do { values.put(Images.URL, cursor.getString(0)); cr.update(Images.CONTENT_URI, values, null, null); } while (cursor.moveToNext()); } } catch (IllegalStateException e) { // Ignore } finally { if (cursor != null) cursor.close(); } return null; } }.execute(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "updateScreenshot"
"private void updateScreenshot(Tab tab) { // If this is a bookmarked site, add a screenshot to the database. // FIXME: Would like to make sure there is actually something to // draw, but the API for that (WebViewCore.pictureReady()) is not // currently accessible here. WebView view = tab.getWebView(); final String url = tab.getUrl(); final String originalUrl = view.getOriginalUrl(); if (TextUtils.isEmpty(url)) { return; } // Only update thumbnails for web urls (http(s)://), not for // about:, javascript:, data:, etc... // Unless it is a bookmarked site, then always update if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) { return; } final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity), getDesiredThumbnailHeight(mActivity)); if (bm == null) { return; } final ContentResolver cr = mActivity.getContentResolver(); new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... unused) { Cursor cursor = null; try { // TODO: Clean this up cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url); if (cursor != null && cursor.moveToFirst()) { final ByteArrayOutputStream os = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, os); ContentValues values = new ContentValues(); values.put(Images.THUMBNAIL, os.toByteArray()); <MASK>values.put(Images.URL, cursor.getString(0));</MASK> do { cr.update(Images.CONTENT_URI, values, null, null); } while (cursor.moveToNext()); } } catch (IllegalStateException e) { // Ignore } finally { if (cursor != null) cursor.close(); } return null; } }.execute(); }"
Inversion-Mutation
megadiff
"@Override protected Void doInBackground(Void... unused) { Cursor cursor = null; try { // TODO: Clean this up cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url); if (cursor != null && cursor.moveToFirst()) { final ByteArrayOutputStream os = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, os); ContentValues values = new ContentValues(); values.put(Images.THUMBNAIL, os.toByteArray()); do { values.put(Images.URL, cursor.getString(0)); cr.update(Images.CONTENT_URI, values, null, null); } while (cursor.moveToNext()); } } catch (IllegalStateException e) { // Ignore } finally { if (cursor != null) cursor.close(); } return null; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doInBackground"
"@Override protected Void doInBackground(Void... unused) { Cursor cursor = null; try { // TODO: Clean this up cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url); if (cursor != null && cursor.moveToFirst()) { final ByteArrayOutputStream os = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, os); ContentValues values = new ContentValues(); values.put(Images.THUMBNAIL, os.toByteArray()); <MASK>values.put(Images.URL, cursor.getString(0));</MASK> do { cr.update(Images.CONTENT_URI, values, null, null); } while (cursor.moveToNext()); } } catch (IllegalStateException e) { // Ignore } finally { if (cursor != null) cursor.close(); } return null; }"
Inversion-Mutation
megadiff
"public static UILink make(UIContainer parent, String ID, String text, String target) { UILink togo = new UILink(); togo.ID = ID; togo.target = new UIOutput(); if (target != null) { togo.target.setValue(target); } if (text != null) { togo.linktext = new UIOutput(); togo.linktext.setValue(text); } parent.addComponent(togo); return togo; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "make"
"public static UILink make(UIContainer parent, String ID, String text, String target) { UILink togo = new UILink(); togo.ID = ID; togo.target = new UIOutput(); if (target != null) { togo.target.setValue(target); } <MASK>togo.linktext = new UIOutput();</MASK> if (text != null) { togo.linktext.setValue(text); } parent.addComponent(togo); return togo; }"
Inversion-Mutation
megadiff
"public void connectWithRef(final String url, final int connCount, Object ref) throws NotifyRemotingException { final Set<Object> refs = this.getReferences(url); synchronized (refs) { this.remotingClient.connect(url, connCount); refs.add(ref); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "connectWithRef"
"public void connectWithRef(final String url, final int connCount, Object ref) throws NotifyRemotingException { final Set<Object> refs = this.getReferences(url); <MASK>this.remotingClient.connect(url, connCount);</MASK> synchronized (refs) { refs.add(ref); } }"
Inversion-Mutation
megadiff
"public @Nonnull Org authenticate(boolean force) throws CloudException, InternalException { Cache<Org> cache = Cache.getInstance(provider, "vCloudOrgs", Org.class, CacheLevel.CLOUD_ACCOUNT, new TimePeriod<Minute>(25, TimePeriod.MINUTE)); ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new CloudException("No context was defined for this request"); } String accountNumber = ctx.getAccountNumber(); Iterable<Org> orgs = cache.get(ctx); Iterator<Org> it = ((force || orgs == null) ? null : orgs.iterator()); if( it == null || !it.hasNext() ) { String endpoint = getVersion().loginUrl; HttpClient client = getClient(true); HttpPost method = new HttpPost(endpoint); Org org = new Org(); org.version = getVersion(); method.addHeader("Accept", "application/*+xml;version=" + org.version.version + ",application/*+xml;version=" + org.version.version); if( wire.isDebugEnabled() ) { wire.debug(""); wire.debug(">>> [POST (" + (new Date()) + ")] -> " + endpoint + " >--------------------------------------------------------------------------------------"); } HttpResponse response; StatusLine status; String body = null; try { if( wire.isDebugEnabled() ) { wire.debug(method.getRequestLine().toString()); for( Header header : method.getAllHeaders() ) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } try { APITrace.trace(provider, "POST sessions"); response = client.execute(method); if( wire.isDebugEnabled() ) { wire.debug(response.getStatusLine().toString()); for( Header header : response.getAllHeaders() ) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } status = response.getStatusLine(); } catch( IOException e ) { throw new CloudException(e); } HttpEntity entity = response.getEntity(); try { body = EntityUtils.toString(entity); if( wire.isDebugEnabled() ) { wire.debug(body); wire.debug(""); } } catch( IOException e ) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } } finally { if( wire.isDebugEnabled() ) { wire.debug("<<< [POST (" + (new Date()) + ")] -> " + endpoint + " <--------------------------------------------------------------------------------------"); wire.debug(""); } } if( status.getStatusCode() == HttpServletResponse.SC_OK ) { if( matches(getAPIVersion(), "0.8", "0.8") ) { for( Header h : response.getHeaders("Set-Cookie") ) { String value = h.getValue(); if( value != null ) { value = value.trim(); if( value.startsWith("vcloud-token") ) { value = value.substring("vcloud-token=".length()); int idx = value.indexOf(";"); if( idx == -1 ) { org.token = value; } else { org.token = value.substring(0, idx); } } } } } else { org.token = response.getFirstHeader("x-vcloud-authorization").getValue(); } if( org.token == null ) { throw new CloudException(CloudErrorType.AUTHENTICATION, 200, "Token Empty", "No token was provided"); } try { ByteArrayInputStream bas = new ByteArrayInputStream(body.getBytes()); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document doc = parser.parse(bas); bas.close(); if( matches(org.version.version, "1.5", null) ) { NodeList orgNodes = doc.getElementsByTagName("Link"); String orgList = null; for( int i=0; i<orgNodes.getLength(); i++ ) { Node orgNode = orgNodes.item(i); if( orgNode.hasAttributes() ) { Node type = orgNode.getAttributes().getNamedItem("type"); if( type != null && type.getNodeValue().trim().equals(getMediaTypeForOrg()) ) { Node name = orgNode.getAttributes().getNamedItem("name"); if( name != null && name.getNodeValue().trim().equals(accountNumber) ) { Node href = orgNode.getAttributes().getNamedItem("href"); if( href != null ) { Region region = new Region(); String url = href.getNodeValue().trim(); region.setActive(true); region.setAvailable(true); if( provider.isCompat() ) { region.setProviderRegionId("/org/" + url.substring(url.lastIndexOf('/') + 1)); } else { region.setProviderRegionId(url.substring(url.lastIndexOf('/') + 1)); } region.setJurisdiction("US"); region.setName(name.getNodeValue().trim()); org.endpoint = url.substring(0, url.lastIndexOf("/api/org")); org.region = region; org.url = url; } } } if( type != null && type.getNodeValue().trim().equals(getMediaTypeForOrgList()) ) { Node href = orgNode.getAttributes().getNamedItem("href"); if( href != null ) { orgList = href.getNodeValue().trim(); } } } } if( org.endpoint == null && orgList != null ) { loadOrg(orgList, org, accountNumber); } } else { NodeList orgNodes = doc.getElementsByTagName("Org"); for( int i=0; i<orgNodes.getLength(); i++ ) { Node orgNode = orgNodes.item(i); if( orgNode.hasAttributes() ) { Node name = orgNode.getAttributes().getNamedItem("name"); Node href = orgNode.getAttributes().getNamedItem("href"); if( href != null ) { String url = href.getNodeValue().trim(); Region region = new Region(); if( !url.endsWith("/org/" + accountNumber) ) { continue; } region.setActive(true); region.setAvailable(true); if( provider.isCompat() ) { region.setProviderRegionId("/org/" + url.substring(url.lastIndexOf('/') + 1)); } else { region.setProviderRegionId(url.substring(url.lastIndexOf('/') + 1)); } region.setJurisdiction("US"); region.setName(name == null ? accountNumber : name.getNodeValue().trim()); org.endpoint = url.substring(0, url.lastIndexOf("/org/")); org.region = region; org.url = url; } } } } } catch( IOException e ) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } catch( ParserConfigurationException e ) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } catch( SAXException e ) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } } else { HttpEntity entity = response.getEntity(); if( entity != null ) { vCloudException.Data data = null; if( body != null && !body.equals("") ) { NodeList errors = parseXML(body).getElementsByTagName("Error"); if( errors.getLength() > 0 ) { data = vCloudException.parseException(status.getStatusCode(), errors.item(0)); } } if( data == null ) { logger.error("Received an error from " + provider.getCloudName() + " with no data: " + status.getStatusCode() + "/" + response.getStatusLine().getReasonPhrase()); throw new vCloudException(CloudErrorType.GENERAL, status.getStatusCode(), response.getStatusLine().getReasonPhrase(), "No further information"); } logger.error("[" + status.getStatusCode() + " : " + data.title + "] " + data.description); throw new vCloudException(data); } throw new CloudException(CloudErrorType.AUTHENTICATION, status.getStatusCode(), status.getReasonPhrase(), "Authentication failed"); } if( org.endpoint == null ) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), "No Org", "No org was identified for " + ctx.getAccountNumber()); } loadVDCs(org); cache.put(ctx, Collections.singletonList(org)); return org; } else { return it.next(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "authenticate"
"public @Nonnull Org authenticate(boolean force) throws CloudException, InternalException { Cache<Org> cache = Cache.getInstance(provider, "vCloudOrgs", Org.class, CacheLevel.CLOUD_ACCOUNT, new TimePeriod<Minute>(25, TimePeriod.MINUTE)); ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new CloudException("No context was defined for this request"); } String accountNumber = ctx.getAccountNumber(); Iterable<Org> orgs = cache.get(ctx); Iterator<Org> it = ((force || orgs == null) ? null : orgs.iterator()); if( it == null || !it.hasNext() ) { String endpoint = getVersion().loginUrl; HttpClient client = getClient(true); HttpPost method = new HttpPost(endpoint); Org org = new Org(); org.version = getVersion(); method.addHeader("Accept", "application/*+xml;version=" + org.version.version + ",application/*+xml;version=" + org.version.version); if( wire.isDebugEnabled() ) { wire.debug(""); wire.debug(">>> [POST (" + (new Date()) + ")] -> " + endpoint + " >--------------------------------------------------------------------------------------"); } HttpResponse response; StatusLine status; String body = null; try { if( wire.isDebugEnabled() ) { wire.debug(method.getRequestLine().toString()); for( Header header : method.getAllHeaders() ) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } try { APITrace.trace(provider, "POST sessions"); response = client.execute(method); if( wire.isDebugEnabled() ) { wire.debug(response.getStatusLine().toString()); for( Header header : response.getAllHeaders() ) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } status = response.getStatusLine(); } catch( IOException e ) { throw new CloudException(e); } HttpEntity entity = response.getEntity(); try { body = EntityUtils.toString(entity); if( wire.isDebugEnabled() ) { wire.debug(body); wire.debug(""); } } catch( IOException e ) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } } finally { if( wire.isDebugEnabled() ) { wire.debug("<<< [POST (" + (new Date()) + ")] -> " + endpoint + " <--------------------------------------------------------------------------------------"); wire.debug(""); } } if( status.getStatusCode() == HttpServletResponse.SC_OK ) { if( matches(getAPIVersion(), "0.8", "0.8") ) { for( Header h : response.getHeaders("Set-Cookie") ) { String value = h.getValue(); if( value != null ) { value = value.trim(); if( value.startsWith("vcloud-token") ) { value = value.substring("vcloud-token=".length()); int idx = value.indexOf(";"); if( idx == -1 ) { org.token = value; } else { org.token = value.substring(0, idx); } } } } } else { org.token = response.getFirstHeader("x-vcloud-authorization").getValue(); } if( org.token == null ) { throw new CloudException(CloudErrorType.AUTHENTICATION, 200, "Token Empty", "No token was provided"); } try { ByteArrayInputStream bas = new ByteArrayInputStream(body.getBytes()); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document doc = parser.parse(bas); bas.close(); if( matches(org.version.version, "1.5", null) ) { NodeList orgNodes = doc.getElementsByTagName("Link"); String orgList = null; for( int i=0; i<orgNodes.getLength(); i++ ) { Node orgNode = orgNodes.item(i); if( orgNode.hasAttributes() ) { Node type = orgNode.getAttributes().getNamedItem("type"); if( type != null && type.getNodeValue().trim().equals(getMediaTypeForOrg()) ) { Node name = orgNode.getAttributes().getNamedItem("name"); if( name != null && name.getNodeValue().trim().equals(accountNumber) ) { Node href = orgNode.getAttributes().getNamedItem("href"); if( href != null ) { Region region = new Region(); String url = href.getNodeValue().trim(); region.setActive(true); region.setAvailable(true); if( provider.isCompat() ) { region.setProviderRegionId("/org/" + url.substring(url.lastIndexOf('/') + 1)); } else { region.setProviderRegionId(url.substring(url.lastIndexOf('/') + 1)); } region.setJurisdiction("US"); region.setName(name.getNodeValue().trim()); org.endpoint = url.substring(0, url.lastIndexOf("/api/org")); org.region = region; org.url = url; } } } if( type != null && type.getNodeValue().trim().equals(getMediaTypeForOrgList()) ) { Node href = orgNode.getAttributes().getNamedItem("href"); if( href != null ) { orgList = href.getNodeValue().trim(); } } } } if( org.endpoint == null && orgList != null ) { loadOrg(orgList, org, accountNumber); } } else { NodeList orgNodes = doc.getElementsByTagName("Org"); for( int i=0; i<orgNodes.getLength(); i++ ) { Node orgNode = orgNodes.item(i); if( orgNode.hasAttributes() ) { Node name = orgNode.getAttributes().getNamedItem("name"); Node href = orgNode.getAttributes().getNamedItem("href"); if( href != null ) { String url = href.getNodeValue().trim(); Region region = new Region(); if( !url.endsWith("/org/" + accountNumber) ) { continue; } region.setActive(true); region.setAvailable(true); if( provider.isCompat() ) { region.setProviderRegionId("/org/" + url.substring(url.lastIndexOf('/') + 1)); } else { region.setProviderRegionId(url.substring(url.lastIndexOf('/') + 1)); } region.setJurisdiction("US"); region.setName(name == null ? accountNumber : name.getNodeValue().trim()); org.endpoint = url.substring(0, url.lastIndexOf("/org/")); org.region = region; org.url = url; } } } } } catch( IOException e ) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } catch( ParserConfigurationException e ) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } catch( SAXException e ) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } } else { HttpEntity entity = response.getEntity(); if( entity != null ) { vCloudException.Data data = null; if( body != null && !body.equals("") ) { NodeList errors = parseXML(body).getElementsByTagName("Error"); if( errors.getLength() > 0 ) { data = vCloudException.parseException(status.getStatusCode(), errors.item(0)); } } if( data == null ) { logger.error("Received an error from " + provider.getCloudName() + " with no data: " + status.getStatusCode() + "/" + response.getStatusLine().getReasonPhrase()); throw new vCloudException(CloudErrorType.GENERAL, status.getStatusCode(), response.getStatusLine().getReasonPhrase(), "No further information"); } logger.error("[" + status.getStatusCode() + " : " + data.title + "] " + data.description); throw new vCloudException(data); } throw new CloudException(CloudErrorType.AUTHENTICATION, status.getStatusCode(), status.getReasonPhrase(), "Authentication failed"); } if( org.endpoint == null ) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), "No Org", "No org was identified for " + ctx.getAccountNumber()); } <MASK>cache.put(ctx, Collections.singletonList(org));</MASK> loadVDCs(org); return org; } else { return it.next(); } }"
Inversion-Mutation
megadiff
"private void runPipeline() throws Exception { String uuid = null; while ((uuid = waitForInput()) != null) { TransformedGraphImpl transformedGraphImpl = null; try { LOG.info(String.format("PipelineService starts processing graph %s", uuid)); int pipelineId = _workingInputGraphStatus.getGraphPipelineId(uuid); Collection<TransformerCommand> TransformerCommands = TransformerCommand.getActualPlan("DB.ODCLEANSTORE", pipelineId); loadData(uuid); LOG.info(String.format("PipelineService ends data loading for graph %s", uuid)); for (TransformerCommand transformerCommand : TransformerCommands) { transformedGraphImpl = transformedGraphImpl == null ? new TransformedGraphImpl(_workingInputGraphStatus, uuid) : new TransformedGraphImpl(transformedGraphImpl); processTransformer(transformerCommand, transformedGraphImpl); if (transformedGraphImpl.isDeleted()) { break; } } } catch (Exception e) { _workingInputGraphStatus.setWorkingTransformedGraph(null); _workingInputGraphStatus.setState(uuid, InputGraphState.DIRTY); throw e; } if (transformedGraphImpl != null && transformedGraphImpl.isDeleted()) { processDeletingState(uuid); } else { _workingInputGraphStatus.setState(uuid, InputGraphState.PROCESSED); processProcessedState(uuid); processPropagatedState(uuid); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "runPipeline"
"private void runPipeline() throws Exception { <MASK>TransformedGraphImpl transformedGraphImpl = null;</MASK> String uuid = null; while ((uuid = waitForInput()) != null) { try { LOG.info(String.format("PipelineService starts processing graph %s", uuid)); int pipelineId = _workingInputGraphStatus.getGraphPipelineId(uuid); Collection<TransformerCommand> TransformerCommands = TransformerCommand.getActualPlan("DB.ODCLEANSTORE", pipelineId); loadData(uuid); LOG.info(String.format("PipelineService ends data loading for graph %s", uuid)); for (TransformerCommand transformerCommand : TransformerCommands) { transformedGraphImpl = transformedGraphImpl == null ? new TransformedGraphImpl(_workingInputGraphStatus, uuid) : new TransformedGraphImpl(transformedGraphImpl); processTransformer(transformerCommand, transformedGraphImpl); if (transformedGraphImpl.isDeleted()) { break; } } } catch (Exception e) { _workingInputGraphStatus.setWorkingTransformedGraph(null); _workingInputGraphStatus.setState(uuid, InputGraphState.DIRTY); throw e; } if (transformedGraphImpl != null && transformedGraphImpl.isDeleted()) { processDeletingState(uuid); } else { _workingInputGraphStatus.setState(uuid, InputGraphState.PROCESSED); processProcessedState(uuid); processPropagatedState(uuid); } } }"
Inversion-Mutation
megadiff
"protected void performApply() { if (proxyService == null) return; boolean proxiesEnabled = manualProxyConfigurationButton.getSelection(); // Save the contents of the text fields to the proxy data. IProxyData[] proxyData = new IProxyData[entryList.length]; for (int index = 0; index < entryList.length; index++) { entryList[index].applyValues(); proxyData[index] = entryList[index].getProxy(); } proxyService.setProxiesEnabled(proxiesEnabled); if (proxiesEnabled) { try { proxyService.setNonProxiedHosts( nonHostComposite.getList()); proxyService.setProxyData(proxyData); } catch (CoreException e) { ErrorDialog.openError(getShell(), null, null, e.getStatus()); } } Activator.getDefault().savePluginPreferences(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "performApply"
"protected void performApply() { if (proxyService == null) return; boolean proxiesEnabled = manualProxyConfigurationButton.getSelection(); // Save the contents of the text fields to the proxy data. IProxyData[] proxyData = new IProxyData[entryList.length]; for (int index = 0; index < entryList.length; index++) { entryList[index].applyValues(); proxyData[index] = entryList[index].getProxy(); } proxyService.setProxiesEnabled(proxiesEnabled); if (proxiesEnabled) { try { <MASK>proxyService.setProxyData(proxyData);</MASK> proxyService.setNonProxiedHosts( nonHostComposite.getList()); } catch (CoreException e) { ErrorDialog.openError(getShell(), null, null, e.getStatus()); } } Activator.getDefault().savePluginPreferences(); }"
Inversion-Mutation
megadiff
"public int main(List<String> args, Locale locale, InputStream stdin, PrintStream stdout, PrintStream stderr) { this.stdin = new BufferedInputStream(stdin); this.stdout = stdout; this.stderr = stderr; this.locale = locale; this.channel = Channel.current(); registerOptionHandlers(); CmdLineParser p = new CmdLineParser(this); // add options from the authenticator SecurityContext sc = SecurityContextHolder.getContext(); Authentication old = sc.getAuthentication(); CliAuthenticator authenticator = HudsonSecurityEntitiesHolder.getHudsonSecurityManager().getSecurityRealm().createCliAuthenticator(this); new ClassParser().parse(authenticator, p); try { p.parseArgument(args.toArray(new String[args.size()])); Authentication auth = authenticator.authenticate(); if (auth == Hudson.ANONYMOUS) { auth = loadStoredAuthentication(); } sc.setAuthentication(auth); // run the CLI with the right credential if (!(this instanceof LoginCommand || this instanceof HelpCommand)) { Hudson.getInstance().checkPermission(Hudson.READ); } return run(); } catch (CmdLineException e) { stderr.println(e.getMessage()); printUsage(stderr, p); return -1; } catch (AbortException e) { // signals an error without stack trace stderr.println(e.getMessage()); return -1; } catch (Exception e) { e.printStackTrace(stderr); return -1; } finally { sc.setAuthentication(old); // restore } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "main"
"public int main(List<String> args, Locale locale, InputStream stdin, PrintStream stdout, PrintStream stderr) { this.stdin = new BufferedInputStream(stdin); this.stdout = stdout; this.stderr = stderr; this.locale = locale; this.channel = Channel.current(); registerOptionHandlers(); CmdLineParser p = new CmdLineParser(this); // add options from the authenticator SecurityContext sc = SecurityContextHolder.getContext(); Authentication old = sc.getAuthentication(); CliAuthenticator authenticator = HudsonSecurityEntitiesHolder.getHudsonSecurityManager().getSecurityRealm().createCliAuthenticator(this); new ClassParser().parse(authenticator, p); try { Authentication auth = authenticator.authenticate(); if (auth == Hudson.ANONYMOUS) { auth = loadStoredAuthentication(); } sc.setAuthentication(auth); // run the CLI with the right credential <MASK>p.parseArgument(args.toArray(new String[args.size()]));</MASK> if (!(this instanceof LoginCommand || this instanceof HelpCommand)) { Hudson.getInstance().checkPermission(Hudson.READ); } return run(); } catch (CmdLineException e) { stderr.println(e.getMessage()); printUsage(stderr, p); return -1; } catch (AbortException e) { // signals an error without stack trace stderr.println(e.getMessage()); return -1; } catch (Exception e) { e.printStackTrace(stderr); return -1; } finally { sc.setAuthentication(old); // restore } }"
Inversion-Mutation
megadiff
"public void onEnable() { prisonSuite = PrisonSuite.addPlugin(this); getConfig().options().copyDefaults(true); saveConfig(); settings = new Settings(this); Message.debug("1. Established connection with PrisonCore"); getLanguageData().options().copyDefaults(true); saveLanguageData(); language = new Language(this); Message.debug("2. Loaded plugin configuration"); commandManager = new CommandManager(this); getCommand("mine").setExecutor(commandManager); Message.debug("3. Started up the CommandManager"); ConfigurationSerialization.registerClass(Mine.class, "Mine"); ConfigurationSerialization.registerClass(MineBlock.class, "MineBlock"); ConfigurationSerialization.registerClass(Blacklist.class, "Blacklist"); ConfigurationSerialization.registerClass(DisplaySign.class, "DisplaySign"); ConfigurationSerialization.registerClass(DataBlock.class, "DataBlock"); ConfigurationSerialization.registerClass(SimpleLoc.class, "SimpleLoc"); ConfigurationSerialization.registerClass(Protection.class, "Protection"); ConfigurationSerialization.registerClass(PrisonRegion.class, "PrisonRegion"); Message.debug("4. Registered serializable classes"); mines = MineData.loadAll(); signs = SignData.loadAll(); generators = GeneratorUtil.loadAll(); Message.debug("5. Loaded data from file"); new BlockBreakListener(this); new BlockPlaceListener(this); new BucketEmptyListener(this); new BucketFillListener(this); new SignClickListener(this); new PVPListener(this); new ButtonPressListener(this); Message.debug("6. Started up event listeners"); Message.log("PrisonMine started [ " + mines.size() + " mine(s) found ]"); Message.debug("7. Sending a timed task to PrisonCore"); PrisonSuite.addTask(new MineTask(20)); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onEnable"
"public void onEnable() { prisonSuite = PrisonSuite.addPlugin(this); <MASK>Message.debug("1. Established connection with PrisonCore");</MASK> getConfig().options().copyDefaults(true); saveConfig(); settings = new Settings(this); getLanguageData().options().copyDefaults(true); saveLanguageData(); language = new Language(this); Message.debug("2. Loaded plugin configuration"); commandManager = new CommandManager(this); getCommand("mine").setExecutor(commandManager); Message.debug("3. Started up the CommandManager"); ConfigurationSerialization.registerClass(Mine.class, "Mine"); ConfigurationSerialization.registerClass(MineBlock.class, "MineBlock"); ConfigurationSerialization.registerClass(Blacklist.class, "Blacklist"); ConfigurationSerialization.registerClass(DisplaySign.class, "DisplaySign"); ConfigurationSerialization.registerClass(DataBlock.class, "DataBlock"); ConfigurationSerialization.registerClass(SimpleLoc.class, "SimpleLoc"); ConfigurationSerialization.registerClass(Protection.class, "Protection"); ConfigurationSerialization.registerClass(PrisonRegion.class, "PrisonRegion"); Message.debug("4. Registered serializable classes"); mines = MineData.loadAll(); signs = SignData.loadAll(); generators = GeneratorUtil.loadAll(); Message.debug("5. Loaded data from file"); new BlockBreakListener(this); new BlockPlaceListener(this); new BucketEmptyListener(this); new BucketFillListener(this); new SignClickListener(this); new PVPListener(this); new ButtonPressListener(this); Message.debug("6. Started up event listeners"); Message.log("PrisonMine started [ " + mines.size() + " mine(s) found ]"); Message.debug("7. Sending a timed task to PrisonCore"); PrisonSuite.addTask(new MineTask(20)); }"
Inversion-Mutation
megadiff
"public Connection(Socket cSocket) { clientSocket = cSocket; shutDown = false; try { outStream = new ObjectOutputStream(cSocket.getOutputStream()); inStream = new ObjectInputStream(cSocket.getInputStream()); } catch (IOException ie) { } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "Connection"
"public Connection(Socket cSocket) { clientSocket = cSocket; shutDown = false; try { inStream = new ObjectInputStream(cSocket.getInputStream()); <MASK>outStream = new ObjectOutputStream(cSocket.getOutputStream());</MASK> } catch (IOException ie) { } }"
Inversion-Mutation
megadiff
"@Override public void run() { LogQueryCommand cmd = null; try { cmd = subQuery.get(subQuery.size() - 1); for (int i = subQuery.size() - 1; i >= 0; i--) subQuery.get(i).start(); subQuery.get(0).eof(false); try { subQueryResultSet = subQueryResult.getResult(); logger.debug("araqne logdb: fetch subquery result of query [{}:{}]", logQuery.getId(), logQuery.getQueryString()); if (subQueryResultSet.size() <= HASH_JOIN_THRESHOLD) buildHashJoinTable(); } catch (IOException e) { logger.error("araqne logdb: cannot get subquery result of query " + logQuery.getId(), e); } } catch (Throwable t) { logger.error("araqne logdb: subquery failed, query " + logQuery.getId(), t); } finally { if (cmd != null) { synchronized (cmd) { cmd.notifyAll(); } } logger.debug("araqne logdb: subquery end, query " + logQuery.getId()); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"@Override public void run() { LogQueryCommand cmd = null; try { for (int i = subQuery.size() - 1; i >= 0; i--) subQuery.get(i).start(); subQuery.get(0).eof(false); <MASK>cmd = subQuery.get(subQuery.size() - 1);</MASK> try { subQueryResultSet = subQueryResult.getResult(); logger.debug("araqne logdb: fetch subquery result of query [{}:{}]", logQuery.getId(), logQuery.getQueryString()); if (subQueryResultSet.size() <= HASH_JOIN_THRESHOLD) buildHashJoinTable(); } catch (IOException e) { logger.error("araqne logdb: cannot get subquery result of query " + logQuery.getId(), e); } } catch (Throwable t) { logger.error("araqne logdb: subquery failed, query " + logQuery.getId(), t); } finally { if (cmd != null) { synchronized (cmd) { cmd.notifyAll(); } } logger.debug("araqne logdb: subquery end, query " + logQuery.getId()); } }"
Inversion-Mutation
megadiff
"@Override public void execute(LogOutUICommand command) throws FatalException { Service service = serviceRegistry.getCurrentService(); IPlayer currentPlayer = serviceRegistry.getPlayer(service); if (currentPlayer != null) { try { dispatcher.dispatch(new SendMessageToUserCommand("Zegnaj, " + currentPlayer.getName(), INFO)); dispatcher.dispatch(new SendAvailableCommandsCommand( currentPlayer, AvailableCommands.getInstance() .getUnloggedCommands())); dispatcher.dispatch(new LogOutCommand()); service.writeObject((IPlayer) null); } catch (IOException e) { throw new FatalException(e); } } else { dispatcher.dispatch(new SendMessageToUserCommand( "Nie jestes zalogowany!", INFO)); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "execute"
"@Override public void execute(LogOutUICommand command) throws FatalException { Service service = serviceRegistry.getCurrentService(); IPlayer currentPlayer = serviceRegistry.getPlayer(service); if (currentPlayer != null) { try { <MASK>dispatcher.dispatch(new LogOutCommand());</MASK> dispatcher.dispatch(new SendMessageToUserCommand("Zegnaj, " + currentPlayer.getName(), INFO)); dispatcher.dispatch(new SendAvailableCommandsCommand( currentPlayer, AvailableCommands.getInstance() .getUnloggedCommands())); service.writeObject((IPlayer) null); } catch (IOException e) { throw new FatalException(e); } } else { dispatcher.dispatch(new SendMessageToUserCommand( "Nie jestes zalogowany!", INFO)); } }"
Inversion-Mutation
megadiff
"public List<TransmissionQbf> splitQbf(int n, Heuristic h) { TransmissionQbf tmp; for (int i = 0; i < n; i++) { qbfResults.add(i, false); resultAvailable.add(i, false); resultProcessed.add(i, false); tmp = new TransmissionQbf(); tmp.setId((new Integer(id * 1000 + i)).toString()); tmp.setEVars(eVars); tmp.setAVars(aVars); tmp.setVars(vars); tmp.setRootNode(root); tmp.setTrueVars(h.decide(this)); subQbfs.add(tmp); } // do stuff // TODO (returns empty TransmissionQbfs until this works) return subQbfs; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "splitQbf"
"public List<TransmissionQbf> splitQbf(int n, Heuristic h) { TransmissionQbf tmp; for (int i = 0; i < n; i++) { qbfResults.add(i, false); resultAvailable.add(i, false); resultProcessed.add(i, false); tmp = new TransmissionQbf(); tmp.setId((new Integer(id * 1000 + i)).toString()); tmp.setEVars(eVars); tmp.setAVars(aVars); tmp.setVars(vars); <MASK>tmp.setTrueVars(h.decide(this));</MASK> tmp.setRootNode(root); subQbfs.add(tmp); } // do stuff // TODO (returns empty TransmissionQbfs until this works) return subQbfs; }"
Inversion-Mutation
megadiff
"protected void onPostExecute(Void unused) { Dialog.dismiss(); if (Error != null) { Toast.makeText(ZeitGeistReichActivity.this, Error, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(ZeitGeistReichActivity.this, "Image uploaded.", Toast.LENGTH_SHORT).show(); } finish(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onPostExecute"
"protected void onPostExecute(Void unused) { Dialog.dismiss(); if (Error != null) { Toast.makeText(ZeitGeistReichActivity.this, Error, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(ZeitGeistReichActivity.this, "Image uploaded.", Toast.LENGTH_SHORT).show(); <MASK>finish();</MASK> } }"
Inversion-Mutation
megadiff
"public static void initDimension(int dim) { WorldServer overworld = getWorld(0); if (overworld == null) { throw new RuntimeException("Cannot Hotload Dim: Overworld is not Loaded!"); } try { DimensionManager.getProviderType(dim); } catch (Exception e) { System.err.println("Cannot Hotload Dim: " + e.getMessage()); return; //If a provider hasn't been registered then we can't hotload the dim } MinecraftServer mcServer = overworld.getMinecraftServer(); ISaveHandler savehandler = overworld.getSaveHandler(); WorldSettings worldSettings = new WorldSettings(overworld.getWorldInfo()); WorldServer world = (dim == 0 ? overworld : new WorldServerMulti(mcServer, savehandler, overworld.getWorldInfo().getWorldName(), dim, worldSettings, overworld, mcServer.theProfiler)); world.addWorldAccess(new WorldManager(mcServer, world)); MinecraftForge.EVENT_BUS.post(new WorldEvent.Load(world)); if (!mcServer.isSinglePlayer()) { world.getWorldInfo().setGameType(mcServer.getGameType()); } mcServer.setDifficultyForAllWorlds(mcServer.getDifficulty()); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "initDimension"
"public static void initDimension(int dim) { WorldServer overworld = getWorld(0); if (overworld == null) { throw new RuntimeException("Cannot Hotload Dim: Overworld is not Loaded!"); } try { DimensionManager.getProviderType(dim); } catch (Exception e) { System.err.println("Cannot Hotload Dim: " + e.getMessage()); return; //If a provider hasn't been registered then we can't hotload the dim } MinecraftServer mcServer = overworld.getMinecraftServer(); ISaveHandler savehandler = overworld.getSaveHandler(); WorldSettings worldSettings = new WorldSettings(overworld.getWorldInfo()); WorldServer world = (dim == 0 ? overworld : new WorldServerMulti(mcServer, savehandler, overworld.getWorldInfo().getWorldName(), dim, worldSettings, overworld, mcServer.theProfiler)); <MASK>MinecraftForge.EVENT_BUS.post(new WorldEvent.Load(world));</MASK> world.addWorldAccess(new WorldManager(mcServer, world)); if (!mcServer.isSinglePlayer()) { world.getWorldInfo().setGameType(mcServer.getGameType()); } mcServer.setDifficultyForAllWorlds(mcServer.getDifficulty()); }"
Inversion-Mutation
megadiff
"public void setStatement(final PreparedStatement statement) { closeStatement(); LOG.debug("setting new prepared statement"); this.statement = statement; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setStatement"
"public void setStatement(final PreparedStatement statement) { LOG.debug("setting new prepared statement"); <MASK>closeStatement();</MASK> this.statement = statement; }"
Inversion-Mutation
megadiff
"public void run() { InputStream is = null; RandomAccessFile randomAccessFile = null; try { int startPos = downinfo.getCompletesize()*1024; int endPos = downinfo.getFilesize()*1024; is = mService.getPushDownLoadInputStream(downinfo.getUrl(), startPos, endPos); boolean isBreakPoint = mService.getIsBreakPoint(downinfo.getUrl()); randomAccessFile = new RandomAccessFile(file, "rwd"); if(!isBreakPoint) { downinfo.setCompletesize(0); startPos = 0; } // 从断点处 继续下载(初始为0) randomAccessFile.seek(startPos); if (is == null) { return; } final int length = 1024; byte[] b = new byte[length]; int len = -1; int pool = 0; boolean isover = false; long startime = System.currentTimeMillis(); Log.e(TAG, "-----downinfo starttime--->1 " + startime); int tempLen = startPos; callback.downloadUpdate(); while ((len = is.read(b))!=-1) { if (isPause) { return; } randomAccessFile.write(b, 0, len); pool += len; if (pool >= 100 * 1024) { // 100kb写一次数据库 Log.e(TAG, "-----下载 未完成----" + len); PushDownLoadDBHelper.getInstances().update(downinfo); //暂不支持断点下载 pool = 0; callback.downloadUpdate();// 刷新一次 } tempLen += len; downinfo.setCompletesize(tempLen/1024); if (pool != 0) { //PushDownLoadDBHelper.getInstances().update(downinfo);/// 暂不支持断点下载 } } long endtime = System.currentTimeMillis(); Log.e(TAG, "-----downinfo time--->1 " + (endtime - startime)); } catch (Exception e) { //Log.i(TAG, "-------->e " + e); e.printStackTrace(); } finally { // end.countDown(); Log.e(TAG, "---over----"); PushDownLoadDBHelper.getInstances().update(downinfo); if (downinfo.getCompletesize() >= downinfo.getFilesize()) { Log.i(TAG, "----finsh----"); if(callback != null){ callback.downloadSucceed(); } }else{ callback.downloadFailed(); } callback.downloadUpdate(); map.remove(String.valueOf(downinfo.getId())); if (is != null) { try { is.close(); } catch (IOException e) { } } if (randomAccessFile != null) { try { randomAccessFile.close(); } catch (IOException e) { } } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"public void run() { InputStream is = null; RandomAccessFile randomAccessFile = null; try { int startPos = downinfo.getCompletesize()*1024; int endPos = downinfo.getFilesize()*1024; is = mService.getPushDownLoadInputStream(downinfo.getUrl(), startPos, endPos); boolean isBreakPoint = mService.getIsBreakPoint(downinfo.getUrl()); randomAccessFile = new RandomAccessFile(file, "rwd"); if(!isBreakPoint) { downinfo.setCompletesize(0); startPos = 0; } // 从断点处 继续下载(初始为0) randomAccessFile.seek(startPos); if (is == null) { return; } final int length = 1024; byte[] b = new byte[length]; int len = -1; int pool = 0; boolean isover = false; long startime = System.currentTimeMillis(); Log.e(TAG, "-----downinfo starttime--->1 " + startime); int tempLen = startPos; callback.downloadUpdate(); while ((len = is.read(b))!=-1) { if (isPause) { return; } randomAccessFile.write(b, 0, len); pool += len; if (pool >= 100 * 1024) { // 100kb写一次数据库 Log.e(TAG, "-----下载 未完成----" + len); <MASK>PushDownLoadDBHelper.getInstances().update(downinfo);</MASK> //暂不支持断点下载 pool = 0; callback.downloadUpdate();// 刷新一次 } tempLen += len; downinfo.setCompletesize(tempLen/1024); if (pool != 0) { //<MASK>PushDownLoadDBHelper.getInstances().update(downinfo);</MASK>/// 暂不支持断点下载 } } long endtime = System.currentTimeMillis(); Log.e(TAG, "-----downinfo time--->1 " + (endtime - startime)); } catch (Exception e) { //Log.i(TAG, "-------->e " + e); e.printStackTrace(); } finally { // end.countDown(); Log.e(TAG, "---over----"); if (downinfo.getCompletesize() >= downinfo.getFilesize()) { Log.i(TAG, "----finsh----"); <MASK>PushDownLoadDBHelper.getInstances().update(downinfo);</MASK> if(callback != null){ callback.downloadSucceed(); } }else{ callback.downloadFailed(); } callback.downloadUpdate(); map.remove(String.valueOf(downinfo.getId())); if (is != null) { try { is.close(); } catch (IOException e) { } } if (randomAccessFile != null) { try { randomAccessFile.close(); } catch (IOException e) { } } } }"
Inversion-Mutation
megadiff
"private void cameraZoomOut(State toState, boolean animated) { final Resources res = getResources(); final boolean toAllApps = (toState == State.ALL_APPS); final int duration = toAllApps ? res.getInteger(R.integer.config_allAppsZoomInTime) : res.getInteger(R.integer.config_customizeZoomInTime); final float scale = toAllApps ? (float) res.getInteger(R.integer.config_allAppsZoomScaleFactor) : (float) res.getInteger(R.integer.config_customizeZoomScaleFactor); final View toView = toAllApps ? (View) mAllAppsGrid : mHomeCustomizationDrawer; setPivotsForZoom(toView, toState, scale); if (toAllApps) { mWorkspace.shrink(ShrinkState.BOTTOM_HIDDEN, animated); } else { mWorkspace.shrink(ShrinkState.TOP, animated); } if (animated) { ValueAnimator scaleAnim = ObjectAnimator.ofPropertyValuesHolder(toView, PropertyValuesHolder.ofFloat("scaleX", scale, 1.0f), PropertyValuesHolder.ofFloat("scaleY", scale, 1.0f)); scaleAnim.setDuration(duration); if (toAllApps) { toView.setAlpha(0f); ObjectAnimator alphaAnim = ObjectAnimator.ofPropertyValuesHolder(toView, PropertyValuesHolder.ofFloat("alpha", 1.0f)); alphaAnim.setInterpolator(new DecelerateInterpolator(1.5f)); alphaAnim.setDuration(duration); alphaAnim.start(); } scaleAnim.setInterpolator(new Workspace.ZoomOutInterpolator()); scaleAnim.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { // Prepare the position toView.setTranslationX(0.0f); toView.setTranslationY(0.0f); toView.setVisibility(View.VISIBLE); if (!toAllApps) { toView.setAlpha(1.0f); } } @Override public void onAnimationEnd(Animator animation) { // If we don't set the final scale values here, if this animation is cancelled // it will have the wrong scale value and subsequent cameraPan animations will // not fix that toView.setScaleX(1.0f); toView.setScaleY(1.0f); } }); AnimatorSet toolbarHideAnim = new AnimatorSet(); AnimatorSet toolbarShowAnim = new AnimatorSet(); hideAndShowToolbarButtons(toState, toolbarShowAnim, toolbarHideAnim); // toView should appear right at the end of the workspace shrink animation final int startDelay = 0; if (mStateAnimation != null) mStateAnimation.cancel(); mStateAnimation = new AnimatorSet(); mStateAnimation.playTogether(scaleAnim, toolbarHideAnim); mStateAnimation.play(scaleAnim).after(startDelay); // Show the new toolbar buttons just as the main animation is ending final int fadeInTime = res.getInteger(R.integer.config_toolbarButtonFadeInTime); mStateAnimation.play(toolbarShowAnim).after(duration + startDelay - fadeInTime); mStateAnimation.start(); } else { toView.setTranslationX(0.0f); toView.setTranslationY(0.0f); toView.setScaleX(1.0f); toView.setScaleY(1.0f); toView.setVisibility(View.VISIBLE); hideAndShowToolbarButtons(toState, null, null); } mWorkspace.setVerticalWallpaperOffset(toAllApps ? Workspace.WallpaperVerticalOffset.TOP : Workspace.WallpaperVerticalOffset.BOTTOM); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "cameraZoomOut"
"private void cameraZoomOut(State toState, boolean animated) { final Resources res = getResources(); final boolean toAllApps = (toState == State.ALL_APPS); final int duration = toAllApps ? res.getInteger(R.integer.config_allAppsZoomInTime) : res.getInteger(R.integer.config_customizeZoomInTime); final float scale = toAllApps ? (float) res.getInteger(R.integer.config_allAppsZoomScaleFactor) : (float) res.getInteger(R.integer.config_customizeZoomScaleFactor); final View toView = toAllApps ? (View) mAllAppsGrid : mHomeCustomizationDrawer; setPivotsForZoom(toView, toState, scale); if (toAllApps) { mWorkspace.shrink(ShrinkState.BOTTOM_HIDDEN, animated); <MASK>toView.setAlpha(0f);</MASK> } else { mWorkspace.shrink(ShrinkState.TOP, animated); } if (animated) { ValueAnimator scaleAnim = ObjectAnimator.ofPropertyValuesHolder(toView, PropertyValuesHolder.ofFloat("scaleX", scale, 1.0f), PropertyValuesHolder.ofFloat("scaleY", scale, 1.0f)); scaleAnim.setDuration(duration); if (toAllApps) { ObjectAnimator alphaAnim = ObjectAnimator.ofPropertyValuesHolder(toView, PropertyValuesHolder.ofFloat("alpha", 1.0f)); alphaAnim.setInterpolator(new DecelerateInterpolator(1.5f)); alphaAnim.setDuration(duration); alphaAnim.start(); } scaleAnim.setInterpolator(new Workspace.ZoomOutInterpolator()); scaleAnim.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { // Prepare the position toView.setTranslationX(0.0f); toView.setTranslationY(0.0f); toView.setVisibility(View.VISIBLE); if (!toAllApps) { toView.setAlpha(1.0f); } } @Override public void onAnimationEnd(Animator animation) { // If we don't set the final scale values here, if this animation is cancelled // it will have the wrong scale value and subsequent cameraPan animations will // not fix that toView.setScaleX(1.0f); toView.setScaleY(1.0f); } }); AnimatorSet toolbarHideAnim = new AnimatorSet(); AnimatorSet toolbarShowAnim = new AnimatorSet(); hideAndShowToolbarButtons(toState, toolbarShowAnim, toolbarHideAnim); // toView should appear right at the end of the workspace shrink animation final int startDelay = 0; if (mStateAnimation != null) mStateAnimation.cancel(); mStateAnimation = new AnimatorSet(); mStateAnimation.playTogether(scaleAnim, toolbarHideAnim); mStateAnimation.play(scaleAnim).after(startDelay); // Show the new toolbar buttons just as the main animation is ending final int fadeInTime = res.getInteger(R.integer.config_toolbarButtonFadeInTime); mStateAnimation.play(toolbarShowAnim).after(duration + startDelay - fadeInTime); mStateAnimation.start(); } else { toView.setTranslationX(0.0f); toView.setTranslationY(0.0f); toView.setScaleX(1.0f); toView.setScaleY(1.0f); toView.setVisibility(View.VISIBLE); hideAndShowToolbarButtons(toState, null, null); } mWorkspace.setVerticalWallpaperOffset(toAllApps ? Workspace.WallpaperVerticalOffset.TOP : Workspace.WallpaperVerticalOffset.BOTTOM); }"
Inversion-Mutation
megadiff
"public void setBody(Body body) throws MessagingException { this.mBody = body; setHeader("MIME-Version", "1.0"); if (body instanceof com.fsck.k9.mail.Multipart) { com.fsck.k9.mail.Multipart multipart = ((com.fsck.k9.mail.Multipart)body); multipart.setParent(this); setHeader(MimeHeader.HEADER_CONTENT_TYPE, multipart.getContentType()); } else if (body instanceof TextBody) { setHeader(MimeHeader.HEADER_CONTENT_TYPE, String.format("%s;\n charset=utf-8", getMimeType())); setHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, "base64"); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setBody"
"public void setBody(Body body) throws MessagingException { this.mBody = body; if (body instanceof com.fsck.k9.mail.Multipart) { com.fsck.k9.mail.Multipart multipart = ((com.fsck.k9.mail.Multipart)body); multipart.setParent(this); setHeader(MimeHeader.HEADER_CONTENT_TYPE, multipart.getContentType()); <MASK>setHeader("MIME-Version", "1.0");</MASK> } else if (body instanceof TextBody) { setHeader(MimeHeader.HEADER_CONTENT_TYPE, String.format("%s;\n charset=utf-8", getMimeType())); setHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, "base64"); } }"
Inversion-Mutation
megadiff
"@Override public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { getDialog().setTitle(R.string.dialog_add_title); final View view = inflater.inflate(R.layout.dialog_new_download, container, false); editDownloadUrl = (EditText) view.findViewById(R.id.et_add_download); btnOk = (Button) view.findViewById(R.id.b_add_download_ok); btnCancel = (Button) view.findViewById(R.id.b_add_download_cancel); btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { getDialog().dismiss(); } }); btnOk.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { final Intent intent = new Intent(DownloadManagerApplication.getInstance(), DownloaderService.class); intent.putExtra(DownloaderService.INTENT_ACTION, DownloaderService.ACTION_ADD); intent.putExtra(DownloaderService.INTENT_URL, editDownloadUrl.getText().toString()); getActivity().startService(intent); getDialog().dismiss(); DownloadManagerApplication.NEXT++; } }); editDownloadUrl.setText(Constants.DOWNLOADS[DownloadManagerApplication.NEXT % 4]); return view; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCreateView"
"@Override public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { getDialog().setTitle(R.string.dialog_add_title); final View view = inflater.inflate(R.layout.dialog_new_download, container, false); editDownloadUrl = (EditText) view.findViewById(R.id.et_add_download); btnOk = (Button) view.findViewById(R.id.b_add_download_ok); btnCancel = (Button) view.findViewById(R.id.b_add_download_cancel); btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { getDialog().dismiss(); } }); btnOk.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { final Intent intent = new Intent(DownloadManagerApplication.getInstance(), DownloaderService.class); intent.putExtra(DownloaderService.INTENT_ACTION, DownloaderService.ACTION_ADD); intent.putExtra(DownloaderService.INTENT_URL, editDownloadUrl.getText().toString()); getActivity().startService(intent); getDialog().dismiss(); } }); editDownloadUrl.setText(Constants.DOWNLOADS[DownloadManagerApplication.NEXT % 4]); <MASK>DownloadManagerApplication.NEXT++;</MASK> return view; }"
Inversion-Mutation
megadiff
"@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = false) public void onBlockBreakLowest(final BlockBreakEvent event){ checkStack(); if (!stack.isEmpty()){ final Player player = event.getPlayer(); final StackEntry entry = stack.get(stack.size() - 1); if (player.equals(entry.player)) addExemption(entry); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onBlockBreakLowest"
"@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = false) public void onBlockBreakLowest(final BlockBreakEvent event){ if (!stack.isEmpty()){ <MASK>checkStack();</MASK> final Player player = event.getPlayer(); final StackEntry entry = stack.get(stack.size() - 1); if (player.equals(entry.player)) addExemption(entry); } }"
Inversion-Mutation
megadiff
"public String rewriteResourceURL(String path, String resourcebase) { String resourceURL = null; if (!URLUtil.isAbsolute(path) && path.charAt(0) != '/') { if (isContextURL(path)) { resourceURL = rewriteContextURL(path); } else { resourceURL = viewstatehandler.encodeResourceURL(resourcebase + path); } resourceURL = StringUtils.cleanPath(resourceURL); } if (Logger.log.isDebugEnabled()) { Logger.log.debug("getResourceURL returning " + resourceURL + " for path " + path); } return resourceURL; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "rewriteResourceURL"
"public String rewriteResourceURL(String path, String resourcebase) { String resourceURL = null; if (!URLUtil.isAbsolute(path) && path.charAt(0) != '/') { if (isContextURL(path)) { resourceURL = rewriteContextURL(path); } else { resourceURL = viewstatehandler.encodeResourceURL(resourcebase + path); } } <MASK>resourceURL = StringUtils.cleanPath(resourceURL);</MASK> if (Logger.log.isDebugEnabled()) { Logger.log.debug("getResourceURL returning " + resourceURL + " for path " + path); } return resourceURL; }"
Inversion-Mutation
megadiff
"private void localConnections(int netMap[]) { // Exports for (int k = 0; k < numExports; k++) { ImmutableExport e = exports.get(k); int portOffset = portOffsets[k]; Name expNm = e.name; int busWidth = expNm.busWidth(); int drawn = drawns[k]; int drawnOffset = drawnOffsets[drawn]; for (int i = 0; i < busWidth; i++) { ImmutableNetLayout.connectMap(netMap, portOffset + i, drawnOffset + (busWidth == drawnWidths[drawn] ? i : i % drawnWidths[drawn])); GenMath.MutableInteger nn = netNames.get(expNm.subname(i)); ImmutableNetLayout.connectMap(netMap, portOffset + i, netNamesOffset + nn.intValue()); } } // PortInsts for (int k = 0; k < numNodes; k++) { ImmutableNodeInst n = nodes.get(k); if (isIconOfParent(n)) { continue; } // NodeProto np = ni.getProto(); if (n.protoId instanceof PrimitiveNodeId) { // Connect global primitives Global g = globalInst(n); if (g != null) { int drawn = drawns[ni_pi[k]]; ImmutableNetLayout.connectMap(netMap, globals.indexOf(g), drawnOffsets[drawn]); } if (n.protoId == schem.wireConNode.getId()) { connectWireCon(netMap, n); } continue; } IconInst iconInst = iconInsts[k]; if (iconInst == null || iconInst.iconOfParent) { continue; } assert iconInst.nodeInst == n; CellId subCellId = (CellId)n.protoId; assert subCellId.isIcon() || subCellId.isSchematic(); EquivalentSchematicExports iconEq = iconInst.eq; EquivalentSchematicExports schemEq = iconEq.implementation; assert schemEq != null; Name nodeName = n.name; int arraySize = nodeName.busWidth(); int numPorts = getNumPorts(n.protoId); CellBackup subCell = snapshot.getCell(subCellId); for (int m = 0; m < numPorts; m++) { ImmutableExport e = subCell.cellRevision.exports.get(m); Name busExportName = e.name; int busWidth = busExportName.busWidth(); int drawn = drawns[ni_pi[k] + m]; if (drawn < 0) { continue; } int width = drawnWidths[drawn]; if (width != busWidth && width != busWidth * arraySize) { continue; } for (int arrayIndex = 0; arrayIndex < arraySize; arrayIndex++) { int nodeOffset = iconInst.netMapOffset + arrayIndex * iconInst.numExtendedExports; int busOffset = drawnOffsets[drawn]; if (width != busWidth) { busOffset += busWidth * arrayIndex; } for (int j = 0; j < busWidth; j++) { Name exportName = busExportName.subname(j); int portOffset = schemEq.getExportNameMapOffset(exportName); if (portOffset < 0) { continue; } ImmutableNetLayout.connectMap(netMap, busOffset + j, nodeOffset + portOffset); } } } } // Arcs for (int arcIndex = 0; arcIndex < numArcs; arcIndex++) { ImmutableArcInst a = arcs.get(arcIndex); int drawn = drawns[arcsOffset + arcIndex]; if (drawn < 0) { continue; } if (!a.isUsernamed()) { continue; } int busWidth = drawnWidths[drawn]; Name arcNm = a.name; if (arcNm.busWidth() != busWidth) { continue; } int drawnOffset = drawnOffsets[drawn]; for (int i = 0; i < busWidth; i++) { GenMath.MutableInteger nn = netNames.get(arcNm.subname(i)); ImmutableNetLayout.connectMap(netMap, drawnOffset + i, netNamesOffset + nn.intValue()); } } // Globals of proxies for (IconInst iconInst : iconInsts) { if (iconInst == null || iconInst.iconOfParent) { continue; } Set<Global> excludeGlobals = null; if (iconInstExcludeGlobals != null) { excludeGlobals = iconInstExcludeGlobals.get(iconInst); } for (int k = 0; k < iconInst.nodeInst.name.busWidth(); k++) { EquivalentSchematicExports eq = iconInst.eq.implementation; assert eq.implementation == eq; int numGlobals = eq.portOffsets[0]; if (numGlobals == 0) { continue; } int nodableOffset = iconInst.netMapOffset + k * iconInst.numExtendedExports; for (int i = 0; i < numGlobals; i++) { Global g = eq.globals.get(i); if (excludeGlobals != null && excludeGlobals.contains(g)) { continue; } ImmutableNetLayout.connectMap(netMap, this.globals.indexOf(g), nodableOffset + i); } } } ImmutableNetLayout.closureMap(netMap); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "localConnections"
"private void localConnections(int netMap[]) { // Exports for (int k = 0; k < numExports; k++) { ImmutableExport e = exports.get(k); int portOffset = portOffsets[k]; Name expNm = e.name; int busWidth = expNm.busWidth(); int drawn = drawns[k]; int drawnOffset = drawnOffsets[drawn]; for (int i = 0; i < busWidth; i++) { ImmutableNetLayout.connectMap(netMap, portOffset + i, drawnOffset + (busWidth == drawnWidths[drawn] ? i : i % drawnWidths[drawn])); GenMath.MutableInteger nn = netNames.get(expNm.subname(i)); ImmutableNetLayout.connectMap(netMap, portOffset + i, netNamesOffset + nn.intValue()); } } // PortInsts for (int k = 0; k < numNodes; k++) { ImmutableNodeInst n = nodes.get(k); if (isIconOfParent(n)) { continue; } // NodeProto np = ni.getProto(); if (n.protoId instanceof PrimitiveNodeId) { // Connect global primitives Global g = globalInst(n); if (g != null) { int drawn = drawns[ni_pi[k]]; ImmutableNetLayout.connectMap(netMap, globals.indexOf(g), drawnOffsets[drawn]); } if (n.protoId == schem.wireConNode.getId()) { connectWireCon(netMap, n); } continue; } IconInst iconInst = iconInsts[k]; <MASK>assert iconInst.nodeInst == n;</MASK> if (iconInst == null || iconInst.iconOfParent) { continue; } CellId subCellId = (CellId)n.protoId; assert subCellId.isIcon() || subCellId.isSchematic(); EquivalentSchematicExports iconEq = iconInst.eq; EquivalentSchematicExports schemEq = iconEq.implementation; assert schemEq != null; Name nodeName = n.name; int arraySize = nodeName.busWidth(); int numPorts = getNumPorts(n.protoId); CellBackup subCell = snapshot.getCell(subCellId); for (int m = 0; m < numPorts; m++) { ImmutableExport e = subCell.cellRevision.exports.get(m); Name busExportName = e.name; int busWidth = busExportName.busWidth(); int drawn = drawns[ni_pi[k] + m]; if (drawn < 0) { continue; } int width = drawnWidths[drawn]; if (width != busWidth && width != busWidth * arraySize) { continue; } for (int arrayIndex = 0; arrayIndex < arraySize; arrayIndex++) { int nodeOffset = iconInst.netMapOffset + arrayIndex * iconInst.numExtendedExports; int busOffset = drawnOffsets[drawn]; if (width != busWidth) { busOffset += busWidth * arrayIndex; } for (int j = 0; j < busWidth; j++) { Name exportName = busExportName.subname(j); int portOffset = schemEq.getExportNameMapOffset(exportName); if (portOffset < 0) { continue; } ImmutableNetLayout.connectMap(netMap, busOffset + j, nodeOffset + portOffset); } } } } // Arcs for (int arcIndex = 0; arcIndex < numArcs; arcIndex++) { ImmutableArcInst a = arcs.get(arcIndex); int drawn = drawns[arcsOffset + arcIndex]; if (drawn < 0) { continue; } if (!a.isUsernamed()) { continue; } int busWidth = drawnWidths[drawn]; Name arcNm = a.name; if (arcNm.busWidth() != busWidth) { continue; } int drawnOffset = drawnOffsets[drawn]; for (int i = 0; i < busWidth; i++) { GenMath.MutableInteger nn = netNames.get(arcNm.subname(i)); ImmutableNetLayout.connectMap(netMap, drawnOffset + i, netNamesOffset + nn.intValue()); } } // Globals of proxies for (IconInst iconInst : iconInsts) { if (iconInst == null || iconInst.iconOfParent) { continue; } Set<Global> excludeGlobals = null; if (iconInstExcludeGlobals != null) { excludeGlobals = iconInstExcludeGlobals.get(iconInst); } for (int k = 0; k < iconInst.nodeInst.name.busWidth(); k++) { EquivalentSchematicExports eq = iconInst.eq.implementation; assert eq.implementation == eq; int numGlobals = eq.portOffsets[0]; if (numGlobals == 0) { continue; } int nodableOffset = iconInst.netMapOffset + k * iconInst.numExtendedExports; for (int i = 0; i < numGlobals; i++) { Global g = eq.globals.get(i); if (excludeGlobals != null && excludeGlobals.contains(g)) { continue; } ImmutableNetLayout.connectMap(netMap, this.globals.indexOf(g), nodableOffset + i); } } } ImmutableNetLayout.closureMap(netMap); }"
Inversion-Mutation
megadiff
"@Override public void cleanupInstance() throws Exception { Details details = new Details(exhibitor); if ( !details.isValid() ) { return; } // see http://zookeeper.apache.org/doc/r3.3.3/zookeeperAdmin.html#Ongoing+Data+Directory+Cleanup ProcessBuilder builder = new ProcessBuilder ( "java", "-cp", String.format("%s:%s:%s", details.zooKeeperJarPath, details.logPaths, details.configDirectory.getPath()), "org.apache.zookeeper.server.PurgeTxnLog", details.logDirectory.getPath(), details.dataDirectory.getPath(), "-n", Integer.toString(exhibitor.getConfigManager().getConfig().getInt(IntConfigs.CLEANUP_MAX_FILES)) ); exhibitor.getProcessMonitor().monitor(ProcessTypes.CLEANUP, builder.start(), "Cleanup task completed", ProcessMonitor.Mode.DESTROY_ON_INTERRUPT, ProcessMonitor.Streams.ERROR); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "cleanupInstance"
"@Override public void cleanupInstance() throws Exception { Details details = new Details(exhibitor); if ( !details.isValid() ) { return; } // see http://zookeeper.apache.org/doc/r3.3.3/zookeeperAdmin.html#Ongoing+Data+Directory+Cleanup ProcessBuilder builder = new ProcessBuilder ( "java", "-cp", String.format("%s:%s:%s", details.zooKeeperJarPath, details.logPaths, details.configDirectory.getPath()), "org.apache.zookeeper.server.PurgeTxnLog", <MASK>details.dataDirectory.getPath(),</MASK> details.logDirectory.getPath(), "-n", Integer.toString(exhibitor.getConfigManager().getConfig().getInt(IntConfigs.CLEANUP_MAX_FILES)) ); exhibitor.getProcessMonitor().monitor(ProcessTypes.CLEANUP, builder.start(), "Cleanup task completed", ProcessMonitor.Mode.DESTROY_ON_INTERRUPT, ProcessMonitor.Streams.ERROR); }"
Inversion-Mutation
megadiff
"@Override protected void onCreate(Bundle savedInstanceState) { //On Activity Create super.onCreate(savedInstanceState); //Invoke Superclass (Activity)'s onCreate() method. setContentView(R.layout.activity_main); //Set view. Button b = (Button) findViewById(R.id.b); //Basic test button Button m = (Button) findViewById(R.id.m); //Mid test button Button e = (Button) findViewById(R.id.e); //Extreme test button Button s = (Button) findViewById(R.id.stop); //Stop button b.setOnClickListener(new ocl(){ //Set button b listener @Override public void onClick(View v) { new Methods().basic(); //Run test. } }); m.setOnClickListener(new ocl(){ //Set button m listener @Override public void onClick(View v) { new Methods().mid(); //Run test. } }); e.setOnClickListener(new ocl(){ //Set button e listener @Override public void onClick(View v) { new Methods().extreme(); //Run test. } }); s.setOnClickListener(new ocl(){ @Override public void onClick(View v){ //Interrupt all threads ThreadPool.t[0].interrupt(); ThreadPool.t[1].interrupt(); ThreadPool.t[2].interrupt(); ThreadPool.emptyit(0); //Empty all threads } }); }"
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) { //On Activity Create super.onCreate(savedInstanceState); //Invoke Superclass (Activity)'s onCreate() method. setContentView(R.layout.activity_main); //Set view. Button b = (Button) findViewById(R.id.b); //Basic test button Button m = (Button) findViewById(R.id.m); //Mid test button Button e = (Button) findViewById(R.id.e); //Extreme test button Button s = (Button) findViewById(R.id.stop); //Stop button b.setOnClickListener(new ocl(){ //Set button b listener @Override public void onClick(View v) { new Methods().basic(); //Run test. } }); m.setOnClickListener(new ocl(){ //Set button m listener @Override public void onClick(View v) { new Methods().mid(); //Run test. } }); e.setOnClickListener(new ocl(){ //Set button e listener @Override public void onClick(View v) { new Methods().extreme(); //Run test. } }); s.setOnClickListener(new ocl(){ @Override public void onClick(View v){ //Interrupt all threads <MASK>ThreadPool.emptyit(0); //Empty all threads</MASK> ThreadPool.t[0].interrupt(); ThreadPool.t[1].interrupt(); ThreadPool.t[2].interrupt(); } }); }"
Inversion-Mutation
megadiff
"@Override public void onClick(View v){ //Interrupt all threads ThreadPool.t[0].interrupt(); ThreadPool.t[1].interrupt(); ThreadPool.t[2].interrupt(); ThreadPool.emptyit(0); //Empty all threads }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onClick"
"@Override public void onClick(View v){ //Interrupt all threads <MASK>ThreadPool.emptyit(0); //Empty all threads</MASK> ThreadPool.t[0].interrupt(); ThreadPool.t[1].interrupt(); ThreadPool.t[2].interrupt(); }"
Inversion-Mutation
megadiff
"public void onEnable() { instance = this; log = getLogger(); createLists(); SCPlayerListener = new SCPlayerListener(this); pm = Bukkit.getServer().getPluginManager(); pm.registerEvents(SCPluginListener, this); loadConfigurationFile(); loadConfig(config); SCPluginListener.spoutHook(pm); if (SCPluginListener.spout != null) { pm.registerEvents(new SCSpoutScreenListener(this), this); pm.registerEvents(SCPlayerListener, this); } if (keysEnabled) { log.info("Listening to keystrokes while CalcWindow is open enabled"); pm.registerEvents(new SCInputListener(), this); } log.info("Version " + this.getDescription().getVersion() + " enabled."); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onEnable"
"public void onEnable() { instance = this; log = getLogger(); createLists(); SCPlayerListener = new SCPlayerListener(this); pm = Bukkit.getServer().getPluginManager(); <MASK>pm.registerEvents(SCPlayerListener, this);</MASK> pm.registerEvents(SCPluginListener, this); loadConfigurationFile(); loadConfig(config); SCPluginListener.spoutHook(pm); if (SCPluginListener.spout != null) { pm.registerEvents(new SCSpoutScreenListener(this), this); } if (keysEnabled) { log.info("Listening to keystrokes while CalcWindow is open enabled"); pm.registerEvents(new SCInputListener(), this); } log.info("Version " + this.getDescription().getVersion() + " enabled."); }"
Inversion-Mutation
megadiff
"@SuppressWarnings("unchecked") public Configuration(Configuration other) { this.resources = (ArrayList<Resource>) other.resources.clone(); synchronized(other) { if (other.properties != null) { this.properties = (Properties)other.properties.clone(); } if (other.overlay!=null) { this.overlay = (Properties)other.overlay.clone(); } this.updatingResource = new HashMap<String, String[]>(other.updatingResource); this.finalParameters = new HashSet<String>(other.finalParameters); } synchronized(Configuration.class) { REGISTRY.put(this, null); } this.classLoader = other.classLoader; this.loadDefaults = other.loadDefaults; setQuietMode(other.getQuietMode()); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "Configuration"
"@SuppressWarnings("unchecked") public Configuration(Configuration other) { this.resources = (ArrayList<Resource>) other.resources.clone(); synchronized(other) { if (other.properties != null) { this.properties = (Properties)other.properties.clone(); } if (other.overlay!=null) { this.overlay = (Properties)other.overlay.clone(); } this.updatingResource = new HashMap<String, String[]>(other.updatingResource); } <MASK>this.finalParameters = new HashSet<String>(other.finalParameters);</MASK> synchronized(Configuration.class) { REGISTRY.put(this, null); } this.classLoader = other.classLoader; this.loadDefaults = other.loadDefaults; setQuietMode(other.getQuietMode()); }"
Inversion-Mutation
megadiff
"private void check(){ File[] files = _deployDir.listFiles(_fileFilter); // Checking for new deployment directories for (File file : files) { if (checkIsNew(new File(file, "deploy.xml"))) { try { DeploymentUnit du = new DeploymentUnit(file, _pxeServer); du.deploy(false); _inspectedFiles.put(file.getName(), du); __log.info("Deployment of artifact " + file.getName() + " successful."); } catch (Exception e) { __log.error("Deployment of " + file.getName() + " failed, aborting for now.", e); } } } // Removing deployments that disappeared HashSet<String> removed = new HashSet<String>(); for (String duName : _inspectedFiles.keySet()) { DeploymentUnit du = _inspectedFiles.get(duName); if (!du.exists()) { du.undeploy(); removed.add(duName); } } if (removed.size() > 0) { for (String duName : removed) { _inspectedFiles.remove(duName); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "check"
"private void check(){ File[] files = _deployDir.listFiles(_fileFilter); // Checking for new deployment directories for (File file : files) { if (checkIsNew(new File(file, "deploy.xml"))) { try { DeploymentUnit du = new DeploymentUnit(file, _pxeServer); <MASK>_inspectedFiles.put(file.getName(), du);</MASK> du.deploy(false); __log.info("Deployment of artifact " + file.getName() + " successful."); } catch (Exception e) { __log.error("Deployment of " + file.getName() + " failed, aborting for now.", e); } } } // Removing deployments that disappeared HashSet<String> removed = new HashSet<String>(); for (String duName : _inspectedFiles.keySet()) { DeploymentUnit du = _inspectedFiles.get(duName); if (!du.exists()) { du.undeploy(); removed.add(duName); } } if (removed.size() > 0) { for (String duName : removed) { _inspectedFiles.remove(duName); } } }"
Inversion-Mutation
megadiff
"@Override public void encodeEnd(FacesContext facesContext, UIComponent component) throws IOException { Components.generateIdIfNotSpecified(component); ResponseWriter writer = facesContext.getResponseWriter(); Chart chart = (Chart) component; ChartView view = chart.getChartView(); if (!chart.isRendered() || view == null) return; writer.startElement("div", chart); writeIdAttribute(facesContext, chart); Rendering.writeComponentClassAttribute(writer, chart); writer.writeAttribute("style", "width: " + chart.getWidth() + "px;" + " height:" + chart.getHeight() + "px;", "style"); String actionFiledId = chart.getClientId(facesContext) + MapRenderUtilities.ACTION_FIELD_SUFFIX; Rendering.writeNewLine(writer); Rendering.renderHiddenField(writer, actionFiledId, null); Rendering.writeNewLine(writer); final byte[] imageAsByteArray = view.renderAsImageFile(); final JfcRenderHints renderHints = chart.getRenderHints(); final ChartRenderingInfo renderingInfo = renderHints.getRenderingInfo(); String mapId = renderHints.getMapId(chart); String map = MapRenderUtilities.getImageMapExt(chart, mapId, renderingInfo, new StandardToolTipTagFragmentGenerator(), new StandardURLTagFragmentGenerator()); renderHints.setMap(map); if (view.getChartPopup() != null) { encodeChartPopup(facesContext, chart, view, renderingInfo); } chart.setImageBytes(imageAsByteArray); DynamicImage dynamicImage = new DynamicImage(); ValueExpression ve = new ValueExpression() { public Object getValue(ELContext elContext) { return imageAsByteArray; } public void setValue(ELContext elContext, Object value) { throw new UnsupportedOperationException("Could not change 'data' property using ValueExpression"); } public boolean isReadOnly(ELContext elContext) { return true; } public Class getType(ELContext elContext) { if (imageAsByteArray == null) return Object.class; return imageAsByteArray.getClass(); } public Class getExpectedType() { return Object.class; } public String getExpressionString() { return null; } public boolean equals(Object o) { return false; } public int hashCode() { return 0; } public boolean isLiteralText() { return false; } }; dynamicImage.setValueExpression("data", ve); dynamicImage.setId("img"); dynamicImage.setParent(chart); dynamicImage.setMapId(mapId); dynamicImage.setMap(map); dynamicImage.getAttributes().put(DynamicImageRenderer.DEFAULT_STYLE_ATTR, "o_chart"); dynamicImage.setWidth(chart.getWidth()); dynamicImage.setHeight(chart.getHeight()); copyAttributes(dynamicImage, chart, "onclick", "ondblclick", "onmousedown", "onmouseup", "onmousemove", "onmouseover", "onmouseout"); dynamicImage.setImageType(ImageType.PNG); dynamicImage.encodeAll(facesContext); if (map != null) { Resources.renderJSLinkIfNeeded(facesContext, Resources.getUtilJsURL(facesContext)); Resources.renderJSLinkIfNeeded(facesContext, Resources.getInternalURL(facesContext, "chart/chartPopup.js")); } encodeScripts(facesContext, chart, dynamicImage); writer.endElement("div"); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "encodeEnd"
"@Override public void encodeEnd(FacesContext facesContext, UIComponent component) throws IOException { Components.generateIdIfNotSpecified(component); ResponseWriter writer = facesContext.getResponseWriter(); Chart chart = (Chart) component; ChartView view = chart.getChartView(); if (!chart.isRendered() || view == null) return; writer.startElement("div", chart); writeIdAttribute(facesContext, chart); Rendering.writeComponentClassAttribute(writer, chart); writer.writeAttribute("style", "width: " + chart.getWidth() + "px;" + " height:" + chart.getHeight() + "px;", "style"); String actionFiledId = chart.getClientId(facesContext) + MapRenderUtilities.ACTION_FIELD_SUFFIX; Rendering.writeNewLine(writer); Rendering.renderHiddenField(writer, actionFiledId, null); Rendering.writeNewLine(writer); final byte[] imageAsByteArray = view.renderAsImageFile(); final JfcRenderHints renderHints = chart.getRenderHints(); final ChartRenderingInfo renderingInfo = renderHints.getRenderingInfo(); String mapId = renderHints.getMapId(chart); String map = MapRenderUtilities.getImageMapExt(chart, mapId, renderingInfo, new StandardToolTipTagFragmentGenerator(), new StandardURLTagFragmentGenerator()); renderHints.setMap(map); if (view.getChartPopup() != null) { encodeChartPopup(facesContext, chart, view, renderingInfo); } chart.setImageBytes(imageAsByteArray); DynamicImage dynamicImage = new DynamicImage(); ValueExpression ve = new ValueExpression() { public Object getValue(ELContext elContext) { return imageAsByteArray; } public void setValue(ELContext elContext, Object value) { throw new UnsupportedOperationException("Could not change 'data' property using ValueExpression"); } public boolean isReadOnly(ELContext elContext) { return true; } public Class getType(ELContext elContext) { if (imageAsByteArray == null) return Object.class; return imageAsByteArray.getClass(); } public Class getExpectedType() { return Object.class; } public String getExpressionString() { return null; } public boolean equals(Object o) { return false; } public int hashCode() { return 0; } public boolean isLiteralText() { return false; } }; dynamicImage.setValueExpression("data", ve); dynamicImage.setId("img"); dynamicImage.setParent(chart); dynamicImage.setMapId(mapId); dynamicImage.setMap(map); dynamicImage.getAttributes().put(DynamicImageRenderer.DEFAULT_STYLE_ATTR, "o_chart"); dynamicImage.setWidth(chart.getWidth()); dynamicImage.setHeight(chart.getHeight()); copyAttributes(dynamicImage, chart, "onclick", "ondblclick", "onmousedown", "onmouseup", "onmousemove", "onmouseover", "onmouseout"); dynamicImage.setImageType(ImageType.PNG); dynamicImage.encodeAll(facesContext); if (map != null) { Resources.renderJSLinkIfNeeded(facesContext, Resources.getUtilJsURL(facesContext)); Resources.renderJSLinkIfNeeded(facesContext, Resources.getInternalURL(facesContext, "chart/chartPopup.js")); } <MASK>writer.endElement("div");</MASK> encodeScripts(facesContext, chart, dynamicImage); }"
Inversion-Mutation
megadiff
"public Iterable<AnnotatedToken> annotated() { return new Iterable<AnnotatedToken>() { public Iterator<AnnotatedToken> iterator() { final PeekingIterator<Behavior> starting = peekingIterator(CompareLow.sortedCopy(behaviors).iterator()); final PeekingIterator<Behavior> ending = peekingIterator(CompareHigh.sortedCopy(behaviors).iterator()); return new AbstractIterator<AnnotatedToken>() { int n = 0; protected AnnotatedToken computeNext() { if (n > tokens.size()) return endOfData(); Token t = (n==tokens.size()) ? null : tokens.get(n); List<Behavior> tStarting = Lists.newArrayList(); while (starting.hasNext() && starting.peek().low()<=n) tStarting.add(starting.next()); List<Behavior> tEnding = Lists.newArrayList(); while (ending.hasNext() && ending.peek().high()<=n) tEnding.add(ending.next()); n++; return new AnnotatedToken(t, tStarting, tEnding); } }; } }; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "annotated"
"public Iterable<AnnotatedToken> annotated() { return new Iterable<AnnotatedToken>() { public Iterator<AnnotatedToken> iterator() { final PeekingIterator<Behavior> starting = peekingIterator(CompareLow.sortedCopy(behaviors).iterator()); final PeekingIterator<Behavior> ending = peekingIterator(CompareHigh.sortedCopy(behaviors).iterator()); return new AbstractIterator<AnnotatedToken>() { int n = 0; protected AnnotatedToken computeNext() { if (n > tokens.size()) return endOfData(); Token t = (n==tokens.size()) ? null : tokens.get(n); <MASK>n++;</MASK> List<Behavior> tStarting = Lists.newArrayList(); while (starting.hasNext() && starting.peek().low()<=n) tStarting.add(starting.next()); List<Behavior> tEnding = Lists.newArrayList(); while (ending.hasNext() && ending.peek().high()<=n) tEnding.add(ending.next()); return new AnnotatedToken(t, tStarting, tEnding); } }; } }; }"
Inversion-Mutation
megadiff
"public Iterator<AnnotatedToken> iterator() { final PeekingIterator<Behavior> starting = peekingIterator(CompareLow.sortedCopy(behaviors).iterator()); final PeekingIterator<Behavior> ending = peekingIterator(CompareHigh.sortedCopy(behaviors).iterator()); return new AbstractIterator<AnnotatedToken>() { int n = 0; protected AnnotatedToken computeNext() { if (n > tokens.size()) return endOfData(); Token t = (n==tokens.size()) ? null : tokens.get(n); List<Behavior> tStarting = Lists.newArrayList(); while (starting.hasNext() && starting.peek().low()<=n) tStarting.add(starting.next()); List<Behavior> tEnding = Lists.newArrayList(); while (ending.hasNext() && ending.peek().high()<=n) tEnding.add(ending.next()); n++; return new AnnotatedToken(t, tStarting, tEnding); } }; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "iterator"
"public Iterator<AnnotatedToken> iterator() { final PeekingIterator<Behavior> starting = peekingIterator(CompareLow.sortedCopy(behaviors).iterator()); final PeekingIterator<Behavior> ending = peekingIterator(CompareHigh.sortedCopy(behaviors).iterator()); return new AbstractIterator<AnnotatedToken>() { int n = 0; protected AnnotatedToken computeNext() { if (n > tokens.size()) return endOfData(); Token t = (n==tokens.size()) ? null : tokens.get(n); <MASK>n++;</MASK> List<Behavior> tStarting = Lists.newArrayList(); while (starting.hasNext() && starting.peek().low()<=n) tStarting.add(starting.next()); List<Behavior> tEnding = Lists.newArrayList(); while (ending.hasNext() && ending.peek().high()<=n) tEnding.add(ending.next()); return new AnnotatedToken(t, tStarting, tEnding); } }; }"
Inversion-Mutation
megadiff
"protected AnnotatedToken computeNext() { if (n > tokens.size()) return endOfData(); Token t = (n==tokens.size()) ? null : tokens.get(n); List<Behavior> tStarting = Lists.newArrayList(); while (starting.hasNext() && starting.peek().low()<=n) tStarting.add(starting.next()); List<Behavior> tEnding = Lists.newArrayList(); while (ending.hasNext() && ending.peek().high()<=n) tEnding.add(ending.next()); n++; return new AnnotatedToken(t, tStarting, tEnding); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "computeNext"
"protected AnnotatedToken computeNext() { if (n > tokens.size()) return endOfData(); Token t = (n==tokens.size()) ? null : tokens.get(n); <MASK>n++;</MASK> List<Behavior> tStarting = Lists.newArrayList(); while (starting.hasNext() && starting.peek().low()<=n) tStarting.add(starting.next()); List<Behavior> tEnding = Lists.newArrayList(); while (ending.hasNext() && ending.peek().high()<=n) tEnding.add(ending.next()); return new AnnotatedToken(t, tStarting, tEnding); }"
Inversion-Mutation
megadiff
"private DocumentModel createCommentDocModel(DocumentModel docModel, DocumentModel comment) throws ClientException { updateAuthor(docModel, comment); String[] pathList = getCommentPathList(comment); String domainPath = docModel.getPath().segment(0); CoreSession mySession = getRepositorySession(docModel.getRepositoryName()); if (mySession == null) { return null; } // TODO GR upgrade this code. It can't work if current user // doesn't have admin rights DocumentModel parent = mySession.getDocument(new PathRef(domainPath)); for (String name : pathList) { String pathStr = parent.getPathAsString(); DocumentRef ref = new PathRef(pathStr, name); if (mySession.exists(ref)) { parent = mySession.getDocument(ref); } else { DocumentModel dm = mySession.createDocumentModel(pathStr, name, "HiddenFolder"); dm.setProperty("dublincore", "title", name); dm.setProperty("dublincore", "description", ""); dm.setProperty("dublincore", "created", Calendar.getInstance()); dm = mySession.createDocument(dm); setFolderPermissions(dm); mySession.save(); parent = dm; } } String pathStr = parent.getPathAsString(); String commentName = getCommentName(docModel, comment); CommentConverter converter = config.getCommentConverter(); DocumentModel commentDocModel = mySession.createDocumentModel(pathStr, IdUtils.generateId(commentName), comment.getType()); converter.updateDocumentModel(commentDocModel, comment); commentDocModel.setProperty("dublincore", "title", commentName); commentDocModel = mySession.createDocument(commentDocModel); setCommentPermissions(commentDocModel); log.debug("created comment with id=" + commentDocModel.getId()); mySession.save(); return commentDocModel; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createCommentDocModel"
"private DocumentModel createCommentDocModel(DocumentModel docModel, DocumentModel comment) throws ClientException { updateAuthor(docModel, comment); String[] pathList = getCommentPathList(comment); String domainPath = docModel.getPath().segment(0); CoreSession mySession = getRepositorySession(docModel.getRepositoryName()); if (mySession == null) { return null; } // TODO GR upgrade this code. It can't work if current user // doesn't have admin rights DocumentModel parent = mySession.getDocument(new PathRef(domainPath)); for (String name : pathList) { String pathStr = parent.getPathAsString(); DocumentRef ref = new PathRef(pathStr, name); if (mySession.exists(ref)) { parent = mySession.getDocument(ref); } else { DocumentModel dm = mySession.createDocumentModel(pathStr, name, "HiddenFolder"); dm.setProperty("dublincore", "title", name); dm.setProperty("dublincore", "description", ""); dm.setProperty("dublincore", "created", Calendar.getInstance()); <MASK>setFolderPermissions(dm);</MASK> dm = mySession.createDocument(dm); mySession.save(); parent = dm; } } String pathStr = parent.getPathAsString(); String commentName = getCommentName(docModel, comment); CommentConverter converter = config.getCommentConverter(); DocumentModel commentDocModel = mySession.createDocumentModel(pathStr, IdUtils.generateId(commentName), comment.getType()); converter.updateDocumentModel(commentDocModel, comment); commentDocModel.setProperty("dublincore", "title", commentName); commentDocModel = mySession.createDocument(commentDocModel); setCommentPermissions(commentDocModel); log.debug("created comment with id=" + commentDocModel.getId()); mySession.save(); return commentDocModel; }"
Inversion-Mutation
megadiff
"@BeforeClass public static void setUpClass() throws BridgeDBException, VoidValidatorException { ConfigReader.useTest(); TestSqlFactory.checkSQLAccess(); uriListener = SQLUriMapper.createNew(); instance = new Loader(); reader = RdfFactory.getTestFilebase(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setUpClass"
"@BeforeClass public static void setUpClass() throws BridgeDBException, VoidValidatorException { ConfigReader.useTest(); TestSqlFactory.checkSQLAccess(); <MASK>instance = new Loader();</MASK> uriListener = SQLUriMapper.createNew(); reader = RdfFactory.getTestFilebase(); }"
Inversion-Mutation
megadiff
"@MotechListener(subjects = {MESSAGE_CAMPAIGN_FIRED_EVENT_SUBJECT}) public void sendProgramMessage(MotechEvent event) { try { Map params = event.getParameters(); String patientId = (String) params.get(EventKeys.EXTERNAL_ID_KEY); LocalDate campaignStartDate = (LocalDate) params.get(EventKeys.CAMPAIGN_START_DATE); String repeatInterval = (String) params.get(EventKeys.CAMPAIGN_REPEAT_INTERVAL); MobileMidwifeEnrollment enrollment = mobileMidwifeService.findActiveBy(patientId); Integer startWeek = Integer.parseInt(enrollment.messageStartWeekSpecificToServiceType()); String campaignName = ((String) params.get(EventKeys.CAMPAIGN_NAME_KEY)); String messageKey = mobileMidwifeWeekCalculator.getMessageKey(campaignName, campaignStartDate, startWeek, repeatInterval); if (messageKey != null) { sendMessage(enrollment, messageKey); if (mobileMidwifeWeekCalculator.hasProgramEnded(campaignName, messageKey)) { if (enrollment.getServiceType().equals(ServiceType.PREGNANCY)) mobileMidwifeService.rollover(patientId, DateUtil.now().plusWeeks(1)); else mobileMidwifeService.unRegister(patientId); } } } catch (Exception e) { logger.error("<MobileMidwifeEvent>: Encountered error while sending alert for patientId " + event.getParameters().get(EventKeys.EXTERNAL_ID_KEY) + ": ", e); throw new EventHandlerException(event, e); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "sendProgramMessage"
"@MotechListener(subjects = {MESSAGE_CAMPAIGN_FIRED_EVENT_SUBJECT}) public void sendProgramMessage(MotechEvent event) { try { Map params = event.getParameters(); String patientId = (String) params.get(EventKeys.EXTERNAL_ID_KEY); LocalDate campaignStartDate = (LocalDate) params.get(EventKeys.CAMPAIGN_START_DATE); String repeatInterval = (String) params.get(EventKeys.CAMPAIGN_REPEAT_INTERVAL); MobileMidwifeEnrollment enrollment = mobileMidwifeService.findActiveBy(patientId); Integer startWeek = Integer.parseInt(enrollment.messageStartWeekSpecificToServiceType()); String campaignName = ((String) params.get(EventKeys.CAMPAIGN_NAME_KEY)); String messageKey = mobileMidwifeWeekCalculator.getMessageKey(campaignName, campaignStartDate, startWeek, repeatInterval); if (messageKey != null) { if (mobileMidwifeWeekCalculator.hasProgramEnded(campaignName, messageKey)) { if (enrollment.getServiceType().equals(ServiceType.PREGNANCY)) mobileMidwifeService.rollover(patientId, DateUtil.now().plusWeeks(1)); else mobileMidwifeService.unRegister(patientId); } <MASK>sendMessage(enrollment, messageKey);</MASK> } } catch (Exception e) { logger.error("<MobileMidwifeEvent>: Encountered error while sending alert for patientId " + event.getParameters().get(EventKeys.EXTERNAL_ID_KEY) + ": ", e); throw new EventHandlerException(event, e); } }"
Inversion-Mutation
megadiff
"private Optional<FileInfo> getNextFile() { /* Filter to exclude finished or hidden files */ FileFilter filter = new FileFilter() { public boolean accept(File candidate) { String fileName = candidate.getName(); if ((candidate.isDirectory()) || (fileName.endsWith(completedSuffix)) || (fileName.startsWith(".")) || ignorePattern.matcher(fileName).matches()) { return false; } return true; } }; List<File> candidateFiles = Arrays.asList(spoolDirectory.listFiles(filter)); if (candidateFiles.isEmpty()) { return Optional.absent(); } else { Collections.sort(candidateFiles, new Comparator<File>() { public int compare(File a, File b) { int timeComparison = new Long(a.lastModified()).compareTo( new Long(b.lastModified())); if (timeComparison != 0) { return timeComparison; } else { return a.getName().compareTo(b.getName()); } } }); File nextFile = candidateFiles.get(0); try { // roll the meta file, if needed String nextPath = nextFile.getPath(); PositionTracker tracker = DurablePositionTracker.getInstance(metaFile, nextPath); if (!tracker.getTarget().equals(nextPath)) { tracker.close(); deleteMetaFile(); tracker = DurablePositionTracker.getInstance(metaFile, nextPath); } // sanity check Preconditions.checkState(tracker.getTarget().equals(nextPath), "Tracker target %s does not equal expected filename %s", tracker.getTarget(), nextPath); ResettableInputStream in = new ResettableFileInputStream(nextFile, tracker, ResettableFileInputStream.DEFAULT_BUF_SIZE, inputCharset); EventDeserializer deserializer = EventDeserializerFactory.getInstance (deserializerType, deserializerContext, in); return Optional.of(new FileInfo(nextFile, deserializer)); } catch (FileNotFoundException e) { // File could have been deleted in the interim logger.warn("Could not find file: " + nextFile, e); return Optional.absent(); } catch (IOException e) { logger.error("Exception opening file: " + nextFile, e); return Optional.absent(); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getNextFile"
"private Optional<FileInfo> getNextFile() { /* Filter to exclude finished or hidden files */ FileFilter filter = new FileFilter() { public boolean accept(File candidate) { String fileName = candidate.getName(); if ((candidate.isDirectory()) || (fileName.endsWith(completedSuffix)) || (fileName.startsWith(".")) || ignorePattern.matcher(fileName).matches()) { return false; } return true; } }; List<File> candidateFiles = Arrays.asList(spoolDirectory.listFiles(filter)); if (candidateFiles.isEmpty()) { return Optional.absent(); } else { Collections.sort(candidateFiles, new Comparator<File>() { public int compare(File a, File b) { int timeComparison = new Long(a.lastModified()).compareTo( new Long(b.lastModified())); if (timeComparison != 0) { return timeComparison; } else { return a.getName().compareTo(b.getName()); } } }); File nextFile = candidateFiles.get(0); try { // roll the meta file, if needed String nextPath = nextFile.getPath(); PositionTracker tracker = DurablePositionTracker.getInstance(metaFile, nextPath); if (!tracker.getTarget().equals(nextPath)) { tracker.close(); deleteMetaFile(); } <MASK>tracker = DurablePositionTracker.getInstance(metaFile, nextPath);</MASK> // sanity check Preconditions.checkState(tracker.getTarget().equals(nextPath), "Tracker target %s does not equal expected filename %s", tracker.getTarget(), nextPath); ResettableInputStream in = new ResettableFileInputStream(nextFile, tracker, ResettableFileInputStream.DEFAULT_BUF_SIZE, inputCharset); EventDeserializer deserializer = EventDeserializerFactory.getInstance (deserializerType, deserializerContext, in); return Optional.of(new FileInfo(nextFile, deserializer)); } catch (FileNotFoundException e) { // File could have been deleted in the interim logger.warn("Could not find file: " + nextFile, e); return Optional.absent(); } catch (IOException e) { logger.error("Exception opening file: " + nextFile, e); return Optional.absent(); } } }"
Inversion-Mutation
megadiff
"private RestResponse convertLocaleToResponse( List<SurveyedLocale> localeList, Boolean needDetailsFlag, String cursor, String oldCursor, String display) { PlacemarkRestResponse resp = new PlacemarkRestResponse(); if (needDetailsFlag == null) { needDetailsFlag = true; } if (localeList != null) { List<PlacemarkDto> dtoList = new ArrayList<PlacemarkDto>(); for (SurveyedLocale ap : localeList) { dtoList.add(marshallDomainToDto(ap, needDetailsFlag, display)); } resp.setPlacemarks(dtoList); } if (cursor != null) { if (oldCursor == null || !cursor.equals(oldCursor)) { resp.setCursor(cursor); } } else { resp.setCursor(null); } return resp; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "convertLocaleToResponse"
"private RestResponse convertLocaleToResponse( List<SurveyedLocale> localeList, Boolean needDetailsFlag, String cursor, String oldCursor, String display) { PlacemarkRestResponse resp = new PlacemarkRestResponse(); if (needDetailsFlag == null) { needDetailsFlag = true; } if (localeList != null) { List<PlacemarkDto> dtoList = new ArrayList<PlacemarkDto>(); for (SurveyedLocale ap : localeList) { dtoList.add(marshallDomainToDto(ap, needDetailsFlag, display)); <MASK>resp.setPlacemarks(dtoList);</MASK> } } if (cursor != null) { if (oldCursor == null || !cursor.equals(oldCursor)) { resp.setCursor(cursor); } } else { resp.setCursor(null); } return resp; }"
Inversion-Mutation
megadiff
"private CommandBar createInteractionsToolBar() { final CommandBar toolBar = createToolBar(INTERACTIONS_TOOL_BAR_ID, "Interactions"); addCommandsToToolBar(toolBar, new String[]{ // These IDs are defined in the module.xml "selectTool", // todo - reactivate range-finder (nf) // "rangeFinder", "zoomTool", "pannerTool", "pinTool", "gcpTool", "drawLineTool", "drawPolylineTool", "drawRectangleTool", "drawEllipseTool", "drawPolygonTool", // todo - activate magic stick (nf) // "magicStickTool", "createVectorDataNode", null, }); return toolBar; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createInteractionsToolBar"
"private CommandBar createInteractionsToolBar() { final CommandBar toolBar = createToolBar(INTERACTIONS_TOOL_BAR_ID, "Interactions"); addCommandsToToolBar(toolBar, new String[]{ // These IDs are defined in the module.xml "selectTool", // todo - reactivate range-finder (nf) // "rangeFinder", "zoomTool", "pannerTool", "pinTool", "gcpTool", "drawLineTool", "drawRectangleTool", "drawEllipseTool", <MASK>"drawPolylineTool",</MASK> "drawPolygonTool", // todo - activate magic stick (nf) // "magicStickTool", "createVectorDataNode", null, }); return toolBar; }"
Inversion-Mutation
megadiff
"private static void updateIO(File f, Stint s){ try { PrintWriter pw=new PrintWriter(f); Scanner sc=new Scanner(f); scanners.put(s.toString(),sc); printers.put(s.toString(),pw); } catch (FileNotFoundException e) { e.printStackTrace(); exception("Stint: IO Exception"); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "updateIO"
"private static void updateIO(File f, Stint s){ try { <MASK>Scanner sc=new Scanner(f);</MASK> PrintWriter pw=new PrintWriter(f); scanners.put(s.toString(),sc); printers.put(s.toString(),pw); } catch (FileNotFoundException e) { e.printStackTrace(); exception("Stint: IO Exception"); } }"
Inversion-Mutation
megadiff
"public static String membersListMessage(Collection<BaseGuildMemberType> members){ StringBuilder sb = new StringBuilder(4 + 15 * members.size()).append("gIM+"); boolean first = true; for (BaseGuildMemberType member : members) { if (first) first = false; else sb.append('|'); sb.append(member.getId()).append(';'); sb.append(member.getName()).append(';'); sb.append(member.getLevel()).append(';'); sb.append(member.getSkin()).append(';'); sb.append(member.getRank().value()).append(';'); sb.append(member.getExperienceGiven()).append(';'); sb.append(member.getExperienceRate()).append(';'); sb.append(member.getRights()).append(';'); sb.append(member.isOnline() ? '1' : '0').append(';'); sb.append(member.getAlignment()).append(';'); sb.append(member.isOnline() ? 0 : new Duration(member.getLastConnection(), DateTime.now()).getStandardHours()); } return sb.toString(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "membersListMessage"
"public static String membersListMessage(Collection<BaseGuildMemberType> members){ StringBuilder sb = new StringBuilder(4 + 15 * members.size()).append("gIM+"); boolean first = true; for (BaseGuildMemberType member : members) { if (first) first = false; else sb.append('|'); sb.append(member.getId()).append(';'); sb.append(member.getName()).append(';'); sb.append(member.getLevel()).append(';'); sb.append(member.getSkin()).append(';'); sb.append(member.getRank().value()).append(';'); <MASK>sb.append(member.getExperienceRate()).append(';');</MASK> sb.append(member.getExperienceGiven()).append(';'); sb.append(member.getRights()).append(';'); sb.append(member.isOnline() ? '1' : '0').append(';'); sb.append(member.getAlignment()).append(';'); sb.append(member.isOnline() ? 0 : new Duration(member.getLastConnection(), DateTime.now()).getStandardHours()); } return sb.toString(); }"
Inversion-Mutation
megadiff
"protected String normalizeValue(String key, String value) throws PgkbException { boolean valid = true; String normalizedValue; ExtendedEnum enumValue; if (IcpcUtils.isBlank(value)) { return IcpcUtils.NA; } String strippedValue = StringUtils.stripToNull(value); normalizedValue = strippedValue; switch (key) { // subject ID column is special case "Subject_ID": valid = (strippedValue.startsWith("PA") && strippedValue.length()>2); break; // columns that must be integers case "Project": Integer.valueOf(strippedValue); break; // enum columns case "Alcohol": enumValue = AlcoholStatus.lookupByName(strippedValue); if (enumValue != null) { if (enumValue==AlcoholStatus.UNKNOWN) { normalizedValue = IcpcUtils.NA; } else { normalizedValue = enumValue.getShortName(); } } else { valid = false; } break; case "Diabetes": enumValue = DiabetesStatus.lookupByName(strippedValue); if (enumValue != null) { if (enumValue == DiabetesStatus.UNKNOWN) { normalizedValue = IcpcUtils.NA; } else { normalizedValue = enumValue.getShortName(); } } else { valid = false; } break; case "Gender": enumValue = Gender.lookupByName(strippedValue); if (enumValue != null) { normalizedValue = enumValue.getShortName(); } else { valid = false; } break; case "Sample_Source": List<String> normalizedTokens = Lists.newArrayList(); for (String token : Splitter.on(";").split(strippedValue)) { SampleSource source = SampleSource.lookupByName(StringUtils.strip(token)); if (source!=null) { normalizedTokens.add(source.getShortName()); } else { valid = valid && (source!=null); } normalizedValue = Joiner.on(";").join(normalizedTokens); } break; case "PPI_Name": enumValue = DrugPpi.lookupByName(strippedValue); if (enumValue != null) { normalizedValue = enumValue.getShortName(); } else { valid = false; } break; // columns that must be floats case "Age": case "Height": case "Weight": case "BMI": case "Diastolic_BP_Max": case "Diastolic_BP_Median": case "Systolic_BP_Max": case "Systolic_BP_Median": case "CRP": case "BUN": case "Left_Ventricle": case "Right_Ventricle": case "Dose_Clopidogrel_aspirin": case "Duration_Clopidogrel": case "Duration_Aspirin": case "Duration_therapy": case "Active_metabolite": case "Days_MajorBleeding": case "Days_MinorBleeding": case "Num_bleeding": case "PFA_mean_EPI_Collagen_closure_Baseline": case "PFA_mean_ADP_Collagen_closure_Baseline": case "PFA_mean_EPI_Collagen_closure_Post": case "PFA_mean_ADP_Collagen_closure_Post": case "PFA_mean_EPI_Collagen_closure_Standard": case "PFA_mean_ADP_Collagen_closure_Standard": case "Verify_Now_baseline_Base": case "Verify_Now_baseline_PRU": case "Verify_Now_baseline_percentinhibition": case "Verify_Now_post_Base": case "Verify_Now_post_PRU": case "Verify_Now_post_percentinhibition": case "Verify_Now_on_clopidogrel_Base": case "Verify_Now_on_clopidogrel_PRU": case "Verify_Now_on_clopidogrel_percentinhibition": case "PAP_8_baseline_max_ADP_2 ": case "PAP_8_baseline_max_ADP_5": case "PAP_8_baseline_max_ADP_10": case "PAP_8_baseline_max_ADP_20": case "PAP_8_baseline_max_collagen_1": case "PAP_8_baseline_max_collagen_2": case "PAP_8_baseline_max_collagen_10": case "PAP_8_baseline_max_collagen_6": case "PAP_8_baseline_max_epi": case "PAP_8_baseline_max_aa": case "PAP_8_baseline_lag_collagen_1": case "PAP_8_baseline_lag_collagen_2": case "PAP_8_baseline_lag_collagen_5": case "PAP_8_baseline_lag_collagen_10": case "PAP_8_post_max_ADP_2 ": case "PAP_8_post_max_ADP_5": case "PAP_8_post_max_ADP_10": case "PAP_8_post_max_ADP_20": case "PAP_8_post_max_collagen_1": case "PAP_8_post_max_collagen_2": case "PAP_8_post_max_collagen_5": case "PAP_8_post_max_collagen_10": case "PAP_8_post_max_epi_perc": case "PAP_8_post_max_aa_perc": case "PAP_8_post_lag_collagen_1": case "PAP_8_post_lag_collagen_2": case "PAP_8_post_lag_collagen_5": case "PAP_8_post_lag_collagen_10": case "PAP_8_standard_max_ADP_2": case "PAP_8_standard_max_ADP_5": case "PAP_8_standard_max_ADP_10": case "PAP_8_standard_max_ADP_20": case "PAP_8_standard_max_collagen_1": case "PAP_8_standard_max_collagen_2": case "PAP_8_standard_max_collagen_5": case "PAP_8_standard_max_collagen_10": case "PAP_8_standard_max_epi_pct": case "PAP_8_standard_max_aa_pct": case "PAP_8_standard_lag_collagen_1": case "PAP_8_standard_lag_collagen_2": case "5PAP_8_standard_lag_collagen_5": case "PAP_8_standard_lag_collagen_10": case "Chronolog_baseline_max_ADP_5": case "Chronolog_baseline_max_ADP_20": case "Chronolog_baseline_max_aa": case "Chronolog_baseline_max_collagen1": case "Chronolog_baseline_lag_ADP_5": case "Chronolog_baseline_lag_ADP_20": case "Chronolog_baseline_lag_aa": case "Chronolog_baseline_lag_collagen1": case "Chronolog_loading_max_ADP_5": case "Chronolog_loading_max_ADP_20": case "Chronolog_loading_max_aa": case "Chronolog_loading_max_collagen1": case "Chronolog_loading_lag_ADP_5": case "Chronolog_loading_lag_ADP_20": case "Chronolog_loading_lag_aa": case "Chronolog_loading_lag_collagen1": case "Chronolog_standard_max_ADP_5": case "Chronolog_standard_max_ADP_20": case "Chronolog_standard_max_aa": case "Chronolog_standard_max_collagen1": case "Chronolog_standard_lag_ADP_5": case "Chronolog_standard_lag_ADP_20": case "Chronolog_standard_lag_aa": case "Chronolog_standard_lag_collagen1": case "VASP": case "Duration_followup_clinical_outcomes": case "Time_STEMI": case "Time_NSTEMI": case "Time_Angina": case "Time_REVASC": case "Time_stroke": case "Time_heartFailure": case "Time_MechValve": case "Time_tissValve": case "Time_stent": case "Time_mortality": case "Time_death": case "Time_venHypertrophy": case "Time_PeriVascular": case "Time_AF": case "Time_Loading_PFA": case "Time_loading_VerifyNow": case "Time_loading_PAP8": case "Clopidogrel_loading_dose": case "White_cell_count": case "Red_cell_count": case "Platelet_count": case "Abs_white_on_plavix": case "Red_on_plavix": case "Platelet_on_plavix": case "MeanPlateletVol_on_plavix": case "Hematocrit_on_plavix": case "Mean_platelet_volume": case "Hematocrit ": case "LDL": case "HDL": case "Total_Cholesterol": case "Triglycerides": case "Intra_assay_variation": case "Optical_Platelet_Aggregometry": case "Time_MACE": case "hemoglobin": case "plasma_urea": try { Float.valueOf(strippedValue); } catch (Exception ex) { Matcher m = sf_dosingPattern.matcher(strippedValue); valid = m.find(); if (valid) { normalizedValue = m.group(1); } } break; // columns with no/yes as 0/1 case "Genotyping": case "Phenotyping": case "Ejection_fraction": case "Clopidogrel": case "Aspirn": case "Clopidogrel_alone": case "Verify_Now_base": case "Verify_Now_post_loading": case "Verify_Now_while_on_clopidogrel": case "Pre_clopidogrel_platelet_aggregometry_base": case "Post_clopidogrel_platelet_aggregometry": enumValue = Value.lookupByName(strippedValue); if (enumValue != null) { normalizedValue = enumValue.getShortName(); } else { valid = false; } break; // columns with no/yes/unknown as 0/1/99 case "Ever_Smoked": case "Current_smoker": case "Blood_Pressure": case "placebo_RCT": case "Aspirin_Less_100": case "Statins": case "PPI ": case "Calcium_blockers": case "Beta_blockers": case "ACE_Inh": case "Ang_inh_blockers": case "Ezetemib": case "Glycoprotein_IIaIIIb_inhibitor": case "CV_events": case "Bleeding": case "Major_Bleeding": case "Minor_Bleeding": case "STEMI": case "NSTEMI": case "Other_ischemic": case "Stroke": case "All_cause_mortality": case "Cardiovascular_death": case "Angina": case "Left_ventricular_hypertrophy": case "Peripheral_vascular_disease": case "Atrial_fibrillation": case "REVASC": case "Congestive_Heart_Failure": case "Tissue_Valve_Replacement": case "Blood_Cell": case "Chol": valid = (strippedValue.equals("0") || strippedValue.equals("1") || strippedValue.equals("99")); if (strippedValue.equals("99")) { normalizedValue = IcpcUtils.NA; } break; // columns with left/right/no/unknown as 0/1/2/99 case "Stent_thromb": case "Mechanical_Valve_Replacement": valid = (strippedValue.equals("0") || strippedValue.equals("1") || strippedValue.equals("2") || strippedValue.equals("99")); if (strippedValue.equals("99")) { normalizedValue = IcpcUtils.NA; } break; // columns that are supposed to be genetic bases (eg. A/T or GC) case "rs4244285": case "rs4986893": case "rs28399504": case "rs56337013": case "rs72552267": case "rs72558186": case "rs41291556": case "rs6413438": case "rs12248560": case "rs662": case "rs854560": case "rs1045642": case "rs4803418": case "rs48034189": case "rs8192719": case "rs3745274": case "rs2279343": case "rs3745274_cyp2b6_9": case "rs2242480": case "rs3213619": case "rs2032582": case "rs1057910": case "rs71647871": Matcher m = sf_geneticBases.matcher(strippedValue); if (m.matches()) { char[] valueArray = StringUtils.remove(strippedValue.toUpperCase(), '/').toCharArray(); Arrays.sort(valueArray); StringBuilder sb = new StringBuilder(); for (char base : valueArray) { if (sb.length()!=0) { sb.append("/"); } sb.append(base); } normalizedValue = sb.toString(); } else { valid = false; } break; // columns that are stored as strings and can skip validation case "Creatinine": case "Inter_assay_variation": case "ADP": case "Arachadonic_acid": case "Collagen": case "Time_loading_Chronolog": break; // no validation default: if (sf_logger.isDebugEnabled()) { sf_logger.debug("no validation for "+key); } } if (!valid) { throw new PgkbException(key+" value is not valid: "+strippedValue); } return normalizedValue; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "normalizeValue"
"protected String normalizeValue(String key, String value) throws PgkbException { boolean valid = true; String normalizedValue; ExtendedEnum enumValue; if (IcpcUtils.isBlank(value)) { return IcpcUtils.NA; } String strippedValue = StringUtils.stripToNull(value); normalizedValue = strippedValue; switch (key) { // subject ID column is special case "Subject_ID": valid = (strippedValue.startsWith("PA") && strippedValue.length()>2); break; // columns that must be integers case "Project": Integer.valueOf(strippedValue); break; // enum columns case "Alcohol": enumValue = AlcoholStatus.lookupByName(strippedValue); if (enumValue != null) { if (enumValue==AlcoholStatus.UNKNOWN) { normalizedValue = IcpcUtils.NA; } else { normalizedValue = enumValue.getShortName(); } } else { valid = false; } break; case "Diabetes": enumValue = DiabetesStatus.lookupByName(strippedValue); if (enumValue != null) { if (enumValue == DiabetesStatus.UNKNOWN) { normalizedValue = IcpcUtils.NA; } else { normalizedValue = enumValue.getShortName(); } } else { valid = false; } break; case "Gender": enumValue = Gender.lookupByName(strippedValue); if (enumValue != null) { normalizedValue = enumValue.getShortName(); } else { valid = false; } break; case "Sample_Source": List<String> normalizedTokens = Lists.newArrayList(); for (String token : Splitter.on(";").split(strippedValue)) { SampleSource source = SampleSource.lookupByName(StringUtils.strip(token)); if (source!=null) { normalizedTokens.add(source.getShortName()); } else { valid = valid && (source!=null); } normalizedValue = Joiner.on(";").join(normalizedTokens); } break; case "PPI_Name": enumValue = DrugPpi.lookupByName(strippedValue); if (enumValue != null) { normalizedValue = enumValue.getShortName(); } else { valid = false; } break; // columns that must be floats case "Age": case "Height": case "Weight": case "BMI": case "Diastolic_BP_Max": case "Diastolic_BP_Median": case "Systolic_BP_Max": case "Systolic_BP_Median": case "CRP": case "BUN": case "Left_Ventricle": case "Right_Ventricle": case "Dose_Clopidogrel_aspirin": case "Duration_Clopidogrel": case "Duration_Aspirin": case "Duration_therapy": case "Active_metabolite": case "Days_MajorBleeding": case "Days_MinorBleeding": case "Num_bleeding": case "PFA_mean_EPI_Collagen_closure_Baseline": case "PFA_mean_ADP_Collagen_closure_Baseline": case "PFA_mean_EPI_Collagen_closure_Post": case "PFA_mean_ADP_Collagen_closure_Post": case "PFA_mean_EPI_Collagen_closure_Standard": case "PFA_mean_ADP_Collagen_closure_Standard": case "Verify_Now_baseline_Base": case "Verify_Now_baseline_PRU": case "Verify_Now_baseline_percentinhibition": case "Verify_Now_post_Base": case "Verify_Now_post_PRU": case "Verify_Now_post_percentinhibition": case "Verify_Now_on_clopidogrel_Base": case "Verify_Now_on_clopidogrel_PRU": case "Verify_Now_on_clopidogrel_percentinhibition": case "PAP_8_baseline_max_ADP_2 ": case "PAP_8_baseline_max_ADP_5": case "PAP_8_baseline_max_ADP_10": case "PAP_8_baseline_max_ADP_20": case "PAP_8_baseline_max_collagen_1": case "PAP_8_baseline_max_collagen_2": case "PAP_8_baseline_max_collagen_10": case "PAP_8_baseline_max_collagen_6": case "PAP_8_baseline_max_epi": case "PAP_8_baseline_max_aa": case "PAP_8_baseline_lag_collagen_1": case "PAP_8_baseline_lag_collagen_2": case "PAP_8_baseline_lag_collagen_5": case "PAP_8_baseline_lag_collagen_10": case "PAP_8_post_max_ADP_2 ": case "PAP_8_post_max_ADP_5": case "PAP_8_post_max_ADP_10": case "PAP_8_post_max_ADP_20": case "PAP_8_post_max_collagen_1": case "PAP_8_post_max_collagen_2": case "PAP_8_post_max_collagen_5": case "PAP_8_post_max_collagen_10": case "PAP_8_post_max_epi_perc": case "PAP_8_post_max_aa_perc": case "PAP_8_post_lag_collagen_1": case "PAP_8_post_lag_collagen_2": case "PAP_8_post_lag_collagen_5": case "PAP_8_post_lag_collagen_10": case "PAP_8_standard_max_ADP_2": case "PAP_8_standard_max_ADP_5": case "PAP_8_standard_max_ADP_10": case "PAP_8_standard_max_ADP_20": case "PAP_8_standard_max_collagen_1": case "PAP_8_standard_max_collagen_2": case "PAP_8_standard_max_collagen_5": case "PAP_8_standard_max_collagen_10": case "PAP_8_standard_max_epi_pct": case "PAP_8_standard_max_aa_pct": case "PAP_8_standard_lag_collagen_1": case "PAP_8_standard_lag_collagen_2": case "5PAP_8_standard_lag_collagen_5": case "PAP_8_standard_lag_collagen_10": case "Chronolog_baseline_max_ADP_5": case "Chronolog_baseline_max_ADP_20": case "Chronolog_baseline_max_aa": case "Chronolog_baseline_max_collagen1": case "Chronolog_baseline_lag_ADP_5": case "Chronolog_baseline_lag_ADP_20": case "Chronolog_baseline_lag_aa": case "Chronolog_baseline_lag_collagen1": case "Chronolog_loading_max_ADP_5": case "Chronolog_loading_max_ADP_20": case "Chronolog_loading_max_aa": case "Chronolog_loading_max_collagen1": case "Chronolog_loading_lag_ADP_5": case "Chronolog_loading_lag_ADP_20": case "Chronolog_loading_lag_aa": case "Chronolog_loading_lag_collagen1": case "Chronolog_standard_max_ADP_5": case "Chronolog_standard_max_ADP_20": case "Chronolog_standard_max_aa": case "Chronolog_standard_max_collagen1": case "Chronolog_standard_lag_ADP_5": case "Chronolog_standard_lag_ADP_20": case "Chronolog_standard_lag_aa": case "Chronolog_standard_lag_collagen1": case "VASP": case "Duration_followup_clinical_outcomes": case "Time_STEMI": case "Time_NSTEMI": case "Time_Angina": case "Time_REVASC": case "Time_stroke": case "Time_heartFailure": case "Time_MechValve": case "Time_tissValve": case "Time_stent": case "Time_mortality": case "Time_death": case "Time_venHypertrophy": case "Time_PeriVascular": case "Time_AF": case "Time_Loading_PFA": case "Time_loading_VerifyNow": case "Time_loading_PAP8": <MASK>case "Time_loading_Chronolog":</MASK> case "Clopidogrel_loading_dose": case "White_cell_count": case "Red_cell_count": case "Platelet_count": case "Abs_white_on_plavix": case "Red_on_plavix": case "Platelet_on_plavix": case "MeanPlateletVol_on_plavix": case "Hematocrit_on_plavix": case "Mean_platelet_volume": case "Hematocrit ": case "LDL": case "HDL": case "Total_Cholesterol": case "Triglycerides": case "Intra_assay_variation": case "Optical_Platelet_Aggregometry": case "Time_MACE": case "hemoglobin": case "plasma_urea": try { Float.valueOf(strippedValue); } catch (Exception ex) { Matcher m = sf_dosingPattern.matcher(strippedValue); valid = m.find(); if (valid) { normalizedValue = m.group(1); } } break; // columns with no/yes as 0/1 case "Genotyping": case "Phenotyping": case "Ejection_fraction": case "Clopidogrel": case "Aspirn": case "Clopidogrel_alone": case "Verify_Now_base": case "Verify_Now_post_loading": case "Verify_Now_while_on_clopidogrel": case "Pre_clopidogrel_platelet_aggregometry_base": case "Post_clopidogrel_platelet_aggregometry": enumValue = Value.lookupByName(strippedValue); if (enumValue != null) { normalizedValue = enumValue.getShortName(); } else { valid = false; } break; // columns with no/yes/unknown as 0/1/99 case "Ever_Smoked": case "Current_smoker": case "Blood_Pressure": case "placebo_RCT": case "Aspirin_Less_100": case "Statins": case "PPI ": case "Calcium_blockers": case "Beta_blockers": case "ACE_Inh": case "Ang_inh_blockers": case "Ezetemib": case "Glycoprotein_IIaIIIb_inhibitor": case "CV_events": case "Bleeding": case "Major_Bleeding": case "Minor_Bleeding": case "STEMI": case "NSTEMI": case "Other_ischemic": case "Stroke": case "All_cause_mortality": case "Cardiovascular_death": case "Angina": case "Left_ventricular_hypertrophy": case "Peripheral_vascular_disease": case "Atrial_fibrillation": case "REVASC": case "Congestive_Heart_Failure": case "Tissue_Valve_Replacement": case "Blood_Cell": case "Chol": valid = (strippedValue.equals("0") || strippedValue.equals("1") || strippedValue.equals("99")); if (strippedValue.equals("99")) { normalizedValue = IcpcUtils.NA; } break; // columns with left/right/no/unknown as 0/1/2/99 case "Stent_thromb": case "Mechanical_Valve_Replacement": valid = (strippedValue.equals("0") || strippedValue.equals("1") || strippedValue.equals("2") || strippedValue.equals("99")); if (strippedValue.equals("99")) { normalizedValue = IcpcUtils.NA; } break; // columns that are supposed to be genetic bases (eg. A/T or GC) case "rs4244285": case "rs4986893": case "rs28399504": case "rs56337013": case "rs72552267": case "rs72558186": case "rs41291556": case "rs6413438": case "rs12248560": case "rs662": case "rs854560": case "rs1045642": case "rs4803418": case "rs48034189": case "rs8192719": case "rs3745274": case "rs2279343": case "rs3745274_cyp2b6_9": case "rs2242480": case "rs3213619": case "rs2032582": case "rs1057910": case "rs71647871": Matcher m = sf_geneticBases.matcher(strippedValue); if (m.matches()) { char[] valueArray = StringUtils.remove(strippedValue.toUpperCase(), '/').toCharArray(); Arrays.sort(valueArray); StringBuilder sb = new StringBuilder(); for (char base : valueArray) { if (sb.length()!=0) { sb.append("/"); } sb.append(base); } normalizedValue = sb.toString(); } else { valid = false; } break; // columns that are stored as strings and can skip validation case "Creatinine": case "Inter_assay_variation": case "ADP": case "Arachadonic_acid": case "Collagen": break; // no validation default: if (sf_logger.isDebugEnabled()) { sf_logger.debug("no validation for "+key); } } if (!valid) { throw new PgkbException(key+" value is not valid: "+strippedValue); } return normalizedValue; }"
Inversion-Mutation
megadiff
"public void main(String[] args) throws Exception { FiniteAlphabet alp = null; //Motif[] mot = MotifIOTools.loadMotifSetXML(motifFiles); List<SymbolList> allSymLists = new ArrayList<SymbolList>(); for (InputStream seqStream : seqFiles) { SequenceDB seqDB; if (type.equals("DNA")) { alp = DNATools.getDNA(); } else if (type.equals("protein")) { alp = ProteinTools.getAlphabet(); } else { System.err.println("Invalid sequence type. Types allowed:dna|protein"); System.exit(1); } seqDB = SeqIOTools.readFasta(seqStream, alp); SequenceIterator seqIterator = seqDB.sequenceIterator(); while (seqIterator.hasNext()) { allSymLists.add(new SimpleSymbolList(seqIterator.nextSequence())); } } SequenceDB spikedSeqDB = new HashSequenceDB(); for (int i = 0; i < allSymLists.size(); i++) { SymbolList symList = allSymLists.get(i); spikedSeqDB.addSequence( new SimpleSequence( symList, null, "seq"+i, null)); } for (File f : motifFiles) { Motif[] motifs = MotifIOTools.loadMotifSetXML( new BufferedInputStream( new FileInputStream(f))); for (Motif m : motifs) { System.err.printf("Spiking %s...%n",m.getName()); WeightMatrix wm = m.getWeightMatrix(); int seqCount = allSymLists.size(); if (this.spikeCount == 0) { int spikeCount = (int) Math.round(rate * seqCount); Random random = new Random(); while (spikeCount > 0) { int randIndex = random.nextInt(allSymLists.size()); SymbolList seq = allSymLists.get(randIndex); insertSeqRandomlyToSeq(generateSeqFromWM(wm), seq, alp); spikeCount--; } } else { int spikeCount = this.spikeCount; //System.err.println("spike count:"+spikeCount); for (int i = 0; i < allSymLists.size(); i++) { SymbolList seq = allSymLists.get(i); //System.err.printf("Spiking seq %d...%n",i); while (spikeCount > 0) { /*System.err.printf( "%d spikes of %s to put in sequence %d%n", spikeCount, m.getName(), i);*/ insertSeqRandomlyToSeq(generateSeqFromWM(wm), seq, alp); } spikeCount--; } } } } OutputStream output; if (outFile == null) { output = System.out; } else { output = new BufferedOutputStream(new FileOutputStream(outFile)); } SeqIOTools.writeFasta(output,spikedSeqDB); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "main"
"public void main(String[] args) throws Exception { FiniteAlphabet alp = null; //Motif[] mot = MotifIOTools.loadMotifSetXML(motifFiles); List<SymbolList> allSymLists = new ArrayList<SymbolList>(); for (InputStream seqStream : seqFiles) { SequenceDB seqDB; if (type.equals("DNA")) { alp = DNATools.getDNA(); } else if (type.equals("protein")) { alp = ProteinTools.getAlphabet(); } else { System.err.println("Invalid sequence type. Types allowed:dna|protein"); System.exit(1); } seqDB = SeqIOTools.readFasta(seqStream, alp); SequenceIterator seqIterator = seqDB.sequenceIterator(); while (seqIterator.hasNext()) { allSymLists.add(new SimpleSymbolList(seqIterator.nextSequence())); } } SequenceDB spikedSeqDB = new HashSequenceDB(); for (int i = 0; i < allSymLists.size(); i++) { SymbolList symList = allSymLists.get(i); spikedSeqDB.addSequence( new SimpleSequence( symList, null, "seq"+i, null)); } for (File f : motifFiles) { Motif[] motifs = MotifIOTools.loadMotifSetXML( new BufferedInputStream( new FileInputStream(f))); for (Motif m : motifs) { System.err.printf("Spiking %s...%n",m.getName()); WeightMatrix wm = m.getWeightMatrix(); int seqCount = allSymLists.size(); if (this.spikeCount == 0) { int spikeCount = (int) Math.round(rate * seqCount); Random random = new Random(); while (spikeCount > 0) { int randIndex = random.nextInt(allSymLists.size()); SymbolList seq = allSymLists.get(randIndex); insertSeqRandomlyToSeq(generateSeqFromWM(wm), seq, alp); <MASK>spikeCount--;</MASK> } } else { int spikeCount = this.spikeCount; //System.err.println("spike count:"+spikeCount); for (int i = 0; i < allSymLists.size(); i++) { SymbolList seq = allSymLists.get(i); //System.err.printf("Spiking seq %d...%n",i); while (spikeCount > 0) { /*System.err.printf( "%d spikes of %s to put in sequence %d%n", spikeCount, m.getName(), i);*/ insertSeqRandomlyToSeq(generateSeqFromWM(wm), seq, alp); <MASK>spikeCount--;</MASK> } } } } } OutputStream output; if (outFile == null) { output = System.out; } else { output = new BufferedOutputStream(new FileOutputStream(outFile)); } SeqIOTools.writeFasta(output,spikedSeqDB); }"
Inversion-Mutation
megadiff
"@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (args.length < 1) { sender.sendMessage(ChatColor.RED + "Ya need to type something after it :P"); return false; } if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + "You are not an in-game player!"); return true; } Player player = (Player) sender; int i; StringBuilder me = new StringBuilder(); for (i = 0; i < args.length; i++) { me.append(args[i]); me.append(" "); } String meMessage = me.toString(); String message = meFormat; message = f.colorize(message); if (sender.hasPermission("bchatmanager.chat.color")) { meMessage = f.colorize(meMessage); } message = message.replace("%message", meMessage).replace("%displayname", "%1$s"); message = f.replacePlayerPlaceholders(player, message); message = f.replaceTime(message); if (rangedMode) { List<Player> pl = getLocalRecipients(player, message, chatRange); for (int j = 0; j < pl.size(); j++) { pl.get(j).sendMessage(message); } sender.sendMessage(message); System.out.println(message); } else { plugin.getServer().broadcastMessage(message); } return true; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCommand"
"@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (args.length < 1) { sender.sendMessage(ChatColor.RED + "Ya need to type something after it :P"); return false; } if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + "You are not an in-game player!"); return true; } Player player = (Player) sender; int i; StringBuilder me = new StringBuilder(); for (i = 0; i < args.length; i++) { <MASK>me.append(" ");</MASK> me.append(args[i]); } String meMessage = me.toString(); String message = meFormat; message = f.colorize(message); if (sender.hasPermission("bchatmanager.chat.color")) { meMessage = f.colorize(meMessage); } message = message.replace("%message", meMessage).replace("%displayname", "%1$s"); message = f.replacePlayerPlaceholders(player, message); message = f.replaceTime(message); if (rangedMode) { List<Player> pl = getLocalRecipients(player, message, chatRange); for (int j = 0; j < pl.size(); j++) { pl.get(j).sendMessage(message); } sender.sendMessage(message); System.out.println(message); } else { plugin.getServer().broadcastMessage(message); } return true; }"
Inversion-Mutation
megadiff
"private void saveToRecorder(ProcessorURI curi, Socket socket, Recorder recorder) throws IOException, InterruptedException { recorder.inputWrap(socket.getInputStream()); recorder.outputWrap(socket.getOutputStream()); recorder.markContentBegin(); // Read the remote file/dir listing in its entirety. long softMax = 0; long hardMax = getMaxLengthBytes(); long timeout = (long)getTimeoutSeconds() * 1000L; int maxRate = getMaxFetchKBSec(); RecordingInputStream input = recorder.getRecordedInput(); input.setLimits(hardMax, timeout, maxRate); input.readFullyOrUntil(softMax); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "saveToRecorder"
"private void saveToRecorder(ProcessorURI curi, Socket socket, Recorder recorder) throws IOException, InterruptedException { <MASK>recorder.markContentBegin();</MASK> recorder.inputWrap(socket.getInputStream()); recorder.outputWrap(socket.getOutputStream()); // Read the remote file/dir listing in its entirety. long softMax = 0; long hardMax = getMaxLengthBytes(); long timeout = (long)getTimeoutSeconds() * 1000L; int maxRate = getMaxFetchKBSec(); RecordingInputStream input = recorder.getRecordedInput(); input.setLimits(hardMax, timeout, maxRate); input.readFullyOrUntil(softMax); }"
Inversion-Mutation
megadiff
"@Override public void createControl(Composite parent, final FormToolkit toolkit) { initialize(); selectionProvider = new SelectionProviderAdapter(); actionGroup = new CommentActionGroup(); MenuManager menuManager = new MenuManager(); menuManager.setRemoveAllWhenShown(true); menuManager.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { // get comment and add reply action as first item in the menu ISelection selection = selectionProvider.getSelection(); if (selection instanceof IStructuredSelection && !selection.isEmpty()) { Object element = ((IStructuredSelection) selection).getFirstElement(); if (element instanceof ITaskComment) { final ITaskComment comment = (ITaskComment) element; AbstractReplyToCommentAction replyAction = new AbstractReplyToCommentAction( getTaskEditorPage(), comment) { @Override protected String getReplyText() { return comment.getText(); } }; manager.add(replyAction); } } actionGroup.setContext(new ActionContext(selectionProvider.getSelection())); actionGroup.fillContextMenu(manager); if (currentViewer != null && currentViewer.getEditor() instanceof RichTextAttributeEditor) { RichTextAttributeEditor editor = (RichTextAttributeEditor) currentViewer.getEditor(); if (editor.getViewSourceAction().isEnabled()) { manager.add(new Separator("planning")); //$NON-NLS-1$ manager.add(editor.getViewSourceAction()); } } } }); getTaskEditorPage().getEditorSite().registerContextMenu(ID_POPUP_MENU, menuManager, selectionProvider, false); commentMenu = menuManager.createContextMenu(parent); section = createSection(parent, toolkit, hasIncoming); section.setText(section.getText() + " (" + commentAttributes.size() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ if (commentAttributes.isEmpty()) { section.setEnabled(false); } else { if (hasIncoming) { expandSection(toolkit, section); } else { section.addExpansionListener(new ExpansionAdapter() { @Override public void expansionStateChanged(ExpansionEvent event) { if (section.getClient() == null) { try { expandAllInProgress = true; getTaskEditorPage().setReflow(false); expandSection(toolkit, section); } finally { expandAllInProgress = false; getTaskEditorPage().setReflow(true); } getTaskEditorPage().reflow(); } } }); } } setSection(toolkit, section); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createControl"
"@Override public void createControl(Composite parent, final FormToolkit toolkit) { initialize(); selectionProvider = new SelectionProviderAdapter(); actionGroup = new CommentActionGroup(); MenuManager menuManager = new MenuManager(); menuManager.setRemoveAllWhenShown(true); menuManager.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { // get comment and add reply action as first item in the menu ISelection selection = selectionProvider.getSelection(); if (selection instanceof IStructuredSelection && !selection.isEmpty()) { Object element = ((IStructuredSelection) selection).getFirstElement(); if (element instanceof ITaskComment) { final ITaskComment comment = (ITaskComment) element; AbstractReplyToCommentAction replyAction = new AbstractReplyToCommentAction( getTaskEditorPage(), comment) { @Override protected String getReplyText() { return comment.getText(); } }; manager.add(replyAction); } } <MASK>actionGroup.fillContextMenu(manager);</MASK> actionGroup.setContext(new ActionContext(selectionProvider.getSelection())); if (currentViewer != null && currentViewer.getEditor() instanceof RichTextAttributeEditor) { RichTextAttributeEditor editor = (RichTextAttributeEditor) currentViewer.getEditor(); if (editor.getViewSourceAction().isEnabled()) { manager.add(new Separator("planning")); //$NON-NLS-1$ manager.add(editor.getViewSourceAction()); } } } }); getTaskEditorPage().getEditorSite().registerContextMenu(ID_POPUP_MENU, menuManager, selectionProvider, false); commentMenu = menuManager.createContextMenu(parent); section = createSection(parent, toolkit, hasIncoming); section.setText(section.getText() + " (" + commentAttributes.size() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ if (commentAttributes.isEmpty()) { section.setEnabled(false); } else { if (hasIncoming) { expandSection(toolkit, section); } else { section.addExpansionListener(new ExpansionAdapter() { @Override public void expansionStateChanged(ExpansionEvent event) { if (section.getClient() == null) { try { expandAllInProgress = true; getTaskEditorPage().setReflow(false); expandSection(toolkit, section); } finally { expandAllInProgress = false; getTaskEditorPage().setReflow(true); } getTaskEditorPage().reflow(); } } }); } } setSection(toolkit, section); }"
Inversion-Mutation
megadiff
"public void menuAboutToShow(IMenuManager manager) { // get comment and add reply action as first item in the menu ISelection selection = selectionProvider.getSelection(); if (selection instanceof IStructuredSelection && !selection.isEmpty()) { Object element = ((IStructuredSelection) selection).getFirstElement(); if (element instanceof ITaskComment) { final ITaskComment comment = (ITaskComment) element; AbstractReplyToCommentAction replyAction = new AbstractReplyToCommentAction( getTaskEditorPage(), comment) { @Override protected String getReplyText() { return comment.getText(); } }; manager.add(replyAction); } } actionGroup.setContext(new ActionContext(selectionProvider.getSelection())); actionGroup.fillContextMenu(manager); if (currentViewer != null && currentViewer.getEditor() instanceof RichTextAttributeEditor) { RichTextAttributeEditor editor = (RichTextAttributeEditor) currentViewer.getEditor(); if (editor.getViewSourceAction().isEnabled()) { manager.add(new Separator("planning")); //$NON-NLS-1$ manager.add(editor.getViewSourceAction()); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "menuAboutToShow"
"public void menuAboutToShow(IMenuManager manager) { // get comment and add reply action as first item in the menu ISelection selection = selectionProvider.getSelection(); if (selection instanceof IStructuredSelection && !selection.isEmpty()) { Object element = ((IStructuredSelection) selection).getFirstElement(); if (element instanceof ITaskComment) { final ITaskComment comment = (ITaskComment) element; AbstractReplyToCommentAction replyAction = new AbstractReplyToCommentAction( getTaskEditorPage(), comment) { @Override protected String getReplyText() { return comment.getText(); } }; manager.add(replyAction); } } <MASK>actionGroup.fillContextMenu(manager);</MASK> actionGroup.setContext(new ActionContext(selectionProvider.getSelection())); if (currentViewer != null && currentViewer.getEditor() instanceof RichTextAttributeEditor) { RichTextAttributeEditor editor = (RichTextAttributeEditor) currentViewer.getEditor(); if (editor.getViewSourceAction().isEnabled()) { manager.add(new Separator("planning")); //$NON-NLS-1$ manager.add(editor.getViewSourceAction()); } } }"