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 tearDown() throws Exception { super.tearDown(); deleteDirectory(OUTBOX_DIR); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "tearDown"
"@Override public void tearDown() throws Exception { <MASK>deleteDirectory(OUTBOX_DIR);</MASK> super.tearDown(); }"
Inversion-Mutation
megadiff
"public Pagination() { paginationDiv.setStyle(Bootstrap.Pagination.LEFT); paginationDiv.add(list); initWidget(paginationDiv); setSize(PaginationSize.NORMAL); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "Pagination"
"public Pagination() { paginationDiv.setStyle(Bootstrap.Pagination.LEFT); paginationDiv.add(list); <MASK>setSize(PaginationSize.NORMAL);</MASK> initWidget(paginationDiv); }"
Inversion-Mutation
megadiff
"public static InApplicationMonitor initInstance(CorePlugin corePlugin, KeyHandler keyHandler) { CorePlugin previousCorePlugin; synchronized (semaphore) { LOGGER.info("+++ initializing InApplicationMonitor() +++"); INSTANCE.keyHandler = keyHandler; LOGGER.info("syncing from previous core plugin"); previousCorePlugin = INSTANCE.corePlugin; corePlugin.syncFrom(previousCorePlugin); INSTANCE.plugins.add(corePlugin); INSTANCE.plugins.remove(previousCorePlugin); INSTANCE.corePlugin = corePlugin; LOGGER.info("InApplicationMonitor updated successfully."); } if ((previousCorePlugin != null) && (previousCorePlugin != corePlugin)) { previousCorePlugin.destroy(); } return INSTANCE; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "initInstance"
"public static InApplicationMonitor initInstance(CorePlugin corePlugin, KeyHandler keyHandler) { CorePlugin previousCorePlugin; synchronized (semaphore) { LOGGER.info("+++ initializing InApplicationMonitor() +++"); INSTANCE.keyHandler = keyHandler; previousCorePlugin = INSTANCE.corePlugin; corePlugin.syncFrom(previousCorePlugin); INSTANCE.plugins.add(corePlugin); INSTANCE.plugins.remove(previousCorePlugin); INSTANCE.corePlugin = corePlugin; LOGGER.info("InApplicationMonitor updated successfully."); } if ((previousCorePlugin != null) && (previousCorePlugin != corePlugin)) { <MASK>LOGGER.info("syncing from previous core plugin");</MASK> previousCorePlugin.destroy(); } return INSTANCE; }"
Inversion-Mutation
megadiff
"@Override public void onStart() { boolean resize = false; boolean move = false; boolean hidden = !g.visible(); Effect fx; g.show(); for (String key : prps.keys()) { String val = prps.get(key); if ((fx = computeFxProp(e, key, val, hidden)) != null) { effects.add(fx); resize = resize || "height".equals(key) || "width".equals(key); move = move || "top".equals(key) || "left".equals(key); } } g.saveCssAttrs(attrsToSave); if (resize) { g.css("overflow", "hidden"); g.css("white-space", "nowrap"); } if (move && !g.css("position", true).matches("absolute|relative")) { g.css("position", "relative"); } g.css("visibility", "visible"); super.onStart(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onStart"
"@Override public void onStart() { boolean resize = false; boolean move = false; boolean hidden = !g.visible(); Effect fx; g.show(); for (String key : prps.keys()) { String val = prps.get(key); if ((fx = computeFxProp(e, key, val, hidden)) != null) { effects.add(fx); resize = resize || "height".equals(key) || "width".equals(key); move = move || "top".equals(key) || "left".equals(key); } } g.saveCssAttrs(attrsToSave); if (resize) { g.css("overflow", "hidden"); } if (move && !g.css("position", true).matches("absolute|relative")) { g.css("position", "relative"); } g.css("visibility", "visible"); <MASK>g.css("white-space", "nowrap");</MASK> super.onStart(); }"
Inversion-Mutation
megadiff
"public int getSectionForPosition(int position) { int savedCursorPos = mDataCursor.getPosition(); mDataCursor.moveToPosition(position); String curName = mDataCursor.getString(mColumnIndex); mDataCursor.moveToPosition(savedCursorPos); // Linear search, as there are only a few items in the section index // Could speed this up later if it actually gets used. for (int i = 0; i < mAlphabetLength; i++) { char letter = mAlphabet.charAt(i); String targetLetter = Character.toString(letter); if (compare(curName, targetLetter) == 0) { return i; } } return 0; // Don't recognize the letter - falls under zero'th section }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getSectionForPosition"
"public int getSectionForPosition(int position) { int savedCursorPos = mDataCursor.getPosition(); mDataCursor.moveToPosition(position); <MASK>mDataCursor.moveToPosition(savedCursorPos);</MASK> String curName = mDataCursor.getString(mColumnIndex); // Linear search, as there are only a few items in the section index // Could speed this up later if it actually gets used. for (int i = 0; i < mAlphabetLength; i++) { char letter = mAlphabet.charAt(i); String targetLetter = Character.toString(letter); if (compare(curName, targetLetter) == 0) { return i; } } return 0; // Don't recognize the letter - falls under zero'th section }"
Inversion-Mutation
megadiff
"private CommonPrefs refresh() { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences( s_context ); String key; key = s_context.getString( R.string.key_show_arrow ); showBoardArrow = sp.getBoolean( key, true ); key = s_context.getString( R.string.key_explain_robot ); showRobotScores = sp.getBoolean( key, false ); key = s_context.getString( R.string.key_hide_values ); hideTileValues = sp.getBoolean( key, false ); key = s_context.getString( R.string.key_skip_confirm ); skipCommitConfirm = sp.getBoolean( key, false ); key = s_context.getString( R.string.key_color_tiles ); showColors = sp.getBoolean( key, true ); int ids[] = { R.string.key_player0, R.string.key_player1, R.string.key_player2, R.string.key_player3, }; for ( int ii = 0; ii < ids.length; ++ii ) { playerColors[ii] = prefToColor( sp, ids[ii] ); } int ids2[] = { R.string.key_bonus_l2x, R.string.key_bonus_w2x, R.string.key_bonus_l3x, R.string.key_bonus_w3x, }; for ( int ii = 0; ii < ids2.length; ++ii ) { bonusColors[ii+1] = prefToColor( sp, ids2[ii] ); } int idsOther[] = { R.string.key_tile_back, R.string.key_empty, R.string.key_focus, }; for ( int ii = 0; ii < idsOther.length; ++ii ) { otherColors[ii] = prefToColor( sp, idsOther[ii] ); } return this; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "refresh"
"private CommonPrefs refresh() { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences( s_context ); String key; key = s_context.getString( R.string.key_show_arrow ); showBoardArrow = sp.getBoolean( key, true ); key = s_context.getString( R.string.key_explain_robot ); showRobotScores = sp.getBoolean( key, false ); key = s_context.getString( R.string.key_hide_values ); hideTileValues = sp.getBoolean( key, false ); key = s_context.getString( R.string.key_skip_confirm ); skipCommitConfirm = sp.getBoolean( key, false ); key = s_context.getString( R.string.key_color_tiles ); showColors = sp.getBoolean( key, true ); int ids[] = { R.string.key_player0, R.string.key_player1, R.string.key_player2, R.string.key_player3, }; for ( int ii = 0; ii < ids.length; ++ii ) { playerColors[ii] = prefToColor( sp, ids[ii] ); } int ids2[] = { R.string.key_bonus_l2x, <MASK>R.string.key_bonus_l3x,</MASK> R.string.key_bonus_w2x, R.string.key_bonus_w3x, }; for ( int ii = 0; ii < ids2.length; ++ii ) { bonusColors[ii+1] = prefToColor( sp, ids2[ii] ); } int idsOther[] = { R.string.key_tile_back, R.string.key_empty, R.string.key_focus, }; for ( int ii = 0; ii < idsOther.length; ++ii ) { otherColors[ii] = prefToColor( sp, idsOther[ii] ); } return this; }"
Inversion-Mutation
megadiff
"public static void populate(){ if(Zegana.xa == 't'){ Zegana.currentGen = Zegana.select(Zegana.currentGen, Zegana.performance); for(int i=0; i<currentGen.length; i++){ if(Math.random()< Zegana.mutationChance) Zegana.twiddle(currentGen[i]); } }else if(Zegana.xa == 'i'){ Deck[] newGen = new Deck[currentGen.length]; float total = arraySum(Zegana.performance); for(int i=0; i<newGen.length; i+=2){ crossover(newGen, i, Zegana.currentGen, Zegana.performance, total); } for(int i=0; i<newGen.length; i++){ if(Math.random() < Zegana.mutationChance){ newGen[i].cards.add(LegalCards.get((int) (Math.random()*LegalCards.size()))); } if((Math.random() < Zegana.mutationChance) && (newGen[i].cards.size() > Zegana.minCards)){ newGen[i].cards.remove( (int) Math.random() * newGen[i].cards.size()); } if(Math.random() < Zegana.inversionChance){ inversion(newGen[i]); } maxCopies(newGen[i]); minSize(newGen[i]); } Zegana.currentGen = newGen; } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "populate"
"public static void populate(){ if(Zegana.xa == 't'){ Zegana.currentGen = Zegana.select(Zegana.currentGen, Zegana.performance); for(int i=0; i<currentGen.length; i++){ if(Math.random()< Zegana.mutationChance) Zegana.twiddle(currentGen[i]); } }else if(Zegana.xa == 'i'){ Deck[] newGen = new Deck[currentGen.length]; float total = arraySum(Zegana.performance); for(int i=0; i<newGen.length; i+=2){ crossover(newGen, i, Zegana.currentGen, Zegana.performance, total); } for(int i=0; i<newGen.length; i++){ if(Math.random() < Zegana.mutationChance){ newGen[i].cards.add(LegalCards.get((int) (Math.random()*LegalCards.size()))); } if((Math.random() < Zegana.mutationChance) && (newGen[i].cards.size() > Zegana.minCards)){ newGen[i].cards.remove( (int) Math.random() * newGen[i].cards.size()); } if(Math.random() < Zegana.inversionChance){ inversion(newGen[i]); } <MASK>minSize(newGen[i]);</MASK> maxCopies(newGen[i]); } Zegana.currentGen = newGen; } }"
Inversion-Mutation
megadiff
"public StorageUnit(StorageUnit su){ super(su); assert su != null; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "StorageUnit"
"public StorageUnit(StorageUnit su){ <MASK>assert su != null;</MASK> super(su); }"
Inversion-Mutation
megadiff
"public synchronized void refreshFeedCache(boolean force) { Log.i(LOG_TAG, "Refreshing the cache feed from db. The force flag value is ["+force+"] and the size of cache elements is :: " + cachedEarthQuakeFeed.size()); if(cachedEarthQuakeFeed.size() == 0 || force) { cachedEarthQuakeFeed.clear(); EarthquakeCursor allEarthquakes = db.getEarthquakes(getCurrentMinIntensity()); EarthQuake currentEarthquake = null; try { if(allEarthquakes != null && allEarthquakes.moveToFirst()) { do { currentEarthquake = allEarthquakes.getEarthQuake(); if(!withinRadius(currentEarthquake)) continue; cachedEarthQuakeFeed.add(currentEarthquake); } while(allEarthquakes.moveToNext()); } } finally { allEarthquakes.close(); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "refreshFeedCache"
"public synchronized void refreshFeedCache(boolean force) { Log.i(LOG_TAG, "Refreshing the cache feed from db. The force flag value is ["+force+"] and the size of cache elements is :: " + cachedEarthQuakeFeed.size()); if(cachedEarthQuakeFeed.size() == 0 || force) { EarthquakeCursor allEarthquakes = db.getEarthquakes(getCurrentMinIntensity()); EarthQuake currentEarthquake = null; try { if(allEarthquakes != null && allEarthquakes.moveToFirst()) { <MASK>cachedEarthQuakeFeed.clear();</MASK> do { currentEarthquake = allEarthquakes.getEarthQuake(); if(!withinRadius(currentEarthquake)) continue; cachedEarthQuakeFeed.add(currentEarthquake); } while(allEarthquakes.moveToNext()); } } finally { allEarthquakes.close(); } } }"
Inversion-Mutation
megadiff
"@Transactional @Test public void testInternalRetrySuccessOnSecondAttemptWithItemProvider() throws Exception { assertInitialState(); JmsItemReader<Object> provider = new JmsItemReader<Object>(); // provider.setItemType(Message.class); jmsTemplate.setDefaultDestinationName("queue"); provider.setJmsTemplate(jmsTemplate); final Object item = provider.read(); retryTemplate.execute(new RetryCallback<String>() { public String doWithRetry(RetryContext context) throws Exception { TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); transactionTemplate.setPropagationBehavior(TransactionTemplate.PROPAGATION_NESTED); return (String) transactionTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { list.add(item); System.err.println("Inserting: [" + list.size() + "," + item + "]"); simpleJdbcTemplate.update("INSERT into T_FOOS (id,name,foo_date) values (?,?,null)", list.size(), item); if (list.size() == 1) { throw new RuntimeException("Rollback!"); } return item; } }); } }); // Verify the state after transactional processing is complete List<String> msgs = getMessages(); // The database portion committed once... int count = simpleJdbcTemplate.queryForInt("select count(*) from T_FOOS"); assertEquals(1, count); // ... and so did the message session. assertEquals("[]", msgs.toString()); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "testInternalRetrySuccessOnSecondAttemptWithItemProvider"
"@Transactional @Test public void testInternalRetrySuccessOnSecondAttemptWithItemProvider() throws Exception { assertInitialState(); JmsItemReader<Object> provider = new JmsItemReader<Object>(); // provider.setItemType(Message.class); <MASK>provider.setJmsTemplate(jmsTemplate);</MASK> jmsTemplate.setDefaultDestinationName("queue"); final Object item = provider.read(); retryTemplate.execute(new RetryCallback<String>() { public String doWithRetry(RetryContext context) throws Exception { TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); transactionTemplate.setPropagationBehavior(TransactionTemplate.PROPAGATION_NESTED); return (String) transactionTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { list.add(item); System.err.println("Inserting: [" + list.size() + "," + item + "]"); simpleJdbcTemplate.update("INSERT into T_FOOS (id,name,foo_date) values (?,?,null)", list.size(), item); if (list.size() == 1) { throw new RuntimeException("Rollback!"); } return item; } }); } }); // Verify the state after transactional processing is complete List<String> msgs = getMessages(); // The database portion committed once... int count = simpleJdbcTemplate.queryForInt("select count(*) from T_FOOS"); assertEquals(1, count); // ... and so did the message session. assertEquals("[]", msgs.toString()); }"
Inversion-Mutation
megadiff
"private void populateDataSet() throws DataException { int originalMaxRows = this.populator.getQuery( ).getMaxRows( ); boolean changeMaxRows = filterByRow == null?false:filterByRow.getFilterList( FilterByRow.QUERY_FILTER ) .size( ) + filterByRow.getFilterList( FilterByRow.GROUP_FILTER ).size( ) > 0; if ( changeMaxRows ) this.populator.getQuery( ).setMaxRows( 0 ); List aggCCList = prepareComputedColumns(TransformationConstants.DATA_SET_MODEL ); doDataSetFilter( changeMaxRows ); populateAggrCCs( this.getAggrComputedColumns( aggCCList, true )); removeAvailableComputedColumns( ); //Begin populate computed columns with aggregations. //TODO:remove me populateComputedColumns( this.getAggrComputedColumns( aggCCList, false )); this.populator.getQuery( ).setMaxRows( originalMaxRows ); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "populateDataSet"
"private void populateDataSet() throws DataException { int originalMaxRows = this.populator.getQuery( ).getMaxRows( ); boolean changeMaxRows = filterByRow == null?false:filterByRow.getFilterList( FilterByRow.QUERY_FILTER ) .size( ) + filterByRow.getFilterList( FilterByRow.GROUP_FILTER ).size( ) > 0; if ( changeMaxRows ) this.populator.getQuery( ).setMaxRows( 0 ); List aggCCList = prepareComputedColumns(TransformationConstants.DATA_SET_MODEL ); populateAggrCCs( this.getAggrComputedColumns( aggCCList, true )); removeAvailableComputedColumns( ); <MASK>doDataSetFilter( changeMaxRows );</MASK> //Begin populate computed columns with aggregations. //TODO:remove me populateComputedColumns( this.getAggrComputedColumns( aggCCList, false )); this.populator.getQuery( ).setMaxRows( originalMaxRows ); }"
Inversion-Mutation
megadiff
"public void close() { isClose.set(true); try { connectionsPool.destroy(); openChannels.close(); for (Channel channel : openChannels) { ChannelHandlerContext ctx = channel.getPipeline().getContext(NettyAsyncHttpProvider.class); if (ctx.getAttachment() instanceof NettyResponseFuture<?>) { NettyResponseFuture<?> future = (NettyResponseFuture<?>) ctx.getAttachment(); future.setReaperFuture(null); } } config.executorService().shutdown(); config.reaper().shutdown(); socketChannelFactory.releaseExternalResources(); plainBootstrap.releaseExternalResources(); secureBootstrap.releaseExternalResources(); webSocketBootstrap.releaseExternalResources(); secureWebSocketBootstrap.releaseExternalResources(); } catch (Throwable t) { log.warn("Unexpected error on close", t); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "close"
"public void close() { isClose.set(true); try { connectionsPool.destroy(); openChannels.close(); for (Channel channel : openChannels) { ChannelHandlerContext ctx = channel.getPipeline().getContext(NettyAsyncHttpProvider.class); if (ctx.getAttachment() instanceof NettyResponseFuture<?>) { NettyResponseFuture<?> future = (NettyResponseFuture<?>) ctx.getAttachment(); future.setReaperFuture(null); } } config.executorService().shutdown(); config.reaper().shutdown(); plainBootstrap.releaseExternalResources(); secureBootstrap.releaseExternalResources(); webSocketBootstrap.releaseExternalResources(); secureWebSocketBootstrap.releaseExternalResources(); <MASK>socketChannelFactory.releaseExternalResources();</MASK> } catch (Throwable t) { log.warn("Unexpected error on close", t); } }"
Inversion-Mutation
megadiff
"private void initializeView(int position, View view) { Database.Schedule schedule = mSchedules[position]; int scheduleId = schedule.getId(); CompoundButton checkBox = (CompoundButton)view.findViewById(R.id.checkbox); int[] ids = mDatabase.getScheduleIdsOfTask(mId); checkBox.setOnCheckedChangeListener(new CheckBoxListener(scheduleId)); checkBox.setChecked(contains(ids, scheduleId)); boolean isDaily = schedule.isDaily(); String hour = isDaily ? String.format(Locale.ROOT, "%02d", schedule.getHour()) : " *"; int minute = schedule.getMinute(); TextView scheduleText = (TextView)view.findViewById(R.id.schedule_text); scheduleText.setText(String.format("%s:%02d", hour, minute)); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "initializeView"
"private void initializeView(int position, View view) { Database.Schedule schedule = mSchedules[position]; int scheduleId = schedule.getId(); CompoundButton checkBox = (CompoundButton)view.findViewById(R.id.checkbox); int[] ids = mDatabase.getScheduleIdsOfTask(mId); <MASK>checkBox.setChecked(contains(ids, scheduleId));</MASK> checkBox.setOnCheckedChangeListener(new CheckBoxListener(scheduleId)); boolean isDaily = schedule.isDaily(); String hour = isDaily ? String.format(Locale.ROOT, "%02d", schedule.getHour()) : " *"; int minute = schedule.getMinute(); TextView scheduleText = (TextView)view.findViewById(R.id.schedule_text); scheduleText.setText(String.format("%s:%02d", hour, minute)); }"
Inversion-Mutation
megadiff
"public void hidePlaceholder() { if (super.getText().equals(this.getPlaceholderText())) { super.setText(""); } super.removeStyleName(this.getPlaceholderStyleName()); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "hidePlaceholder"
"public void hidePlaceholder() { if (super.getText().equals(this.getPlaceholderText())) { super.setText(""); <MASK>super.removeStyleName(this.getPlaceholderStyleName());</MASK> } }"
Inversion-Mutation
megadiff
"@Override public void onError(MediaRecorder mr, int what, int extra) { Log.e(TAG, "MediaRecorder error. what=" + what + ". extra=" + extra); stopVideoRecording(); if (what == MediaRecorder.MEDIA_RECORDER_ERROR_UNKNOWN) { // We may have run out of space on the sdcard. mActivity.updateStorageSpaceAndHint(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onError"
"@Override public void onError(MediaRecorder mr, int what, int extra) { Log.e(TAG, "MediaRecorder error. what=" + what + ". extra=" + extra); if (what == MediaRecorder.MEDIA_RECORDER_ERROR_UNKNOWN) { // We may have run out of space on the sdcard. <MASK>stopVideoRecording();</MASK> mActivity.updateStorageSpaceAndHint(); } }"
Inversion-Mutation
megadiff
"void addLinkContentItem(PDFLink link, String structurePointer) { int structParent = getNextParentTreeKey(); link.setStructParent(structParent); PDFDictionary contentItem = new PDFDictionary(); contentItem.put("Type", OBJR); contentItem.put("Pg", this.currentPage); contentItem.put("Obj", link); PDFStructElem parent = (PDFStructElem) structTreeMap.get(structurePointer); parentTree.getNums().put(structParent, link); parent.addKid(contentItem); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addLinkContentItem"
"void addLinkContentItem(PDFLink link, String structurePointer) { int structParent = getNextParentTreeKey(); link.setStructParent(structParent); <MASK>parentTree.getNums().put(structParent, link);</MASK> PDFDictionary contentItem = new PDFDictionary(); contentItem.put("Type", OBJR); contentItem.put("Pg", this.currentPage); contentItem.put("Obj", link); PDFStructElem parent = (PDFStructElem) structTreeMap.get(structurePointer); parent.addKid(contentItem); }"
Inversion-Mutation
megadiff
"@Override public final void execute(CharWrapper characters, ProductionContext context) throws Exception { characters.removeSpace(); String extraExcMsg=""; if(!hasValue){ hasValue=true; Matcher match = characters.match(getPattern()); if(match.find()){ characters.shift(match.group(1).length()); characters.removeSpace(); Matcher nameMatch = characters.match(NAME); if(nameMatch.find()){ String name = nameMatch.group(1); characters.shift(name.length()); if(characters.removeSpace()){ Output assignmentOutput = new Output(); doAssignment(name, assignmentOutput); context.getCurrentVariableOutput().add(name, assignmentOutput); context.addProduction(getProduction(assignmentOutput)); } else { doNoAssignment(name, context); } return; } } extraExcMsg=" No Name found."; } else if(characters.charAt(0) == close){ characters.shift(1); context.removeProduction(); return; } throw new Exception("Invalid "+getClassName()+"."+extraExcMsg); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "execute"
"@Override public final void execute(CharWrapper characters, ProductionContext context) throws Exception { characters.removeSpace(); String extraExcMsg=""; if(!hasValue){ Matcher match = characters.match(getPattern()); if(match.find()){ characters.shift(match.group(1).length()); characters.removeSpace(); Matcher nameMatch = characters.match(NAME); if(nameMatch.find()){ String name = nameMatch.group(1); characters.shift(name.length()); if(characters.removeSpace()){ <MASK>hasValue=true;</MASK> Output assignmentOutput = new Output(); doAssignment(name, assignmentOutput); context.getCurrentVariableOutput().add(name, assignmentOutput); context.addProduction(getProduction(assignmentOutput)); } else { doNoAssignment(name, context); } return; } } extraExcMsg=" No Name found."; } else if(characters.charAt(0) == close){ characters.shift(1); context.removeProduction(); return; } throw new Exception("Invalid "+getClassName()+"."+extraExcMsg); }"
Inversion-Mutation
megadiff
"public void updatePingGUIValue(String value) { // Format of value : ICMP ip nb_try nb_worked total_timems[ first_timems]*[;...] // We can't use the total time as on linux it isn't the sum of all the pings. // So we will display the first time. //final String regex = "\\S+\\s\\S+\\s(\\d+)\\s(\\d+)\\s(\\d+)\\s(\\d+).+"; try { String[] groups = value.split(";")[0].split(" |ms", 8); int nb_try = Integer.parseInt(groups[2]); int nb_worked = Integer.parseInt(groups[3]); //float totaltime = Float.parseFloat(groups[4]) / 1000f; if (nb_worked == 0) { this.connectionRefused(); } else if (nb_worked < nb_try -1)//If more then 1 ICMP ping failed { this.unknownError(); } else { float firsttime = Float.parseFloat(groups[6]) / 1000f; this.setValue(firsttime); } } catch (Exception e) { //There is a parsing error. This probably mean their was an error during the ping. this.unknownError(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "updatePingGUIValue"
"public void updatePingGUIValue(String value) { // Format of value : ICMP ip nb_try nb_worked total_timems[ first_timems]*[;...] // We can't use the total time as on linux it isn't the sum of all the pings. // So we will display the first time. //final String regex = "\\S+\\s\\S+\\s(\\d+)\\s(\\d+)\\s(\\d+)\\s(\\d+).+"; try { String[] groups = value.split(";")[0].split(" |ms", 8); int nb_try = Integer.parseInt(groups[2]); int nb_worked = Integer.parseInt(groups[3]); //float totaltime = Float.parseFloat(groups[4]) / 1000f; <MASK>float firsttime = Float.parseFloat(groups[6]) / 1000f;</MASK> if (nb_worked == 0) { this.connectionRefused(); } else if (nb_worked < nb_try -1)//If more then 1 ICMP ping failed { this.unknownError(); } else { this.setValue(firsttime); } } catch (Exception e) { //There is a parsing error. This probably mean their was an error during the ping. this.unknownError(); } }"
Inversion-Mutation
megadiff
"@Override public void processCommandWithMap(ICommandSender sender, Map map, String[] args){ Player player = PlayerRegistry.instance().getPlayerByUsername(args[0]); args[0] = null; String cmd = Joiner.on(" ").skipNulls().join(args); if (player != null){ FMLCommonHandler.instance().getMinecraftServerInstance().getCommandManager().executeCommand(player.getEntity(), cmd); }else{ throw new CommandException("Unknown player"); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "processCommandWithMap"
"@Override public void processCommandWithMap(ICommandSender sender, Map map, String[] args){ args[0] = null; String cmd = Joiner.on(" ").skipNulls().join(args); <MASK>Player player = PlayerRegistry.instance().getPlayerByUsername(args[0]);</MASK> if (player != null){ FMLCommonHandler.instance().getMinecraftServerInstance().getCommandManager().executeCommand(player.getEntity(), cmd); }else{ throw new CommandException("Unknown player"); } }"
Inversion-Mutation
megadiff
"OnlineSectioningServerImpl(Long sessionId, boolean waitTillStarted) throws SectioningException { iConfig = new ServerConfig(); org.hibernate.Session hibSession = SessionDAO.getInstance().createNewSession(); try { Session session = SessionDAO.getInstance().get(sessionId, hibSession); if (session == null) throw new SectioningException(MSG.exceptionSessionDoesNotExist(sessionId == null ? "null" : sessionId.toString())); iAcademicSession = new AcademicSessionInfo(session); iLog = LogFactory.getLog(OnlineSectioningServerImpl.class.getName() + ".server[" + iAcademicSession.toCompactString() + "]"); iMultiLock = new MultiLock(iAcademicSession); iExecutor = new AsyncExecutor(); iExecutor.start(); final OnlineSectioningLog.Entity user = OnlineSectioningLog.Entity.newBuilder() .setExternalId(StudentClassEnrollment.SystemChange.SYSTEM.name()) .setName(StudentClassEnrollment.SystemChange.SYSTEM.getName()) .setType(OnlineSectioningLog.Entity.EntityType.OTHER).build(); if (waitTillStarted) { try { execute(new ReloadAllData(), user); } catch (Throwable exception) { iLog.error("Failed to load server: " + exception.getMessage(), exception); throw exception; } if (iAcademicSession.isSectioningEnabled()) { try { execute(new CheckAllOfferingsAction(), user); } catch (Throwable exception) { iLog.error("Failed to check all offerings: " + exception.getMessage(), exception); throw exception; } } } else { execute(new ReloadAllData(), user, new ServerCallback<Boolean>() { @Override public void onSuccess(Boolean result) { if (iAcademicSession.isSectioningEnabled()) execute(new CheckAllOfferingsAction(), user, new ServerCallback<Boolean>() { @Override public void onSuccess(Boolean result) {} @Override public void onFailure(Throwable exception) { iLog.error("Failed to check all offerings: " + exception.getMessage(), exception); } }); } @Override public void onFailure(Throwable exception) { iLog.error("Failed to load server: " + exception.getMessage(), exception); } }); } } catch (Throwable t) { if (t instanceof SectioningException) throw (SectioningException)t; throw new SectioningException(MSG.exceptionUnknown(t.getMessage()), t); } finally { hibSession.close(); } iDistanceMetric = new DistanceMetric(iConfig); TravelTime.populateTravelTimes(iDistanceMetric, sessionId); iLog.info("Config: " + ToolBox.dict2string(iConfig, 2)); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "OnlineSectioningServerImpl"
"OnlineSectioningServerImpl(Long sessionId, boolean waitTillStarted) throws SectioningException { org.hibernate.Session hibSession = SessionDAO.getInstance().createNewSession(); try { Session session = SessionDAO.getInstance().get(sessionId, hibSession); if (session == null) throw new SectioningException(MSG.exceptionSessionDoesNotExist(sessionId == null ? "null" : sessionId.toString())); iAcademicSession = new AcademicSessionInfo(session); iLog = LogFactory.getLog(OnlineSectioningServerImpl.class.getName() + ".server[" + iAcademicSession.toCompactString() + "]"); iMultiLock = new MultiLock(iAcademicSession); iExecutor = new AsyncExecutor(); iExecutor.start(); final OnlineSectioningLog.Entity user = OnlineSectioningLog.Entity.newBuilder() .setExternalId(StudentClassEnrollment.SystemChange.SYSTEM.name()) .setName(StudentClassEnrollment.SystemChange.SYSTEM.getName()) .setType(OnlineSectioningLog.Entity.EntityType.OTHER).build(); if (waitTillStarted) { try { execute(new ReloadAllData(), user); } catch (Throwable exception) { iLog.error("Failed to load server: " + exception.getMessage(), exception); throw exception; } if (iAcademicSession.isSectioningEnabled()) { try { execute(new CheckAllOfferingsAction(), user); } catch (Throwable exception) { iLog.error("Failed to check all offerings: " + exception.getMessage(), exception); throw exception; } } } else { execute(new ReloadAllData(), user, new ServerCallback<Boolean>() { @Override public void onSuccess(Boolean result) { if (iAcademicSession.isSectioningEnabled()) execute(new CheckAllOfferingsAction(), user, new ServerCallback<Boolean>() { @Override public void onSuccess(Boolean result) {} @Override public void onFailure(Throwable exception) { iLog.error("Failed to check all offerings: " + exception.getMessage(), exception); } }); } @Override public void onFailure(Throwable exception) { iLog.error("Failed to load server: " + exception.getMessage(), exception); } }); } } catch (Throwable t) { if (t instanceof SectioningException) throw (SectioningException)t; throw new SectioningException(MSG.exceptionUnknown(t.getMessage()), t); } finally { hibSession.close(); } <MASK>iConfig = new ServerConfig();</MASK> iDistanceMetric = new DistanceMetric(iConfig); TravelTime.populateTravelTimes(iDistanceMetric, sessionId); iLog.info("Config: " + ToolBox.dict2string(iConfig, 2)); }"
Inversion-Mutation
megadiff
"protected Resource resolve(String location) { Resource resource = null; Matcher matcher = VAR_REPLACE_REGEX.matcher(location); boolean allValuesReplaced = true; StringBuffer sb = new StringBuffer(); while (matcher.find()) { boolean env = matcher.group(1) != null; String key = matcher.group(2); String value; if (env) { // Resolve an environment variable value = envMap.get(key); } else { // System property value = System.getProperty(key); } allValuesReplaced &= (value != null); if (!allValuesReplaced) { break; } matcher.appendReplacement(sb, Matcher.quoteReplacement(value)); } matcher.appendTail(sb); if (allValuesReplaced) { String url = sb.toString(); if (applicationContext != null) { resource = applicationContext.getResource(url); } else { try { resource = new UrlResource(url); } catch (MalformedURLException e) { // Ignore if (log.isWarnEnabled()) { log.warn(format("Failed to parse URL '%s'", url), e); } } } if (!resource.exists()) { resource = null; } } return resource; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "resolve"
"protected Resource resolve(String location) { Resource resource = null; Matcher matcher = VAR_REPLACE_REGEX.matcher(location); boolean allValuesReplaced = true; StringBuffer sb = new StringBuffer(); while (matcher.find()) { boolean env = matcher.group(1) != null; String key = matcher.group(2); String value; if (env) { // Resolve an environment variable value = envMap.get(key); } else { // System property value = System.getProperty(key); } allValuesReplaced &= (value != null); if (!allValuesReplaced) { break; } matcher.appendReplacement(sb, Matcher.quoteReplacement(value)); <MASK>matcher.appendTail(sb);</MASK> } if (allValuesReplaced) { String url = sb.toString(); if (applicationContext != null) { resource = applicationContext.getResource(url); } else { try { resource = new UrlResource(url); } catch (MalformedURLException e) { // Ignore if (log.isWarnEnabled()) { log.warn(format("Failed to parse URL '%s'", url), e); } } } if (!resource.exists()) { resource = null; } } return resource; }"
Inversion-Mutation
megadiff
"private void checkSearch(Intent intent){ if (Intent.ACTION_SEARCH.equals(intent.getAction())) { String query = intent.getStringExtra(SearchManager.QUERY); Log.d("basti", "Search String: " + query); SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this, SelectScreenSavedSearches.AUTHORITY, SelectScreenSavedSearches.MODE); suggestions.saveRecentQuery(query, null); if(searchForSearchResults(classSpinner, query))return; if(searchForSearchResults(teacherSpinner, query))return; if(searchForSearchResults(roomSpinner, query))return; if(searchForSearchResults(subjectSpinner, query))return; Toast.makeText(this, getResources().getString(R.string.selectscreen_search_fail), Toast.LENGTH_SHORT).show(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "checkSearch"
"private void checkSearch(Intent intent){ if (Intent.ACTION_SEARCH.equals(intent.getAction())) { String query = intent.getStringExtra(SearchManager.QUERY); Log.d("basti", "Search String: " + query); SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this, SelectScreenSavedSearches.AUTHORITY, SelectScreenSavedSearches.MODE); suggestions.saveRecentQuery(query, null); if(searchForSearchResults(classSpinner, query))return; <MASK>if(searchForSearchResults(roomSpinner, query))return;</MASK> if(searchForSearchResults(teacherSpinner, query))return; if(searchForSearchResults(subjectSpinner, query))return; Toast.makeText(this, getResources().getString(R.string.selectscreen_search_fail), Toast.LENGTH_SHORT).show(); } }"
Inversion-Mutation
megadiff
"public void run() { FileConnection file = null; InputStream is = null; Image capturedImage = null; try { file = (FileConnection) Connector.open("file://" + imagePath, Connector.READ_WRITE); is = file.openInputStream(); capturedImage = Image.createImage(is); } catch (IOException e) { Log.error("Problem creating image: " + e); removeProgressBar(); invalidate(); showMessage("An error occured processing the image."); return; } finally { try { if (is != null) { is.close(); } if (file != null && file.exists()) { if (file.isOpen()) { file.delete(); file.close(); } Log.info("Deleted image file."); } } catch (IOException ioe) { Log.error("Error while closing file: " + ioe); } } if (capturedImage != null) { Log.info("Got image..."); LuminanceSource source = new LCDUIImageLuminanceSource(capturedImage); BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source)); Result result; ReasonableTimer decodingTimer = null; try { decodingTimer = new ReasonableTimer(); Log.info("Attempting to decode image..."); result = reader.decode(bitmap, readerHints); decodingTimer.finished(); } catch (ReaderException e) { Log.error("Could not decode image: " + e); decodingTimer.finished(); removeProgressBar(); invalidate(); boolean showResolutionMsg = !AppSettings.getInstance().getBooleanItem(AppSettings.SETTING_CAM_RES_MSG).booleanValue(); if (showResolutionMsg) { showMessage("A QR Code was not found in the image. " + "We detected that the decoding process took quite a while. " + "It will be much faster if you decrease your camera's resolution (640x480)."); } else { showMessage("A QR Code was not found in the image."); } return; } if (result != null) { String resultText = result.getText(); Log.info("result: " + resultText); if (isURI(resultText)) { resultText = URLDecoder.decode(resultText); removeProgressBar(); invalidate(); if (!decodingTimer.wasResonableTime() && !AppSettings.getInstance().getBooleanItem(AppSettings.SETTING_CAM_RES_MSG).booleanValue()) { showMessage("We detected that the decoding process took quite a while. " + "It will be much faster if you decrease your camera's resolution (640x480)."); } DecodeHistory.getInstance().addHistoryItem(new DecodeHistoryItem(resultText)); invokeBrowser(resultText); return; } } else { removeProgressBar(); invalidate(); showMessage("A QR Code was not found in the image."); return; } } removeProgressBar(); invalidate(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"public void run() { FileConnection file = null; InputStream is = null; Image capturedImage = null; try { file = (FileConnection) Connector.open("file://" + imagePath, Connector.READ_WRITE); is = file.openInputStream(); capturedImage = Image.createImage(is); } catch (IOException e) { Log.error("Problem creating image: " + e); removeProgressBar(); invalidate(); showMessage("An error occured processing the image."); return; } finally { try { if (is != null) { is.close(); } if (file != null && file.exists()) { if (file.isOpen()) { file.close(); } <MASK>file.delete();</MASK> Log.info("Deleted image file."); } } catch (IOException ioe) { Log.error("Error while closing file: " + ioe); } } if (capturedImage != null) { Log.info("Got image..."); LuminanceSource source = new LCDUIImageLuminanceSource(capturedImage); BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source)); Result result; ReasonableTimer decodingTimer = null; try { decodingTimer = new ReasonableTimer(); Log.info("Attempting to decode image..."); result = reader.decode(bitmap, readerHints); decodingTimer.finished(); } catch (ReaderException e) { Log.error("Could not decode image: " + e); decodingTimer.finished(); removeProgressBar(); invalidate(); boolean showResolutionMsg = !AppSettings.getInstance().getBooleanItem(AppSettings.SETTING_CAM_RES_MSG).booleanValue(); if (showResolutionMsg) { showMessage("A QR Code was not found in the image. " + "We detected that the decoding process took quite a while. " + "It will be much faster if you decrease your camera's resolution (640x480)."); } else { showMessage("A QR Code was not found in the image."); } return; } if (result != null) { String resultText = result.getText(); Log.info("result: " + resultText); if (isURI(resultText)) { resultText = URLDecoder.decode(resultText); removeProgressBar(); invalidate(); if (!decodingTimer.wasResonableTime() && !AppSettings.getInstance().getBooleanItem(AppSettings.SETTING_CAM_RES_MSG).booleanValue()) { showMessage("We detected that the decoding process took quite a while. " + "It will be much faster if you decrease your camera's resolution (640x480)."); } DecodeHistory.getInstance().addHistoryItem(new DecodeHistoryItem(resultText)); invokeBrowser(resultText); return; } } else { removeProgressBar(); invalidate(); showMessage("A QR Code was not found in the image."); return; } } removeProgressBar(); invalidate(); }"
Inversion-Mutation
megadiff
"public DataExportPopupMenu() { if (validateUserHasNasAccess()) { this.add(createNASMenuItem()); } if (validateUserHasButler1Access()) { this.add(createButler2MenuItem()); this.add(createButler1MenuItem()); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "DataExportPopupMenu"
"public DataExportPopupMenu() { if (validateUserHasNasAccess()) { this.add(createNASMenuItem()); } if (validateUserHasButler1Access()) { <MASK>this.add(createButler1MenuItem());</MASK> this.add(createButler2MenuItem()); } }"
Inversion-Mutation
megadiff
"public InitialAccountRegistrationFrame() { setDefaultCloseOperation(DISPOSE_ON_CLOSE); MainPanel mainPanel = new MainPanel(new BorderLayout(5, 5)); JPanel messageAreaPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); JTextArea messageArea = new JTextArea(Resources.getString("initialAccountRegistration")); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JButton cancelButton = new JButton(Resources.getString("cancel")); this.setTitle(Resources.getString("signin")); mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); this.getContentPane().add(mainPanel); mainPanel.add(messageAreaPanel, BorderLayout.NORTH); mainPanel.add(mainAccountsPanel, BorderLayout.CENTER); mainPanel.add(buttonPanel, BorderLayout.SOUTH); messageAreaPanel.add(messageArea); messageArea.setPreferredSize(new Dimension(350, 20)); messageArea.setFont(messageArea.getFont().deriveFont(Font.BOLD)); mainAccountsPanel.add(accountsPanel, BorderLayout.CENTER); mainAccountsPanel.setOpaque(false); accountsPanel.setOpaque(false); buttonPanel.setOpaque(false); messageArea.setOpaque(false); messageAreaPanel.setOpaque(false); SigninActionListener actionListener = new SigninActionListener(); signinButton.addActionListener(actionListener); cancelButton.addActionListener(actionListener); buttonPanel.add(signinButton); buttonPanel.add(cancelButton); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); messageArea.setOpaque(false); this.getRootPane().setDefaultButton(signinButton); this.initAccountWizards(); // Create the default group String groupName = Resources.getApplicationProperty("defaultGroupName"); if(groupName != null && groupName.length() > 0) { MetaContactListService contactList = SimpleAccountRegistrationActivator.getContactList(); Iterator iter = contactList.getRoot().getSubgroups(); while (iter.hasNext()) { MetaContactGroup gr = (MetaContactGroup) iter.next(); if (groupName.equals(gr.getGroupName())) return; } contactList .createMetaContactGroup(contactList.getRoot(), groupName); getConfigurationService() .setProperty( "net.java.sip.communicator.impl.gui.addcontact.lastContactParent", groupName); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "InitialAccountRegistrationFrame"
"public InitialAccountRegistrationFrame() { setDefaultCloseOperation(DISPOSE_ON_CLOSE); MainPanel mainPanel = new MainPanel(new BorderLayout(5, 5)); JPanel messageAreaPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); JTextArea messageArea = new JTextArea(Resources.getString("initialAccountRegistration")); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JButton cancelButton = new JButton(Resources.getString("cancel")); this.setTitle(Resources.getString("signin")); mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); this.getContentPane().add(mainPanel); mainPanel.add(messageAreaPanel, BorderLayout.NORTH); mainPanel.add(mainAccountsPanel, BorderLayout.CENTER); mainPanel.add(buttonPanel, BorderLayout.SOUTH); messageAreaPanel.add(messageArea); messageArea.setPreferredSize(new Dimension(350, 20)); messageArea.setFont(messageArea.getFont().deriveFont(Font.BOLD)); mainAccountsPanel.add(accountsPanel, BorderLayout.CENTER); mainAccountsPanel.setOpaque(false); accountsPanel.setOpaque(false); buttonPanel.setOpaque(false); messageArea.setOpaque(false); messageAreaPanel.setOpaque(false); SigninActionListener actionListener = new SigninActionListener(); signinButton.addActionListener(actionListener); cancelButton.addActionListener(actionListener); <MASK>buttonPanel.add(cancelButton);</MASK> buttonPanel.add(signinButton); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); messageArea.setOpaque(false); this.getRootPane().setDefaultButton(signinButton); this.initAccountWizards(); // Create the default group String groupName = Resources.getApplicationProperty("defaultGroupName"); if(groupName != null && groupName.length() > 0) { MetaContactListService contactList = SimpleAccountRegistrationActivator.getContactList(); Iterator iter = contactList.getRoot().getSubgroups(); while (iter.hasNext()) { MetaContactGroup gr = (MetaContactGroup) iter.next(); if (groupName.equals(gr.getGroupName())) return; } contactList .createMetaContactGroup(contactList.getRoot(), groupName); getConfigurationService() .setProperty( "net.java.sip.communicator.impl.gui.addcontact.lastContactParent", groupName); } }"
Inversion-Mutation
megadiff
"public void run(IProgressMonitor monitor) throws InterruptedException { monitor.beginTask(NLS.bind(Messages.DeleteProjectActionDeleting, new Object[] {m_project.getName(), m_project.getMajorProjectVersion(), m_project.getMinorProjectVersion()}), getTotalWork()); try { boolean isRefreshRequired = false; if (!m_deleteCurrentProject) { isRefreshRequired = isRefreshRequired(m_project.getGuid(), m_project.getMajorProjectVersion(), m_project.getMinorProjectVersion()); } if (m_deleteCurrentProject) { Plugin.getDisplay().syncExec(new Runnable() { public void run() { Plugin.closeAllOpenedJubulaEditors(false); } }); } // Register Persistence (JPA / EclipseLink) progress listeners ProgressMonitorTracker.getInstance().setProgressMonitor( monitor); ProjectPM.deleteProject(m_project, m_deleteCurrentProject); final String jobName = Messages.UIJobDeletingTestResultDetails; Job job = new Job(jobName) { public IStatus run(IProgressMonitor mon) { mon.beginTask(jobName, IProgressMonitor.UNKNOWN); if (m_keepTestresultSummary) { TestResultSummaryPM.deleteTestrunsByProject( m_project.getGuid(), m_project.getMajorProjectVersion(), m_project.getMinorProjectVersion(), true); } else { TestResultSummaryPM.deleteTestrunsByProject( m_project.getGuid(), m_project.getMajorProjectVersion(), m_project.getMinorProjectVersion(), false); } mon.done(); DataEventDispatcher.getInstance() .fireTestresultChanged(TestresultState.Refresh); return Status.OK_STATUS; } }; if (m_deleteCurrentProject) { Utils.clearClient(); GeneralStorage.getInstance().setProject(null); DataEventDispatcher.getInstance() .fireDataChangedListener(m_project, DataState.Deleted, UpdateState.all); } else if (isRefreshRequired) { GeneralStorage.getInstance().reloadMasterSession( new NullProgressMonitor()); } job.schedule(); } catch (PMException e) { PMExceptionHandler.handlePMExceptionForMasterSession(e); return; } catch (ProjectDeletedException e) { PMExceptionHandler.handleGDProjectDeletedException(); return; } catch (JBException e) { ErrorHandlingUtil.createMessageDialog(e, null, null); } finally { // Remove JPA progress listeners ProgressMonitorTracker.getInstance().setProgressMonitor(null); monitor.done(); Plugin.stopLongRunning(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"public void run(IProgressMonitor monitor) throws InterruptedException { monitor.beginTask(NLS.bind(Messages.DeleteProjectActionDeleting, new Object[] {m_project.getName(), m_project.getMajorProjectVersion(), m_project.getMinorProjectVersion()}), getTotalWork()); try { boolean isRefreshRequired = false; if (!m_deleteCurrentProject) { isRefreshRequired = isRefreshRequired(m_project.getGuid(), m_project.getMajorProjectVersion(), m_project.getMinorProjectVersion()); } if (m_deleteCurrentProject) { Plugin.getDisplay().syncExec(new Runnable() { public void run() { Plugin.closeAllOpenedJubulaEditors(false); } }); } // Register Persistence (JPA / EclipseLink) progress listeners ProgressMonitorTracker.getInstance().setProgressMonitor( monitor); ProjectPM.deleteProject(m_project, m_deleteCurrentProject); final String jobName = Messages.UIJobDeletingTestResultDetails; Job job = new Job(jobName) { public IStatus run(IProgressMonitor mon) { mon.beginTask(jobName, IProgressMonitor.UNKNOWN); if (m_keepTestresultSummary) { TestResultSummaryPM.deleteTestrunsByProject( m_project.getGuid(), m_project.getMajorProjectVersion(), m_project.getMinorProjectVersion(), true); } else { TestResultSummaryPM.deleteTestrunsByProject( m_project.getGuid(), m_project.getMajorProjectVersion(), m_project.getMinorProjectVersion(), false); } mon.done(); DataEventDispatcher.getInstance() .fireTestresultChanged(TestresultState.Refresh); return Status.OK_STATUS; } }; <MASK>job.schedule();</MASK> if (m_deleteCurrentProject) { Utils.clearClient(); GeneralStorage.getInstance().setProject(null); DataEventDispatcher.getInstance() .fireDataChangedListener(m_project, DataState.Deleted, UpdateState.all); } else if (isRefreshRequired) { GeneralStorage.getInstance().reloadMasterSession( new NullProgressMonitor()); } } catch (PMException e) { PMExceptionHandler.handlePMExceptionForMasterSession(e); return; } catch (ProjectDeletedException e) { PMExceptionHandler.handleGDProjectDeletedException(); return; } catch (JBException e) { ErrorHandlingUtil.createMessageDialog(e, null, null); } finally { // Remove JPA progress listeners ProgressMonitorTracker.getInstance().setProgressMonitor(null); monitor.done(); Plugin.stopLongRunning(); } }"
Inversion-Mutation
megadiff
"private SSLSocketFactory createSSLSocketFactory() { InputStream keyStoreIS = null; try { final SSLContext sslContext = SSLContext.getInstance(this.sslConfiguration.getProperty("protocol", "SSL")); if (this.sslConfiguration.getProperty("keyStoreType") != null) { final KeyStore keyStore = KeyStore.getInstance(this.sslConfiguration.getProperty("keyStoreType")); if (this.sslConfiguration.getProperty("keyStorePath") != null) { keyStoreIS = new FileInputStream(this.sslConfiguration.getProperty("keyStorePath")); if (this.sslConfiguration.getProperty("keyStorePass") != null) { keyStore.load(keyStoreIS, this.sslConfiguration.getProperty("keyStorePass").toCharArray()); LOGGER.debug("Keystore has {} keys", keyStore.size()); final KeyManagerFactory keyManager = KeyManagerFactory.getInstance(this.sslConfiguration.getProperty("keyManagerType", "SunX509")); keyManager.init(keyStore, this.sslConfiguration.getProperty("certificatePassword").toCharArray()); sslContext.init(keyManager.getKeyManagers(), null, null); return sslContext.getSocketFactory(); } } } } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } finally { CommonUtils.closeQuietly(keyStoreIS); } return null; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createSSLSocketFactory"
"private SSLSocketFactory createSSLSocketFactory() { InputStream keyStoreIS = null; try { final SSLContext sslContext = SSLContext.getInstance(this.sslConfiguration.getProperty("protocol", "SSL")); if (this.sslConfiguration.getProperty("keyStoreType") != null) { final KeyStore keyStore = KeyStore.getInstance(this.sslConfiguration.getProperty("keyStoreType")); if (this.sslConfiguration.getProperty("keyStorePath") != null) { keyStoreIS = new FileInputStream(this.sslConfiguration.getProperty("keyStorePath")); if (this.sslConfiguration.getProperty("keyStorePass") != null) { keyStore.load(keyStoreIS, this.sslConfiguration.getProperty("keyStorePass").toCharArray()); LOGGER.debug("Keystore has {} keys", keyStore.size()); final KeyManagerFactory keyManager = KeyManagerFactory.getInstance(this.sslConfiguration.getProperty("keyManagerType", "SunX509")); keyManager.init(keyStore, this.sslConfiguration.getProperty("certificatePassword").toCharArray()); sslContext.init(keyManager.getKeyManagers(), null, null); } } } <MASK>return sslContext.getSocketFactory();</MASK> } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } finally { CommonUtils.closeQuietly(keyStoreIS); } return null; }"
Inversion-Mutation
megadiff
"public CoreTexture2D( @Nonnull final CoreGL gl, @Nonnull final BufferFactory bufferFactory, final int textureId, final int target, final int level, final int internalFormat, final int width, final int height, final int border, final int format, final int type, @Nonnull final Buffer data, final int magFilter, final int minFilter) { this.gl = gl; this.textureId = createTexture( textureId, target, level, internalFormat, width, height, border, format, type, data, magFilter, minFilter); textureIdBuffer = bufferFactory.createNativeOrderedIntBuffer(1); textureTarget = target; this.width = width; this.height = height; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "CoreTexture2D"
"public CoreTexture2D( @Nonnull final CoreGL gl, @Nonnull final BufferFactory bufferFactory, final int textureId, final int target, final int level, final int internalFormat, final int width, final int height, final int border, final int format, final int type, @Nonnull final Buffer data, final int magFilter, final int minFilter) { this.textureId = createTexture( textureId, target, level, internalFormat, width, height, border, format, type, data, magFilter, minFilter); <MASK>this.gl = gl;</MASK> textureIdBuffer = bufferFactory.createNativeOrderedIntBuffer(1); textureTarget = target; this.width = width; this.height = height; }"
Inversion-Mutation
megadiff
"@Override public boolean onTouchEvent(MotionEvent event) { if ( !isTouchScreenEnabled ) { return true; } int x = (int)event.getX(); int y = (int)event.getY(); int dx = getWidth(); int dy = getHeight(); int START_DRAG_THRESHOLD = mActivity.getPalmTipPixels(); final int zone = getTapZone(x, y, dx, dy); if ( event.getAction()==MotionEvent.ACTION_UP ) { longTouchId++; if ( selectionInProgress ) { Log.v("cr3", "touch ACTION_UP: selection finished"); selectionEndX = x; selectionEndY = y; updateSelection( selectionStartX, selectionStartY, selectionEndX, selectionEndY, true ); selectionInProgress = false; selectionModeActive = false; // TODO: multiple selection mode return true; } if ( touchEventIgnoreNextUp ) return true; mActivity.onUserActivity(); unhiliteTapZone(); boolean isLongPress = (event.getEventTime()-event.getDownTime())>LONG_KEYPRESS_TIME; stopAnimation(x, y); stopBrightnessControl(x, y); if ( isManualScrollActive || isBrightnessControlActive ) { isManualScrollActive = false; isBrightnessControlActive = false; manualScrollStartPosX = manualScrollStartPosY = -1; return true; } if ( isLongPress || !doubleTapSelectionEnabled ) { currentDoubleTapActionStart = 0; if ( !isLongPress ) onTapZone( zone, isLongPress ); else { onLongTap( x, y, zone ); } } else { currentDoubleTapActionStart = android.os.SystemClock.uptimeMillis(); final long myStart = currentDoubleTapActionStart; BackgroundThread.instance().postGUI(new Runnable() { @Override public void run() { if ( currentDoubleTapActionStart == myStart ) { onTapZone( zone, false ); } currentDoubleTapActionStart = 0; } }, DOUBLE_CLICK_INTERVAL); } return true; } else if ( event.getAction()==MotionEvent.ACTION_DOWN ) { touchEventIgnoreNextUp = false; if ( selectionModeActive || currentDoubleTapActionStart + DOUBLE_CLICK_INTERVAL > android.os.SystemClock.uptimeMillis() ) { Log.v("cr3", "touch ACTION_DOWN: double tap: starting selection"); // double tap started selectionInProgress = true; longTouchId++; selectionStartX = x; selectionStartY = y; selectionEndX = x; selectionEndY = y; currentDoubleTapActionStart = 0; updateSelection( selectionStartX, selectionStartY, selectionEndX, selectionEndY, false ); return true; } currentDoubleTapActionStart = 0; selectionInProgress = false; manualScrollStartPosX = x; manualScrollStartPosY = y; currentDoubleTapActionStart = 0; if ( hiliteTapZoneOnTap ) { hiliteTapZone( true, x, y, dx, dy ); scheduleUnhilite( LONG_KEYPRESS_TIME ); } final int myId = ++longTouchId; mBackThread.postGUI( new Runnable() { @Override public void run() { Log.v("cr3", "onTouchEvent: long tap delayed event myId=" + myId + ", currentId=" + longTouchId); if ( myId==longTouchId ) { touchEventIgnoreNextUp = true; isBrightnessControlActive = false; isManualScrollActive = false; onLongTap( manualScrollStartPosX, manualScrollStartPosY, zone ); manualScrollStartPosX = manualScrollStartPosY = -1; } } }, LONG_KEYPRESS_TIME); return true; } else if ( event.getAction()==MotionEvent.ACTION_MOVE) { if ( selectionInProgress ) { Log.v("cr3", "touch ACTION_MOVE: updating selection"); selectionEndX = x; selectionEndY = y; updateSelection( selectionStartX, selectionStartY, selectionEndX, selectionEndY, false ); return true; } if ( !isManualScrollActive && !isBrightnessControlActive && manualScrollStartPosX>=0 && manualScrollStartPosY>=0 ) { int deltax = manualScrollStartPosX - x; int deltay = manualScrollStartPosY - y; deltax = deltax < 0 ? -deltax : deltax; deltay = deltay < 0 ? -deltay : deltay; if ( deltax + deltay > START_DRAG_THRESHOLD ) { Log.v("cr3", "onTouchEvent: move threshold reached"); longTouchId++; if ( manualScrollStartPosX < START_DRAG_THRESHOLD * 170 / 100 && deltay>deltax && isBacklightControlWithLeftScreenEdgeEnabled ) { // brightness isBrightnessControlActive = true; startBrightnessControl(x, y); return true; } else { // scroll isManualScrollActive = true; startAnimation(manualScrollStartPosX, manualScrollStartPosY, dx, dy); updateAnimation(x, y); return true; } } } if ( isManualScrollActive ) updateAnimation(x, y); else if ( isBrightnessControlActive ) updateBrightnessControl(x, y); return true; } else if ( event.getAction()==MotionEvent.ACTION_OUTSIDE ) { if ( selectionInProgress ) { // cancel selection cancelSelection(); } isManualScrollActive = false; isBrightnessControlActive = false; selectionModeActive = false; currentDoubleTapActionStart = 0; longTouchId++; stopAnimation(-1, -1); stopBrightnessControl(-1, -1); hiliteTapZone( false, x, y, dx, dy ); } return true; //return super.onTouchEvent(event); }"
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) { if ( !isTouchScreenEnabled ) { return true; } int x = (int)event.getX(); int y = (int)event.getY(); int dx = getWidth(); int dy = getHeight(); int START_DRAG_THRESHOLD = mActivity.getPalmTipPixels(); final int zone = getTapZone(x, y, dx, dy); if ( event.getAction()==MotionEvent.ACTION_UP ) { longTouchId++; if ( selectionInProgress ) { Log.v("cr3", "touch ACTION_UP: selection finished"); selectionEndX = x; selectionEndY = y; updateSelection( selectionStartX, selectionStartY, selectionEndX, selectionEndY, true ); selectionInProgress = false; selectionModeActive = false; // TODO: multiple selection mode return true; } if ( touchEventIgnoreNextUp ) return true; mActivity.onUserActivity(); unhiliteTapZone(); boolean isLongPress = (event.getEventTime()-event.getDownTime())>LONG_KEYPRESS_TIME; stopAnimation(x, y); stopBrightnessControl(x, y); if ( isManualScrollActive || isBrightnessControlActive ) { isManualScrollActive = false; isBrightnessControlActive = false; <MASK>manualScrollStartPosX = manualScrollStartPosY = -1;</MASK> return true; } if ( isLongPress || !doubleTapSelectionEnabled ) { currentDoubleTapActionStart = 0; if ( !isLongPress ) onTapZone( zone, isLongPress ); else { onLongTap( x, y, zone ); } } else { currentDoubleTapActionStart = android.os.SystemClock.uptimeMillis(); final long myStart = currentDoubleTapActionStart; BackgroundThread.instance().postGUI(new Runnable() { @Override public void run() { if ( currentDoubleTapActionStart == myStart ) { onTapZone( zone, false ); } currentDoubleTapActionStart = 0; } }, DOUBLE_CLICK_INTERVAL); } return true; } else if ( event.getAction()==MotionEvent.ACTION_DOWN ) { touchEventIgnoreNextUp = false; if ( selectionModeActive || currentDoubleTapActionStart + DOUBLE_CLICK_INTERVAL > android.os.SystemClock.uptimeMillis() ) { Log.v("cr3", "touch ACTION_DOWN: double tap: starting selection"); // double tap started selectionInProgress = true; longTouchId++; selectionStartX = x; selectionStartY = y; selectionEndX = x; selectionEndY = y; currentDoubleTapActionStart = 0; updateSelection( selectionStartX, selectionStartY, selectionEndX, selectionEndY, false ); return true; } currentDoubleTapActionStart = 0; selectionInProgress = false; manualScrollStartPosX = x; manualScrollStartPosY = y; currentDoubleTapActionStart = 0; if ( hiliteTapZoneOnTap ) { hiliteTapZone( true, x, y, dx, dy ); scheduleUnhilite( LONG_KEYPRESS_TIME ); } final int myId = ++longTouchId; mBackThread.postGUI( new Runnable() { @Override public void run() { Log.v("cr3", "onTouchEvent: long tap delayed event myId=" + myId + ", currentId=" + longTouchId); if ( myId==longTouchId ) { touchEventIgnoreNextUp = true; isBrightnessControlActive = false; isManualScrollActive = false; <MASK>manualScrollStartPosX = manualScrollStartPosY = -1;</MASK> onLongTap( manualScrollStartPosX, manualScrollStartPosY, zone ); } } }, LONG_KEYPRESS_TIME); return true; } else if ( event.getAction()==MotionEvent.ACTION_MOVE) { if ( selectionInProgress ) { Log.v("cr3", "touch ACTION_MOVE: updating selection"); selectionEndX = x; selectionEndY = y; updateSelection( selectionStartX, selectionStartY, selectionEndX, selectionEndY, false ); return true; } if ( !isManualScrollActive && !isBrightnessControlActive && manualScrollStartPosX>=0 && manualScrollStartPosY>=0 ) { int deltax = manualScrollStartPosX - x; int deltay = manualScrollStartPosY - y; deltax = deltax < 0 ? -deltax : deltax; deltay = deltay < 0 ? -deltay : deltay; if ( deltax + deltay > START_DRAG_THRESHOLD ) { Log.v("cr3", "onTouchEvent: move threshold reached"); longTouchId++; if ( manualScrollStartPosX < START_DRAG_THRESHOLD * 170 / 100 && deltay>deltax && isBacklightControlWithLeftScreenEdgeEnabled ) { // brightness isBrightnessControlActive = true; startBrightnessControl(x, y); return true; } else { // scroll isManualScrollActive = true; startAnimation(manualScrollStartPosX, manualScrollStartPosY, dx, dy); updateAnimation(x, y); return true; } } } if ( isManualScrollActive ) updateAnimation(x, y); else if ( isBrightnessControlActive ) updateBrightnessControl(x, y); return true; } else if ( event.getAction()==MotionEvent.ACTION_OUTSIDE ) { if ( selectionInProgress ) { // cancel selection cancelSelection(); } isManualScrollActive = false; isBrightnessControlActive = false; selectionModeActive = false; currentDoubleTapActionStart = 0; longTouchId++; stopAnimation(-1, -1); stopBrightnessControl(-1, -1); hiliteTapZone( false, x, y, dx, dy ); } return true; //return super.onTouchEvent(event); }"
Inversion-Mutation
megadiff
"@Override public void run() { Log.v("cr3", "onTouchEvent: long tap delayed event myId=" + myId + ", currentId=" + longTouchId); if ( myId==longTouchId ) { touchEventIgnoreNextUp = true; isBrightnessControlActive = false; isManualScrollActive = false; onLongTap( manualScrollStartPosX, manualScrollStartPosY, zone ); manualScrollStartPosX = manualScrollStartPosY = -1; } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"@Override public void run() { Log.v("cr3", "onTouchEvent: long tap delayed event myId=" + myId + ", currentId=" + longTouchId); if ( myId==longTouchId ) { touchEventIgnoreNextUp = true; isBrightnessControlActive = false; isManualScrollActive = false; <MASK>manualScrollStartPosX = manualScrollStartPosY = -1;</MASK> onLongTap( manualScrollStartPosX, manualScrollStartPosY, zone ); } }"
Inversion-Mutation
megadiff
"public static void query(String query) throws IllegalArgumentException, IllegalAccessException { flash.put("query", query); List<Object> exeResult = new ArrayList<Object>(); // Try to exe the query try { Query exeQuery = JPA.em().createQuery(query); exeResult.addAll(exeQuery.getResultList()); } catch (Exception e) { renderArgs.put("error", e.getMessage()); renderTemplate("Tester/queryempty.html"); } // The query is empty if (exeResult.size() == 0) { renderArgs.put("error", "The query did not match any items."); renderTemplate("Tester/queryempty.html"); } // We got results List<Field> fields = Arrays.asList(exeResult.get(0).getClass() .getFields()); List<Object> items = new ArrayList<Object>(); for (int i = -1; i < exeResult.size(); i++) { List<String> values = new ArrayList<String>(); for (int j = 0; j < fields.size(); j++) { if (i == -1) { values.add(fields.get(j).getName()); } else { values.add("" + fields.get(j).get(exeResult.get(i))); } } items.add(values); } renderArgs.put("results", items); renderTemplate("Tester/queryresult.html"); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "query"
"public static void query(String query) throws IllegalArgumentException, IllegalAccessException { flash.put("query", query); <MASK>Query exeQuery = JPA.em().createQuery(query);</MASK> List<Object> exeResult = new ArrayList<Object>(); // Try to exe the query try { exeResult.addAll(exeQuery.getResultList()); } catch (Exception e) { renderArgs.put("error", e.getMessage()); renderTemplate("Tester/queryempty.html"); } // The query is empty if (exeResult.size() == 0) { renderArgs.put("error", "The query did not match any items."); renderTemplate("Tester/queryempty.html"); } // We got results List<Field> fields = Arrays.asList(exeResult.get(0).getClass() .getFields()); List<Object> items = new ArrayList<Object>(); for (int i = -1; i < exeResult.size(); i++) { List<String> values = new ArrayList<String>(); for (int j = 0; j < fields.size(); j++) { if (i == -1) { values.add(fields.get(j).getName()); } else { values.add("" + fields.get(j).get(exeResult.get(i))); } } items.add(values); } renderArgs.put("results", items); renderTemplate("Tester/queryresult.html"); }"
Inversion-Mutation
megadiff
"public Object visitClassNode(ClassNode visited) { FormatterClassNode classNode = new FormatterClassNode(document); SourcePosition position = visited.getPosition(); classNode.setBegin(builder.createTextNode(document, position.getStartOffset(), visited.getCPath().getPosition() .getStartOffset())); builder.push(classNode); // visitChildren(visited); Node bodyNode = visited.getBodyNode(); int bodyEndOffset; if (NodeType.NILNODE.equals(bodyNode.getNodeType())) { bodyEndOffset = classNode.getEndOffset(); } else { bodyNode.accept(this); bodyEndOffset = bodyNode.getPosition().getEndOffset(); } builder.checkedPop(classNode, bodyEndOffset); classNode.setEnd(builder.createTextNode(document, bodyEndOffset, position.getEndOffset())); return null; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "visitClassNode"
"public Object visitClassNode(ClassNode visited) { FormatterClassNode classNode = new FormatterClassNode(document); SourcePosition position = visited.getPosition(); classNode.setBegin(builder.createTextNode(document, position.getStartOffset(), visited.getCPath().getPosition() .getStartOffset())); builder.push(classNode); // visitChildren(visited); Node bodyNode = visited.getBodyNode(); <MASK>bodyNode.accept(this);</MASK> int bodyEndOffset; if (NodeType.NILNODE.equals(bodyNode.getNodeType())) { bodyEndOffset = classNode.getEndOffset(); } else { bodyEndOffset = bodyNode.getPosition().getEndOffset(); } builder.checkedPop(classNode, bodyEndOffset); classNode.setEnd(builder.createTextNode(document, bodyEndOffset, position.getEndOffset())); return null; }"
Inversion-Mutation
megadiff
"private void storeHistory(ConnectionResource conn, History history, Repository repository) throws SQLException { Integer reposId = null; Map<String, Integer> authors = null; Map<String, Integer> files = null; PreparedStatement addChangeset = null; PreparedStatement addFilechange = null; for (int i = 0;; i++) { try { if (reposId == null) { reposId = getRepositoryId(conn, repository); conn.commit(); } if (authors == null) { authors = getAuthors(conn, history, reposId); conn.commit(); } if (files == null) { files = getFiles(conn, history, reposId); conn.commit(); } if (addChangeset == null) { addChangeset = conn.getStatement(ADD_CHANGESET); } if (addFilechange == null) { addFilechange = conn.getStatement(ADD_FILECHANGE); } // Success! Break out of the loop. break; } catch (SQLException sqle) { handleSQLException(sqle, i); conn.rollback(); } } addChangeset.setInt(1, reposId); // getHistoryEntries() returns the entries in reverse chronological // order, but we want to insert them in chronological order so that // their auto-generated identity column can be used as a chronological // ordering column. Otherwise, incremental updates will make the // identity column unusable for chronological ordering. So therefore // we walk the list backwards. List<HistoryEntry> entries = history.getHistoryEntries(); for (ListIterator<HistoryEntry> it = entries.listIterator(entries.size()); it.hasPrevious();) { HistoryEntry entry = it.previous(); retry: for (int i = 0;; i++) { try { addChangeset.setString(2, entry.getRevision()); addChangeset.setInt(3, authors.get(entry.getAuthor())); addChangeset.setTimestamp(4, new Timestamp(entry.getDate().getTime())); addChangeset.setString(5, entry.getMessage()); addChangeset.executeUpdate(); int changesetId = getGeneratedIntKey(addChangeset); addFilechange.setInt(1, changesetId); for (String file : entry.getFiles()) { int fileId = files.get(toUnixPath(file)); addFilechange.setInt(2, fileId); addFilechange.executeUpdate(); } conn.commit(); // Successfully added the entry. Break out of retry loop. break retry; } catch (SQLException sqle) { handleSQLException(sqle, i); conn.rollback(); } } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "storeHistory"
"private void storeHistory(ConnectionResource conn, History history, Repository repository) throws SQLException { Integer reposId = null; Map<String, Integer> authors = null; Map<String, Integer> files = null; PreparedStatement addChangeset = null; PreparedStatement addFilechange = null; for (int i = 0;; i++) { try { if (reposId == null) { reposId = getRepositoryId(conn, repository); conn.commit(); } if (authors == null) { authors = getAuthors(conn, history, reposId); conn.commit(); } if (files == null) { files = getFiles(conn, history, reposId); conn.commit(); } if (addChangeset == null) { addChangeset = conn.getStatement(ADD_CHANGESET); } if (addFilechange == null) { addFilechange = conn.getStatement(ADD_FILECHANGE); } // Success! Break out of the loop. break; } catch (SQLException sqle) { handleSQLException(sqle, i); conn.rollback(); } } addChangeset.setInt(1, reposId); // getHistoryEntries() returns the entries in reverse chronological // order, but we want to insert them in chronological order so that // their auto-generated identity column can be used as a chronological // ordering column. Otherwise, incremental updates will make the // identity column unusable for chronological ordering. So therefore // we walk the list backwards. List<HistoryEntry> entries = history.getHistoryEntries(); for (ListIterator<HistoryEntry> it = entries.listIterator(entries.size()); it.hasPrevious();) { retry: for (int i = 0;; i++) { try { <MASK>HistoryEntry entry = it.previous();</MASK> addChangeset.setString(2, entry.getRevision()); addChangeset.setInt(3, authors.get(entry.getAuthor())); addChangeset.setTimestamp(4, new Timestamp(entry.getDate().getTime())); addChangeset.setString(5, entry.getMessage()); addChangeset.executeUpdate(); int changesetId = getGeneratedIntKey(addChangeset); addFilechange.setInt(1, changesetId); for (String file : entry.getFiles()) { int fileId = files.get(toUnixPath(file)); addFilechange.setInt(2, fileId); addFilechange.executeUpdate(); } conn.commit(); // Successfully added the entry. Break out of retry loop. break retry; } catch (SQLException sqle) { handleSQLException(sqle, i); conn.rollback(); } } } }"
Inversion-Mutation
megadiff
"public void onReceivedMessage(SipProvider provider, Message msg) { if (msg.isResponse()) { int code = msg.getStatusLine().getCode(); if (code >= 100 && code < 200 && (statusIs(STATE_TRYING) || statusIs(STATE_PROCEEDING))) { if (statusIs(STATE_TRYING)) { retransmission_to.halt(); transaction_to.halt(); changeStatus(STATE_PROCEEDING); } if (transaction_listener != null) transaction_listener.onTransProvisionalResponse(this, msg); return; } if (code >= 300 && code < 700 && (statusIs(STATE_TRYING) || statusIs(STATE_PROCEEDING) || statusIs(STATE_COMPLETED))) { if (statusIs(STATE_TRYING) || statusIs(STATE_PROCEEDING)) { retransmission_to.halt(); transaction_to.halt(); ack = MessageFactory.createNon2xxAckRequest(sip_provider, request, msg); changeStatus(STATE_COMPLETED); connection_id = sip_provider.sendMessage(ack); if (transaction_listener != null) transaction_listener.onTransFailureResponse(this, msg); transaction_listener = null; if (connection_id == null) end_to.start(); else { printLog("end_to=0 for reliable transport", LogLevel.LOW); onTimeout(end_to); } } else { // retransmit ACK only in case of unreliable // transport if (connection_id == null) sip_provider.sendMessage(ack); } return; } if (code >= 200 && code < 300 && (statusIs(STATE_TRYING) || statusIs(STATE_PROCEEDING))) { retransmission_to.halt(); transaction_to.halt(); end_to.halt(); changeStatus(STATE_TERMINATED); sip_provider.removeSipProviderListener(transaction_id); if (transaction_listener != null) transaction_listener.onTransSuccessResponse(this, msg); transaction_listener = null; return; } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onReceivedMessage"
"public void onReceivedMessage(SipProvider provider, Message msg) { if (msg.isResponse()) { int code = msg.getStatusLine().getCode(); if (code >= 100 && code < 200 && (statusIs(STATE_TRYING) || statusIs(STATE_PROCEEDING))) { if (statusIs(STATE_TRYING)) { retransmission_to.halt(); transaction_to.halt(); changeStatus(STATE_PROCEEDING); } if (transaction_listener != null) transaction_listener.onTransProvisionalResponse(this, msg); return; } if (code >= 300 && code < 700 && (statusIs(STATE_TRYING) || statusIs(STATE_PROCEEDING) || statusIs(STATE_COMPLETED))) { if (statusIs(STATE_TRYING) || statusIs(STATE_PROCEEDING)) { retransmission_to.halt(); transaction_to.halt(); ack = MessageFactory.createNon2xxAckRequest(sip_provider, request, msg); changeStatus(STATE_COMPLETED); if (transaction_listener != null) transaction_listener.onTransFailureResponse(this, msg); transaction_listener = null; <MASK>connection_id = sip_provider.sendMessage(ack);</MASK> if (connection_id == null) end_to.start(); else { printLog("end_to=0 for reliable transport", LogLevel.LOW); onTimeout(end_to); } } else { // retransmit ACK only in case of unreliable // transport if (connection_id == null) sip_provider.sendMessage(ack); } return; } if (code >= 200 && code < 300 && (statusIs(STATE_TRYING) || statusIs(STATE_PROCEEDING))) { retransmission_to.halt(); transaction_to.halt(); end_to.halt(); changeStatus(STATE_TERMINATED); sip_provider.removeSipProviderListener(transaction_id); if (transaction_listener != null) transaction_listener.onTransSuccessResponse(this, msg); transaction_listener = null; return; } } }"
Inversion-Mutation
megadiff
"private void storeHistory(ConnectionResource conn, History history, Repository repository) throws SQLException { Integer reposId = null; Map<String, Integer> authors = null; Map<String, Integer> files = null; PreparedStatement addChangeset = null; PreparedStatement addFilechange = null; for (int i = 0;; i++) { try { if (reposId == null) { reposId = getRepositoryId(conn, repository); conn.commit(); } if (authors == null) { authors = getAuthors(conn, history, reposId); conn.commit(); } if (files == null) { files = getFiles(conn, history, reposId); conn.commit(); } if (addChangeset == null) { addChangeset = conn.getStatement(ADD_CHANGESET); } if (addFilechange == null) { addFilechange = conn.getStatement(ADD_FILECHANGE); } // Success! Break out of the loop. break; } catch (SQLException sqle) { handleSQLException(sqle, i); conn.rollback(); } } addChangeset.setInt(1, reposId); // getHistoryEntries() returns the entries in reverse chronological // order, but we want to insert them in chronological order so that // their auto-generated identity column can be used as a chronological // ordering column. Otherwise, incremental updates will make the // identity column unusable for chronological ordering. So therefore // we walk the list backwards. List<HistoryEntry> entries = history.getHistoryEntries(); for (ListIterator<HistoryEntry> it = entries.listIterator(entries.size()); it.hasPrevious();) { HistoryEntry entry = it.previous(); retry: for (int i = 0;; i++) { try { addChangeset.setString(2, entry.getRevision()); addChangeset.setInt(3, authors.get(entry.getAuthor())); addChangeset.setTimestamp(4, new Timestamp(entry.getDate().getTime())); addChangeset.setString(5, entry.getMessage()); addChangeset.executeUpdate(); int changesetId = getGeneratedIntKey(addChangeset); addFilechange.setInt(1, changesetId); for (String file : entry.getFiles()) { int fileId = files.get(toUnixPath(file)); addFilechange.setInt(2, fileId); addFilechange.executeUpdate(); } conn.commit(); // Successfully added the entry. Break out of retry loop. break retry; } catch (SQLException sqle) { handleSQLException(sqle, i); conn.rollback(); } } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "storeHistory"
"private void storeHistory(ConnectionResource conn, History history, Repository repository) throws SQLException { Integer reposId = null; Map<String, Integer> authors = null; Map<String, Integer> files = null; PreparedStatement addChangeset = null; PreparedStatement addFilechange = null; for (int i = 0;; i++) { try { if (reposId == null) { reposId = getRepositoryId(conn, repository); conn.commit(); } if (authors == null) { authors = getAuthors(conn, history, reposId); conn.commit(); } if (files == null) { files = getFiles(conn, history, reposId); conn.commit(); } if (addChangeset == null) { addChangeset = conn.getStatement(ADD_CHANGESET); } if (addFilechange == null) { addFilechange = conn.getStatement(ADD_FILECHANGE); } // Success! Break out of the loop. break; } catch (SQLException sqle) { handleSQLException(sqle, i); conn.rollback(); } } addChangeset.setInt(1, reposId); // getHistoryEntries() returns the entries in reverse chronological // order, but we want to insert them in chronological order so that // their auto-generated identity column can be used as a chronological // ordering column. Otherwise, incremental updates will make the // identity column unusable for chronological ordering. So therefore // we walk the list backwards. List<HistoryEntry> entries = history.getHistoryEntries(); for (ListIterator<HistoryEntry> it = entries.listIterator(entries.size()); it.hasPrevious();) { retry: for (int i = 0;; i++) { try { <MASK>HistoryEntry entry = it.previous();</MASK> addChangeset.setString(2, entry.getRevision()); addChangeset.setInt(3, authors.get(entry.getAuthor())); addChangeset.setTimestamp(4, new Timestamp(entry.getDate().getTime())); addChangeset.setString(5, entry.getMessage()); addChangeset.executeUpdate(); int changesetId = getGeneratedIntKey(addChangeset); addFilechange.setInt(1, changesetId); for (String file : entry.getFiles()) { int fileId = files.get(toUnixPath(file)); addFilechange.setInt(2, fileId); addFilechange.executeUpdate(); } conn.commit(); // Successfully added the entry. Break out of retry loop. break retry; } catch (SQLException sqle) { handleSQLException(sqle, i); conn.rollback(); } } } }"
Inversion-Mutation
megadiff
"protected ILazyDataset getLazyDataset(final File path, final String dsPath, final IConversionContext context) throws Exception { final DataHolder dh = LoaderFactory.getData(path.getAbsolutePath()); context.setSelectedH5Path(dsPath); if (context.getSliceDimensions()==null) { AbstractDataset data = LoaderFactory.getDataSet(path.getAbsolutePath(), dsPath, null); data.setName(dsPath); convert(data); return null; } if (context.getMonitor()!=null) { context.getMonitor().subTask("Process '"+dsPath+"'"); } return dh.getLazyDataset(dsPath); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getLazyDataset"
"protected ILazyDataset getLazyDataset(final File path, final String dsPath, final IConversionContext context) throws Exception { final DataHolder dh = LoaderFactory.getData(path.getAbsolutePath()); if (context.getSliceDimensions()==null) { AbstractDataset data = LoaderFactory.getDataSet(path.getAbsolutePath(), dsPath, null); data.setName(dsPath); convert(data); return null; } <MASK>context.setSelectedH5Path(dsPath);</MASK> if (context.getMonitor()!=null) { context.getMonitor().subTask("Process '"+dsPath+"'"); } return dh.getLazyDataset(dsPath); }"
Inversion-Mutation
megadiff
"private void insertAfter(Node n[], int s, int e) { int l1 = e - s; System.arraycopy(n, s, nodes, endUsed, l1); endUsed += l1; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "insertAfter"
"private void insertAfter(Node n[], int s, int e) { int l1 = e - s; <MASK>endUsed += l1;</MASK> System.arraycopy(n, s, nodes, endUsed, l1); }"
Inversion-Mutation
megadiff
"@Override public void doExecute() { if (setNameCmd != null) { // This is a hack. // TODO: Fix this when we stop using canExecute()==false for no-op commands. if (!setNameCmd.canExecute()) setNameCmd = null; } flow = FlowLinkUtil.getCommonFlow(source, target); if (flow == null) { if (Policy.DEBUG) System.out.println("No common flow found!!"); //$NON-NLS-1$ return; } if (setNameCmd != null) setNameCmd.execute(); FlowLinkUtil.setLinkSource(link, source); FlowLinkUtil.setLinkTarget(link, target); if (link.eContainer() != null) { Flow oldParent = (Flow)link.eContainer().eContainer(); if (oldParent != null) { FlowLinkUtil.removeFlowLink(oldParent, link); } } FlowLinkUtil.addFlowLink(flow, link); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doExecute"
"@Override public void doExecute() { if (setNameCmd != null) { // This is a hack. // TODO: Fix this when we stop using canExecute()==false for no-op commands. if (!setNameCmd.canExecute()) setNameCmd = null; } flow = FlowLinkUtil.getCommonFlow(source, target); if (flow == null) { if (Policy.DEBUG) System.out.println("No common flow found!!"); //$NON-NLS-1$ return; } FlowLinkUtil.setLinkSource(link, source); FlowLinkUtil.setLinkTarget(link, target); if (link.eContainer() != null) { Flow oldParent = (Flow)link.eContainer().eContainer(); if (oldParent != null) { FlowLinkUtil.removeFlowLink(oldParent, link); } } FlowLinkUtil.addFlowLink(flow, link); <MASK>if (setNameCmd != null) setNameCmd.execute();</MASK> }"
Inversion-Mutation
megadiff
"public void next(double[] point) { pos = iterator.next(); for (int i = 0; i < point.length; i++) { point[i] = tiles[i].getSampleDouble(pos.x, pos.y); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "next"
"public void next(double[] point) { for (int i = 0; i < point.length; i++) { point[i] = tiles[i].getSampleDouble(pos.x, pos.y); } <MASK>pos = iterator.next();</MASK> }"
Inversion-Mutation
megadiff
"@Override public void appModeChanged() { setCursor(new Cursor(Cursor.WAIT_CURSOR)); if (currentMode != null) { saveLayout(FILEPATH_LAYOUT + "." + currentMode.name()); saveConfig(FILEPATH_MAP + "." + currentMode.name()); } final CidsAppBackend.Mode mode = CidsAppBackend.getInstance().getMode(); if (mode.equals(mode.ALLGEMEIN)) { setupLayoutInfo(); } else if (mode.equals(mode.ESW)) { setupLayoutWDSR(); } else if (mode.equals(mode.REGEN)) { setupLayoutRegen(); } currentMode = mode; refreshClipboardButtons(); refreshClipboardButtonsToolTipText(); refreshItemButtons(); final ModeLayer ml = de.cismet.cismap.commons.ModeLayerRegistry.getInstance() .getModeLayer("verdisAppModeLayer"); if (ml != null) { ml.forceMode(mode.toString()); } setupMap(currentMode); setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "appModeChanged"
"@Override public void appModeChanged() { setCursor(new Cursor(Cursor.WAIT_CURSOR)); if (currentMode != null) { saveLayout(FILEPATH_LAYOUT + "." + currentMode.name()); saveConfig(FILEPATH_MAP + "." + currentMode.name()); } final CidsAppBackend.Mode mode = CidsAppBackend.getInstance().getMode(); if (mode.equals(mode.ALLGEMEIN)) { setupLayoutInfo(); } else if (mode.equals(mode.ESW)) { setupLayoutWDSR(); } else if (mode.equals(mode.REGEN)) { setupLayoutRegen(); } currentMode = mode; <MASK>setupMap(currentMode);</MASK> refreshClipboardButtons(); refreshClipboardButtonsToolTipText(); refreshItemButtons(); final ModeLayer ml = de.cismet.cismap.commons.ModeLayerRegistry.getInstance() .getModeLayer("verdisAppModeLayer"); if (ml != null) { ml.forceMode(mode.toString()); } setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); }"
Inversion-Mutation
megadiff
"@Override protected void getJobDone() throws InterruptedException { /** Read stdErr pipe **/ this.stdErrThread = new Thread(){ @Override public void run(){ char[] chars = new char[BUF_SIZE]; int i = 0; while(i > -1){ try{ i = Console.this.getStdErr().getData(chars, Console.this.writingLock); if(i != -1){ print(String.copyValueOf(chars, 0, i)); } Console.this.writingLock.unlock(); } catch (IOException e) { print("Console read error"); }catch (InterruptedException e) { return; } } }}; this.stdErrThread.start(); /** Read stdIn pipe **/ this.stdInThread = new Thread(new Runnable() { public void run() { char[] chars = new char[BUF_SIZE]; int i = 0; while(i > -1){ try { i = Console.this.getStdIn().getData(chars, Console.this.writingLock); if(i != -1){ print(String.copyValueOf(chars, 0, i)); Console.this.writingLock.unlock(); } } catch (IOException e) { print("Console read error"); } catch (InterruptedException e) { return; } } } }); this.stdInThread.start(); /** Waits for threads in this console to do something */ this.stdErrThread.join(); this.stdInThread.join(); this.swingWorker.join(); System.out.println("CONSOLE " + this.PID + " ENDED NORMALLY."); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getJobDone"
"@Override protected void getJobDone() throws InterruptedException { /** Read stdErr pipe **/ this.stdErrThread = new Thread(){ @Override public void run(){ char[] chars = new char[BUF_SIZE]; int i = 0; while(i > -1){ try{ i = Console.this.getStdErr().getData(chars, Console.this.writingLock); if(i != -1){ print(String.copyValueOf(chars, 0, i)); } <MASK>Console.this.writingLock.unlock();</MASK> } catch (IOException e) { print("Console read error"); }catch (InterruptedException e) { return; } } }}; this.stdErrThread.start(); /** Read stdIn pipe **/ this.stdInThread = new Thread(new Runnable() { public void run() { char[] chars = new char[BUF_SIZE]; int i = 0; while(i > -1){ try { i = Console.this.getStdIn().getData(chars, Console.this.writingLock); if(i != -1){ print(String.copyValueOf(chars, 0, i)); } <MASK>Console.this.writingLock.unlock();</MASK> } catch (IOException e) { print("Console read error"); } catch (InterruptedException e) { return; } } } }); this.stdInThread.start(); /** Waits for threads in this console to do something */ this.stdErrThread.join(); this.stdInThread.join(); this.swingWorker.join(); System.out.println("CONSOLE " + this.PID + " ENDED NORMALLY."); }"
Inversion-Mutation
megadiff
"public void run() { char[] chars = new char[BUF_SIZE]; int i = 0; while(i > -1){ try { i = Console.this.getStdIn().getData(chars, Console.this.writingLock); if(i != -1){ print(String.copyValueOf(chars, 0, i)); Console.this.writingLock.unlock(); } } catch (IOException e) { print("Console read error"); } catch (InterruptedException e) { return; } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"public void run() { char[] chars = new char[BUF_SIZE]; int i = 0; while(i > -1){ try { i = Console.this.getStdIn().getData(chars, Console.this.writingLock); if(i != -1){ print(String.copyValueOf(chars, 0, i)); } <MASK>Console.this.writingLock.unlock();</MASK> } catch (IOException e) { print("Console read error"); } catch (InterruptedException e) { return; } } }"
Inversion-Mutation
megadiff
"public DataSessionContext( int mode, ModuleHandle moduleHandle, ScriptContext scriptContext, ClassLoader classLoader ) throws AdapterException { try { if ( !( mode == MODE_GENERATION || mode == MODE_PRESENTATION || mode == MODE_DIRECT_PRESENTATION || mode == MODE_UPDATE ) ) throw new AdapterException( ResourceConstants.ADAPTER_INVALID_MODE, new Integer( mode ) ); this.mode = mode; this.moduleHandle = moduleHandle; this.appClassLoader = classLoader; if ( scriptContext == null ) { scriptContext = new ScriptContext( ).newContext( this.getTopScope( ) ); } this.sContext = scriptContext; this.topScope = ( (IDataScriptEngine) scriptContext.getScriptEngine( IDataScriptEngine.ENGINE_NAME ) ).getJSScope( scriptContext ); this.hasExternalScope = topScope != null; } catch ( BirtException e ) { throw new AdapterException( e.getErrorCode( ), e ); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "DataSessionContext"
"public DataSessionContext( int mode, ModuleHandle moduleHandle, ScriptContext scriptContext, ClassLoader classLoader ) throws AdapterException { try { if ( !( mode == MODE_GENERATION || mode == MODE_PRESENTATION || mode == MODE_DIRECT_PRESENTATION || mode == MODE_UPDATE ) ) throw new AdapterException( ResourceConstants.ADAPTER_INVALID_MODE, new Integer( mode ) ); this.mode = mode; <MASK>this.hasExternalScope = topScope != null;</MASK> this.moduleHandle = moduleHandle; this.appClassLoader = classLoader; if ( scriptContext == null ) { scriptContext = new ScriptContext( ).newContext( this.getTopScope( ) ); } this.sContext = scriptContext; this.topScope = ( (IDataScriptEngine) scriptContext.getScriptEngine( IDataScriptEngine.ENGINE_NAME ) ).getJSScope( scriptContext ); } catch ( BirtException e ) { throw new AdapterException( e.getErrorCode( ), e ); } }"
Inversion-Mutation
megadiff
"public void createFieldEditors() { if(System.getProperty("os.name").equals("Mac OS X")){ addField(new DirectoryFieldEditor(BrowserPreferenceConstants.P_PRIMARY_BROWSER_PATH, "Primary Browser", getFieldEditorParent())); addField(new DirectoryFieldEditor(BrowserPreferenceConstants.P_SECONDARY_BROWSER_PATH, "Secondary Browser", getFieldEditorParent())); } else { addField(new FileFieldEditor(BrowserPreferenceConstants.P_PRIMARY_BROWSER_PATH, "Primary Browser",getFieldEditorParent())); addField(new FileFieldEditor(BrowserPreferenceConstants.P_SECONDARY_BROWSER_PATH, "Secondary Browser",getFieldEditorParent())); } addField(new StringFieldEditor(BrowserPreferenceConstants.P_TESTCASE_QUERYSTRING, "Querystring for TestCases",getFieldEditorParent())); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createFieldEditors"
"public void createFieldEditors() { if(System.getProperty("os.name").equals("Mac OS X")){ addField(new DirectoryFieldEditor(BrowserPreferenceConstants.P_PRIMARY_BROWSER_PATH, "Primary Browser", getFieldEditorParent())); addField(new DirectoryFieldEditor(BrowserPreferenceConstants.P_SECONDARY_BROWSER_PATH, "Secondary Browser", getFieldEditorParent())); } else { addField(new FileFieldEditor(BrowserPreferenceConstants.P_PRIMARY_BROWSER_PATH, "Primary Browser",getFieldEditorParent())); addField(new FileFieldEditor(BrowserPreferenceConstants.P_SECONDARY_BROWSER_PATH, "Secondary Browser",getFieldEditorParent())); <MASK>addField(new StringFieldEditor(BrowserPreferenceConstants.P_TESTCASE_QUERYSTRING, "Querystring for TestCases",getFieldEditorParent()));</MASK> } }"
Inversion-Mutation
megadiff
"public ArithmeticExpression parse(String rpnInput) { Queue<Character> unprocessed = new ArrayDeque<>(); for (int charI = 0; charI < rpnInput.length(); charI++) { char c = rpnInput.charAt(charI); if (c == ' ') { continue; } unprocessed.offer(c); } Deque<ArithmeticExpression> workStack = new ArrayDeque<>(); while (! unprocessed.isEmpty()) { Character c = unprocessed.poll(); String s = c.toString(); if (isNumericOperand(s)) { Integer value = Integer.parseInt(s); workStack.push(new NumericOperand(value)); } else if (isBinaryOperator(s)) { ArithmeticExpression rightOperand = workStack.pop(); ArithmeticExpression leftOperand = workStack.pop(); ArithmeticExpression binary; if (c.equals('+')) { binary = new AddOperator(leftOperand, rightOperand); } else if (c.equals('-')) { binary = new SubtractOperator(leftOperand, rightOperand); } else { throw new IllegalArgumentException("Unknown binary operator"); } workStack.push(binary); } } return workStack.pop(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "parse"
"public ArithmeticExpression parse(String rpnInput) { Queue<Character> unprocessed = new ArrayDeque<>(); for (int charI = 0; charI < rpnInput.length(); charI++) { char c = rpnInput.charAt(charI); if (c == ' ') { continue; } unprocessed.offer(c); } Deque<ArithmeticExpression> workStack = new ArrayDeque<>(); while (! unprocessed.isEmpty()) { Character c = unprocessed.poll(); String s = c.toString(); if (isNumericOperand(s)) { Integer value = Integer.parseInt(s); workStack.push(new NumericOperand(value)); } else if (isBinaryOperator(s)) { <MASK>ArithmeticExpression leftOperand = workStack.pop();</MASK> ArithmeticExpression rightOperand = workStack.pop(); ArithmeticExpression binary; if (c.equals('+')) { binary = new AddOperator(leftOperand, rightOperand); } else if (c.equals('-')) { binary = new SubtractOperator(leftOperand, rightOperand); } else { throw new IllegalArgumentException("Unknown binary operator"); } workStack.push(binary); } } return workStack.pop(); }"
Inversion-Mutation
megadiff
"private File getTileFile(MapTile tile) { World world = tile.getWorld(); File worldTileDirectory = worldTileDirectories.get(world); if (worldTileDirectory == null) { worldTileDirectory = new File(DynmapPlugin.tilesDirectory, tile.getWorld().getName()); worldTileDirectories.put(world, worldTileDirectory); } worldTileDirectory.mkdirs(); return new File(worldTileDirectory, tile.getFilename()); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getTileFile"
"private File getTileFile(MapTile tile) { World world = tile.getWorld(); File worldTileDirectory = worldTileDirectories.get(world); if (worldTileDirectory == null) { worldTileDirectory = new File(DynmapPlugin.tilesDirectory, tile.getWorld().getName()); <MASK>worldTileDirectory.mkdirs();</MASK> worldTileDirectories.put(world, worldTileDirectory); } return new File(worldTileDirectory, tile.getFilename()); }"
Inversion-Mutation
megadiff
"public void openChat(Protocol p, Contact c, boolean allowingStateLoss) { FragmentManager fragmentManager = getSupportFragmentManager(); ChatView chatView = (ChatView) fragmentManager.findFragmentById(R.id.chat_fragment); c.activate(p); if (chatView == null) { Fragment rosterView = getSupportFragmentManager().findFragmentByTag(RosterView.TAG); chatView = (ChatView) getSupportFragmentManager().findFragmentByTag(ChatView.TAG); if (fragmentManager.getFragments() == null || rosterView == null || chatView == null) { createChatView(p, c, fragmentManager, true, allowingStateLoss); return; } if (!chatView.isLastPosition()) return; if (rosterView.isVisible()) { createChatView(p, c, fragmentManager, true, allowingStateLoss); } else if (chatView.isVisible()) { if (c != null) { chatView.openChat(p, c); chatView.resume(p.getChat(c)); } } } else { if (c == null && !chatView.isLastPosition()) return; chatView.openChat(p, c); chatView.resume(chatView.getCurrentChat()); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "openChat"
"public void openChat(Protocol p, Contact c, boolean allowingStateLoss) { FragmentManager fragmentManager = getSupportFragmentManager(); ChatView chatView = (ChatView) fragmentManager.findFragmentById(R.id.chat_fragment); c.activate(p); if (chatView == null) { Fragment rosterView = getSupportFragmentManager().findFragmentByTag(RosterView.TAG); chatView = (ChatView) getSupportFragmentManager().findFragmentByTag(ChatView.TAG); <MASK>if (!chatView.isLastPosition()) return;</MASK> if (fragmentManager.getFragments() == null || rosterView == null || chatView == null) { createChatView(p, c, fragmentManager, true, allowingStateLoss); return; } if (rosterView.isVisible()) { createChatView(p, c, fragmentManager, true, allowingStateLoss); } else if (chatView.isVisible()) { if (c != null) { chatView.openChat(p, c); chatView.resume(p.getChat(c)); } } } else { if (c == null && !chatView.isLastPosition()) return; chatView.openChat(p, c); chatView.resume(chatView.getCurrentChat()); } }"
Inversion-Mutation
megadiff
"@Override public synchronized int enableApnType(String apnType) { ApnContext apnContext = mApnContexts.get(apnType); if (apnContext == null || !isApnTypeAvailable(apnType)) { if (DBG) log("enableApnType: " + apnType + " is type not available"); return PhoneConstants.APN_TYPE_NOT_AVAILABLE; } // If already active, return if (DBG) log("enableApnType: " + apnType + " mState(" + apnContext.getState() + ")"); setEnabled(apnTypeToId(apnType), true); if (apnContext.getState() == DctConstants.State.CONNECTED) { if (DBG) log("enableApnType: return APN_ALREADY_ACTIVE"); return PhoneConstants.APN_ALREADY_ACTIVE; } if (DBG) { log("enableApnType: new apn request for type " + apnType + " return APN_REQUEST_STARTED"); } return PhoneConstants.APN_REQUEST_STARTED; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "enableApnType"
"@Override public synchronized int enableApnType(String apnType) { ApnContext apnContext = mApnContexts.get(apnType); if (apnContext == null || !isApnTypeAvailable(apnType)) { if (DBG) log("enableApnType: " + apnType + " is type not available"); return PhoneConstants.APN_TYPE_NOT_AVAILABLE; } // If already active, return if (DBG) log("enableApnType: " + apnType + " mState(" + apnContext.getState() + ")"); if (apnContext.getState() == DctConstants.State.CONNECTED) { if (DBG) log("enableApnType: return APN_ALREADY_ACTIVE"); return PhoneConstants.APN_ALREADY_ACTIVE; } <MASK>setEnabled(apnTypeToId(apnType), true);</MASK> if (DBG) { log("enableApnType: new apn request for type " + apnType + " return APN_REQUEST_STARTED"); } return PhoneConstants.APN_REQUEST_STARTED; }"
Inversion-Mutation
megadiff
"public void run() { if(runPolling()) { LOGGER.info("SCM changes detected in "+ job.getName()); job.scheduleBuild(); } synchronized(SCMTrigger.this) { if(abortNow) return; // terminate now without queueing the next one. if(pollingScheduled) { // schedule a next run pollingScheduled = false; polling = DESCRIPTOR.getExecutor().submit(new Runner()); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"public void run() { if(runPolling()) { LOGGER.info("SCM changes detected in "+ job.getName()); job.scheduleBuild(); } synchronized(SCMTrigger.this) { if(abortNow) return; // terminate now without queueing the next one. if(pollingScheduled) { // schedule a next run polling = DESCRIPTOR.getExecutor().submit(new Runner()); } <MASK>pollingScheduled = false;</MASK> } }"
Inversion-Mutation
megadiff
"private void analyzeContinue(boolean checkComputerMove, boolean resetBoard) { endLengthyCommand(); String title = m_analyzeCommand.getResultTitle(); try { if (resetBoard) resetBoard(); Gtp.Error e = m_commandThread.getException(); if (e != null) throw e; String response = m_commandThread.getResponse(); AnalyzeShow.show(m_analyzeCommand, m_guiBoard, m_board, response); int type = m_analyzeCommand.getType(); boolean statusContainsResponse = false; if (type == AnalyzeCommand.STRING || type == AnalyzeCommand.HSTRING || type == AnalyzeCommand.HPSTRING || type == AnalyzeCommand.PSTRING || type == AnalyzeCommand.VAR || type == AnalyzeCommand.VARW || type == AnalyzeCommand.VARB || type == AnalyzeCommand.VARP || type == AnalyzeCommand.VARPO) { if (response.indexOf("\n") < 0) { showStatus(title + ": " + response); statusContainsResponse = true; } else { boolean highlight = (type == AnalyzeCommand.HSTRING || type == AnalyzeCommand.HPSTRING); new AnalyzeTextOutput(this, title, response, highlight); } } if (! statusContainsResponse) showStatus(title); if (checkComputerMove) checkComputerMove(); } catch(Gtp.Error e) { showStatus(title); showGtpError(e); return; } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "analyzeContinue"
"private void analyzeContinue(boolean checkComputerMove, boolean resetBoard) { endLengthyCommand(); String title = m_analyzeCommand.getResultTitle(); try { if (resetBoard) resetBoard(); Gtp.Error e = m_commandThread.getException(); if (e != null) throw e; String response = m_commandThread.getResponse(); AnalyzeShow.show(m_analyzeCommand, m_guiBoard, m_board, response); int type = m_analyzeCommand.getType(); boolean statusContainsResponse = false; if (type == AnalyzeCommand.STRING || type == AnalyzeCommand.HSTRING || type == AnalyzeCommand.HPSTRING || type == AnalyzeCommand.PSTRING || type == AnalyzeCommand.VAR || type == AnalyzeCommand.VARW || type == AnalyzeCommand.VARB || type == AnalyzeCommand.VARP || type == AnalyzeCommand.VARPO) { if (response.indexOf("\n") < 0) { showStatus(title + ": " + response); statusContainsResponse = true; } else { boolean highlight = (type == AnalyzeCommand.HSTRING || type == AnalyzeCommand.HPSTRING); new AnalyzeTextOutput(this, title, response, highlight); } } if (! statusContainsResponse) showStatus(title); if (checkComputerMove) checkComputerMove(); } catch(Gtp.Error e) { <MASK>showGtpError(e);</MASK> showStatus(title); return; } }"
Inversion-Mutation
megadiff
"public void unmute() { if (!mute) return; effectsVolume = prevEffectsVolume; mute = false; setSoundVolume(prevSoundsVolume); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "unmute"
"public void unmute() { if (!mute) return; effectsVolume = prevEffectsVolume; <MASK>setSoundVolume(prevSoundsVolume);</MASK> mute = false; }"
Inversion-Mutation
megadiff
"@After public final void shutDown() { if (this.context != null) { this.cleanup(this.context); this.context.close(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "shutDown"
"@After public final void shutDown() { <MASK>this.cleanup(this.context);</MASK> if (this.context != null) { this.context.close(); } }"
Inversion-Mutation
megadiff
"protected static String initApp(final String[] args) { try { /* Metal */ UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); MetalLookAndFeel.setCurrentTheme( new OceanTheme() { /** e.g. arrows on split pane... */ protected ColorUIResource getPrimary1() { return new ColorUIResource( ClusterBrowser.STATUS_BACKGROUND); } /** unknown to me */ protected ColorUIResource getPrimary2() { return new ColorUIResource( ClusterBrowser.PANEL_BACKGROUND); } /** unknown to me */ protected ColorUIResource getPrimary3() { return new ColorUIResource( ClusterBrowser.PANEL_BACKGROUND); } /** Button and other borders. */ protected ColorUIResource getSecondary1() { return new ColorUIResource(AppDefaults.BACKGROUND_DARK); } protected ColorUIResource getSecondary2() { return new ColorUIResource( ClusterBrowser.PANEL_BACKGROUND); } /** Split pane divider. Line in the main menu. */ protected ColorUIResource getSecondary3() { return new ColorUIResource( ClusterBrowser.PANEL_BACKGROUND); } } ); } catch (final Exception e) { /* ignore it then */ } Thread.setDefaultUncaughtExceptionHandler( new Thread.UncaughtExceptionHandler() { public void uncaughtException(final Thread t, final Throwable ex) { System.out.println(ex.toString()); System.out.println(Tools.getStackTrace(ex)); if (!uncaughtException && Tools.getGUIData().getMainFrame() != null) { uncaughtException = true; Tools.appError("", ex.toString(), ex); } } }); float fps = ConfigData.DEFAULT_ANIM_FPS; final Options options = new Options(); options.addOption("h", HELP_OP, false, "print this help"); options.addOption(null, KEEP_HELPER_OP, false, "do not overwrite the lcmc-gui-helper program"); options.addOption(null, RO_OP, false, "read only mode"); options.addOption(null, OP_OP, false, "operator mode"); options.addOption(null, ADMIN_OP, false, "administrator mode"); options.addOption(null, OP_MODE_OP, true, "operating mode. <arg> can be:\n" + "ro - read only\n" + "op - operator\n" + "admin - administrator"); options.addOption(null, NOLRM_OP, false, "do not show removed resources from LRM."); options.addOption("v", VERSION_OP, false, "print version"); options.addOption(null, AUTO_OP, true, "ADVANCED USE: for testing"); options.addOption(null, PCMKTEST_OP, true, "ADVANCED USE: for testing"); options.addOption(null, DRBDTEST_OP, true, "ADVANCED USE: for testing"); options.addOption(null, VMTEST_OP, true, "ADVANCED USE: for testing"); options.addOption(null, GUITEST_OP, true, "ADVANCED USE: for testing"); options.addOption(null, NO_UPGRADE_CHECK_OP, false, "disable upgrade check"); options.addOption( null, NO_PLUGIN_CHECK_OP, false, "disable plugin check, DEPRECATED: there are no plugins"); options.addOption(null, TIGHTVNC_OP, false, "enable tight vnc viewer"); options.addOption(null, ULTRAVNC_OP, false, "enable ultra vnc viewer"); options.addOption(null, REALVNC_OP, false, "enable real vnc viewer"); options.addOption(null, BIGDRBDCONF_OP, false, "create one big drbd.conf, instead of many" + " files in drbd.d/ directory"); options.addOption(null, STAGING_DRBD_OP, false, "enable more DRBD installation options"); options.addOption(null, STAGING_PACEMAKER_OP, false, "enable more Pacemaker installation options"); options.addOption(null, VNC_PORT_OFFSET_OP, true, "offset for port forwarding"); options.addOption(null, SLOW_OP, false, "specify this if you have slow computer"); options.addOption(null, RESTORE_MOUSE_OP, false, "ADVANCED USE: for testing"); options.addOption(null, SCALE_OP, true, "scale fonts and sizes of elements in percent (100)"); options.addOption(null, ID_DSA_OP, true, "location of id_dsa file ($HOME/.ssh/id_dsa)"); options.addOption(null, ID_RSA_OP, true, "location of id_rsa file ($HOME/.ssh/id_rsa)"); options.addOption( null, KNOWN_HOSTS_OP, true, "location of known_hosts file ($HOME/.ssh/known_hosts)"); options.addOption( null, OUT_OP, true, "where to redirect the standard out"); options.addOption( null, DEBUG_OP, true, "debug level, 0 - none, 3 - all"); options.addOption("c", CLUSTER_OP, true, "define a cluster"); final Option hostOp = new Option("h", HOST_OP, true, "define a cluster, used with --cluster option"); hostOp.setArgs(10000); options.addOption(hostOp); options.addOption(null, SUDO_OP, false, "whether to use sudo, used with --cluster option"); options.addOption(null, USER_OP, true, "user to use with sudo, used with --cluster option"); options.addOption(null, PORT_OP, true, "ssh port, used with --cluster option"); options.addOption(null, ADVANCED_OP, false, "start in an advanced mode"); options.addOption(null, ONE_HOST_CLUSTER_OP, false, "allow one host cluster"); options.addOption(null, NO_PASSPHRASE_OP, false, "try no passphrase first"); options.addOption(null, EMBED_OP, false, "embed applet in the browser"); options.addOption(null, NO_EMBED_OP, false, "don't embed applet in the browser"); options.addOption( null, CMD_LOG_OP, false, "Log executed commands to the lcmc.log on the servers"); options.addOption( null, CHECK_SWING_OP, false, "ADVANCED USE: for testing"); final CommandLineParser parser = new PosixParser(); String autoArgs = null; try { final CommandLine cmd = parser.parse(options, args); if (cmd.hasOption(OUT_OP)) { final String out = cmd.getOptionValue(OUT_OP); if (out != null) { try { System.setOut( new PrintStream(new FileOutputStream(out))); } catch (final FileNotFoundException e) { System.exit(2); } } } if (cmd.hasOption(DEBUG_OP)) { final String level = cmd.getOptionValue(DEBUG_OP); if (level != null && Tools.isNumber(level)) { Tools.setDebugLevel(Integer.parseInt(level)); } else { throw new ParseException( "cannot parse debug level: " + level); } } boolean tightvnc = cmd.hasOption(TIGHTVNC_OP); boolean ultravnc = cmd.hasOption(ULTRAVNC_OP); final boolean realvnc = cmd.hasOption(REALVNC_OP); if (!tightvnc && !ultravnc && !realvnc) { if (Tools.isLinux()) { tightvnc = true; } else { tightvnc = true; ultravnc = true; } } final boolean advanced = cmd.hasOption(ADVANCED_OP); Tools.getConfigData().setAdvancedMode(advanced); Tools.getConfigData().setTightvnc(tightvnc); Tools.getConfigData().setUltravnc(ultravnc); Tools.getConfigData().setRealvnc(realvnc); Tools.getConfigData().setUpgradeCheckEnabled( !cmd.hasOption(NO_UPGRADE_CHECK_OP)); Tools.getConfigData().setBigDRBDConf( cmd.hasOption(BIGDRBDCONF_OP)); Tools.getConfigData().setStagingDrbd( cmd.hasOption(STAGING_DRBD_OP)); Tools.getConfigData().setStagingPacemaker( cmd.hasOption(STAGING_PACEMAKER_OP)); Tools.getConfigData().setNoLRM(cmd.hasOption(NOLRM_OP)); Tools.getConfigData().setKeepHelper(cmd.hasOption(KEEP_HELPER_OP)); Tools.getConfigData().setOneHostCluster( cmd.hasOption(ONE_HOST_CLUSTER_OP)); Tools.getConfigData().setNoPassphrase( cmd.hasOption(NO_PASSPHRASE_OP)); if (cmd.hasOption(EMBED_OP)) { Tools.getConfigData().setEmbed(true); } if (cmd.hasOption(NO_EMBED_OP)) { Tools.getConfigData().setEmbed(false); } if (cmd.hasOption(CMD_LOG_OP)) { Tools.getConfigData().setCmdLog(true); } if (cmd.hasOption(CHECK_SWING_OP)) { Tools.getConfigData().setCheckSwing(true); } final String pwd = System.getProperty("user.home"); final String scaleOp = cmd.getOptionValue(SCALE_OP, "100"); try { final int scale = Integer.parseInt(scaleOp); Tools.getConfigData().setScale(scale); Tools.resizeFonts(scale); } catch (java.lang.NumberFormatException e) { Tools.appWarning("cannot parse scale: " + scaleOp); } final String idDsaPath = cmd.getOptionValue(ID_DSA_OP, pwd + "/.ssh/id_dsa"); final String idRsaPath = cmd.getOptionValue(ID_RSA_OP, pwd + "/.ssh/id_rsa"); final String knownHostsPath = cmd.getOptionValue( KNOWN_HOSTS_OP, pwd + "/.ssh/known_hosts"); Tools.getConfigData().setIdDSAPath(idDsaPath); Tools.getConfigData().setIdRSAPath(idRsaPath); Tools.getConfigData().setKnownHostPath(knownHostsPath); final String opMode = cmd.getOptionValue(OP_MODE_OP); autoArgs = cmd.getOptionValue(AUTO_OP); if (cmd.hasOption(HELP_OP)) { final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar LCMC.jar [OPTIONS]", options); System.exit(0); } if (cmd.hasOption(VERSION_OP)) { System.out.println("LINUX CLUSTER MANAGEMENT CONSOLE " + Tools.getRelease() + " by Rasto Levrinc"); System.exit(0); } if (cmd.hasOption("ro") || "ro".equals(opMode)) { Tools.getConfigData().setAccessType(ConfigData.AccessType.RO); Tools.getConfigData().setMaxAccessType( ConfigData.AccessType.RO); } else if (cmd.hasOption("op") || "op".equals(opMode)) { Tools.getConfigData().setAccessType(ConfigData.AccessType.OP); Tools.getConfigData().setMaxAccessType( ConfigData.AccessType.OP); } else if (cmd.hasOption("admin") || "admin".equals(opMode)) { Tools.getConfigData().setAccessType( ConfigData.AccessType.ADMIN); Tools.getConfigData().setMaxAccessType( ConfigData.AccessType.ADMIN); } else if (opMode != null) { Tools.appWarning("unknown operating mode: " + opMode); } if (cmd.hasOption(SLOW_OP)) { fps = fps / 2; } if (cmd.hasOption(RESTORE_MOUSE_OP)) { /* restore mouse if it is stuck in pressed state, during * robot tests. */ RoboTest.restoreMouse(); } final String vncPortOffsetString = cmd.getOptionValue(VNC_PORT_OFFSET_OP); if (vncPortOffsetString != null && Tools.isNumber(vncPortOffsetString)) { Tools.getConfigData().setVncPortOffset( Integer.parseInt(vncPortOffsetString)); } Tools.getConfigData().setAnimFPS(fps); if (cmd.hasOption(CLUSTER_OP) || cmd.hasOption(HOST_OP)) { parseClusterOptions(cmd); } } catch (ParseException exp) { System.out.println("ERROR: " + exp.getMessage()); System.exit(1); } Tools.debug(null, "max mem: " + Runtime.getRuntime().maxMemory() / 1024 / 1024 + "m", 1); return autoArgs; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "initApp"
"protected static String initApp(final String[] args) { try { /* Metal */ UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); MetalLookAndFeel.setCurrentTheme( new OceanTheme() { /** e.g. arrows on split pane... */ protected ColorUIResource getPrimary1() { return new ColorUIResource( ClusterBrowser.STATUS_BACKGROUND); } /** unknown to me */ protected ColorUIResource getPrimary2() { return new ColorUIResource( ClusterBrowser.PANEL_BACKGROUND); } /** unknown to me */ protected ColorUIResource getPrimary3() { return new ColorUIResource( ClusterBrowser.PANEL_BACKGROUND); } /** Button and other borders. */ protected ColorUIResource getSecondary1() { return new ColorUIResource(AppDefaults.BACKGROUND_DARK); } protected ColorUIResource getSecondary2() { return new ColorUIResource( ClusterBrowser.PANEL_BACKGROUND); } /** Split pane divider. Line in the main menu. */ protected ColorUIResource getSecondary3() { return new ColorUIResource( ClusterBrowser.PANEL_BACKGROUND); } } ); } catch (final Exception e) { /* ignore it then */ } Thread.setDefaultUncaughtExceptionHandler( new Thread.UncaughtExceptionHandler() { public void uncaughtException(final Thread t, final Throwable ex) { <MASK>uncaughtException = true;</MASK> System.out.println(ex.toString()); System.out.println(Tools.getStackTrace(ex)); if (!uncaughtException && Tools.getGUIData().getMainFrame() != null) { Tools.appError("", ex.toString(), ex); } } }); float fps = ConfigData.DEFAULT_ANIM_FPS; final Options options = new Options(); options.addOption("h", HELP_OP, false, "print this help"); options.addOption(null, KEEP_HELPER_OP, false, "do not overwrite the lcmc-gui-helper program"); options.addOption(null, RO_OP, false, "read only mode"); options.addOption(null, OP_OP, false, "operator mode"); options.addOption(null, ADMIN_OP, false, "administrator mode"); options.addOption(null, OP_MODE_OP, true, "operating mode. <arg> can be:\n" + "ro - read only\n" + "op - operator\n" + "admin - administrator"); options.addOption(null, NOLRM_OP, false, "do not show removed resources from LRM."); options.addOption("v", VERSION_OP, false, "print version"); options.addOption(null, AUTO_OP, true, "ADVANCED USE: for testing"); options.addOption(null, PCMKTEST_OP, true, "ADVANCED USE: for testing"); options.addOption(null, DRBDTEST_OP, true, "ADVANCED USE: for testing"); options.addOption(null, VMTEST_OP, true, "ADVANCED USE: for testing"); options.addOption(null, GUITEST_OP, true, "ADVANCED USE: for testing"); options.addOption(null, NO_UPGRADE_CHECK_OP, false, "disable upgrade check"); options.addOption( null, NO_PLUGIN_CHECK_OP, false, "disable plugin check, DEPRECATED: there are no plugins"); options.addOption(null, TIGHTVNC_OP, false, "enable tight vnc viewer"); options.addOption(null, ULTRAVNC_OP, false, "enable ultra vnc viewer"); options.addOption(null, REALVNC_OP, false, "enable real vnc viewer"); options.addOption(null, BIGDRBDCONF_OP, false, "create one big drbd.conf, instead of many" + " files in drbd.d/ directory"); options.addOption(null, STAGING_DRBD_OP, false, "enable more DRBD installation options"); options.addOption(null, STAGING_PACEMAKER_OP, false, "enable more Pacemaker installation options"); options.addOption(null, VNC_PORT_OFFSET_OP, true, "offset for port forwarding"); options.addOption(null, SLOW_OP, false, "specify this if you have slow computer"); options.addOption(null, RESTORE_MOUSE_OP, false, "ADVANCED USE: for testing"); options.addOption(null, SCALE_OP, true, "scale fonts and sizes of elements in percent (100)"); options.addOption(null, ID_DSA_OP, true, "location of id_dsa file ($HOME/.ssh/id_dsa)"); options.addOption(null, ID_RSA_OP, true, "location of id_rsa file ($HOME/.ssh/id_rsa)"); options.addOption( null, KNOWN_HOSTS_OP, true, "location of known_hosts file ($HOME/.ssh/known_hosts)"); options.addOption( null, OUT_OP, true, "where to redirect the standard out"); options.addOption( null, DEBUG_OP, true, "debug level, 0 - none, 3 - all"); options.addOption("c", CLUSTER_OP, true, "define a cluster"); final Option hostOp = new Option("h", HOST_OP, true, "define a cluster, used with --cluster option"); hostOp.setArgs(10000); options.addOption(hostOp); options.addOption(null, SUDO_OP, false, "whether to use sudo, used with --cluster option"); options.addOption(null, USER_OP, true, "user to use with sudo, used with --cluster option"); options.addOption(null, PORT_OP, true, "ssh port, used with --cluster option"); options.addOption(null, ADVANCED_OP, false, "start in an advanced mode"); options.addOption(null, ONE_HOST_CLUSTER_OP, false, "allow one host cluster"); options.addOption(null, NO_PASSPHRASE_OP, false, "try no passphrase first"); options.addOption(null, EMBED_OP, false, "embed applet in the browser"); options.addOption(null, NO_EMBED_OP, false, "don't embed applet in the browser"); options.addOption( null, CMD_LOG_OP, false, "Log executed commands to the lcmc.log on the servers"); options.addOption( null, CHECK_SWING_OP, false, "ADVANCED USE: for testing"); final CommandLineParser parser = new PosixParser(); String autoArgs = null; try { final CommandLine cmd = parser.parse(options, args); if (cmd.hasOption(OUT_OP)) { final String out = cmd.getOptionValue(OUT_OP); if (out != null) { try { System.setOut( new PrintStream(new FileOutputStream(out))); } catch (final FileNotFoundException e) { System.exit(2); } } } if (cmd.hasOption(DEBUG_OP)) { final String level = cmd.getOptionValue(DEBUG_OP); if (level != null && Tools.isNumber(level)) { Tools.setDebugLevel(Integer.parseInt(level)); } else { throw new ParseException( "cannot parse debug level: " + level); } } boolean tightvnc = cmd.hasOption(TIGHTVNC_OP); boolean ultravnc = cmd.hasOption(ULTRAVNC_OP); final boolean realvnc = cmd.hasOption(REALVNC_OP); if (!tightvnc && !ultravnc && !realvnc) { if (Tools.isLinux()) { tightvnc = true; } else { tightvnc = true; ultravnc = true; } } final boolean advanced = cmd.hasOption(ADVANCED_OP); Tools.getConfigData().setAdvancedMode(advanced); Tools.getConfigData().setTightvnc(tightvnc); Tools.getConfigData().setUltravnc(ultravnc); Tools.getConfigData().setRealvnc(realvnc); Tools.getConfigData().setUpgradeCheckEnabled( !cmd.hasOption(NO_UPGRADE_CHECK_OP)); Tools.getConfigData().setBigDRBDConf( cmd.hasOption(BIGDRBDCONF_OP)); Tools.getConfigData().setStagingDrbd( cmd.hasOption(STAGING_DRBD_OP)); Tools.getConfigData().setStagingPacemaker( cmd.hasOption(STAGING_PACEMAKER_OP)); Tools.getConfigData().setNoLRM(cmd.hasOption(NOLRM_OP)); Tools.getConfigData().setKeepHelper(cmd.hasOption(KEEP_HELPER_OP)); Tools.getConfigData().setOneHostCluster( cmd.hasOption(ONE_HOST_CLUSTER_OP)); Tools.getConfigData().setNoPassphrase( cmd.hasOption(NO_PASSPHRASE_OP)); if (cmd.hasOption(EMBED_OP)) { Tools.getConfigData().setEmbed(true); } if (cmd.hasOption(NO_EMBED_OP)) { Tools.getConfigData().setEmbed(false); } if (cmd.hasOption(CMD_LOG_OP)) { Tools.getConfigData().setCmdLog(true); } if (cmd.hasOption(CHECK_SWING_OP)) { Tools.getConfigData().setCheckSwing(true); } final String pwd = System.getProperty("user.home"); final String scaleOp = cmd.getOptionValue(SCALE_OP, "100"); try { final int scale = Integer.parseInt(scaleOp); Tools.getConfigData().setScale(scale); Tools.resizeFonts(scale); } catch (java.lang.NumberFormatException e) { Tools.appWarning("cannot parse scale: " + scaleOp); } final String idDsaPath = cmd.getOptionValue(ID_DSA_OP, pwd + "/.ssh/id_dsa"); final String idRsaPath = cmd.getOptionValue(ID_RSA_OP, pwd + "/.ssh/id_rsa"); final String knownHostsPath = cmd.getOptionValue( KNOWN_HOSTS_OP, pwd + "/.ssh/known_hosts"); Tools.getConfigData().setIdDSAPath(idDsaPath); Tools.getConfigData().setIdRSAPath(idRsaPath); Tools.getConfigData().setKnownHostPath(knownHostsPath); final String opMode = cmd.getOptionValue(OP_MODE_OP); autoArgs = cmd.getOptionValue(AUTO_OP); if (cmd.hasOption(HELP_OP)) { final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar LCMC.jar [OPTIONS]", options); System.exit(0); } if (cmd.hasOption(VERSION_OP)) { System.out.println("LINUX CLUSTER MANAGEMENT CONSOLE " + Tools.getRelease() + " by Rasto Levrinc"); System.exit(0); } if (cmd.hasOption("ro") || "ro".equals(opMode)) { Tools.getConfigData().setAccessType(ConfigData.AccessType.RO); Tools.getConfigData().setMaxAccessType( ConfigData.AccessType.RO); } else if (cmd.hasOption("op") || "op".equals(opMode)) { Tools.getConfigData().setAccessType(ConfigData.AccessType.OP); Tools.getConfigData().setMaxAccessType( ConfigData.AccessType.OP); } else if (cmd.hasOption("admin") || "admin".equals(opMode)) { Tools.getConfigData().setAccessType( ConfigData.AccessType.ADMIN); Tools.getConfigData().setMaxAccessType( ConfigData.AccessType.ADMIN); } else if (opMode != null) { Tools.appWarning("unknown operating mode: " + opMode); } if (cmd.hasOption(SLOW_OP)) { fps = fps / 2; } if (cmd.hasOption(RESTORE_MOUSE_OP)) { /* restore mouse if it is stuck in pressed state, during * robot tests. */ RoboTest.restoreMouse(); } final String vncPortOffsetString = cmd.getOptionValue(VNC_PORT_OFFSET_OP); if (vncPortOffsetString != null && Tools.isNumber(vncPortOffsetString)) { Tools.getConfigData().setVncPortOffset( Integer.parseInt(vncPortOffsetString)); } Tools.getConfigData().setAnimFPS(fps); if (cmd.hasOption(CLUSTER_OP) || cmd.hasOption(HOST_OP)) { parseClusterOptions(cmd); } } catch (ParseException exp) { System.out.println("ERROR: " + exp.getMessage()); System.exit(1); } Tools.debug(null, "max mem: " + Runtime.getRuntime().maxMemory() / 1024 / 1024 + "m", 1); return autoArgs; }"
Inversion-Mutation
megadiff
"public void uncaughtException(final Thread t, final Throwable ex) { System.out.println(ex.toString()); System.out.println(Tools.getStackTrace(ex)); if (!uncaughtException && Tools.getGUIData().getMainFrame() != null) { uncaughtException = true; Tools.appError("", ex.toString(), ex); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "uncaughtException"
"public void uncaughtException(final Thread t, final Throwable ex) { <MASK>uncaughtException = true;</MASK> System.out.println(ex.toString()); System.out.println(Tools.getStackTrace(ex)); if (!uncaughtException && Tools.getGUIData().getMainFrame() != null) { Tools.appError("", ex.toString(), ex); } }"
Inversion-Mutation
megadiff
"private void responseImage(String contentPath) throws Exception { HttpServletResponse response = Struts2Utils.getResponse(); HttpServletRequest request = Struts2Utils.getRequest(); if (StringUtils.isBlank(contentPath)) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "path parametter is required."); return; } contentPath = URLDecoder.decode(contentPath, "UTF-8"); String realPath = Constants.LOCKER_STORAGE + new String(contentPath.getBytes("iso-8859-1"), "utf-8"); ContentInfo contentInfo = getContentInfo(realPath); //根据Etag或ModifiedSince Header判断客户端的缓存文件是否有效, 如仍有效则设置返回码为304,直接返回. if (!ServletUtils.checkIfModifiedSince(request, response, contentInfo.lastModified) || !ServletUtils.checkIfNoneMatchEtag(request, response, contentInfo.etag)) { return; } ServletUtils.setExpiresHeader(response, ONE_YEAR_SECONDS); ServletUtils.setLastModifiedHeader(response, System.currentTimeMillis()); ServletUtils.setEtag(response, contentInfo.etag); response.setContentType(contentInfo.mimeType); //设置弹出下载文件请求窗口的Header if (request.getParameter("download") != null) { ServletUtils.setFileDownloadHeader(response, contentInfo.fileName); } //构造OutputStream OutputStream output; if (checkAccetptGzip(request) && contentInfo.needGzip) { //使用压缩传输的outputstream, 使用http1.1 trunked编码不设置content-length. output = buildGzipOutputStream(response); } else { //使用普通outputstream, 设置content-length. response.setContentLength(contentInfo.length); output = response.getOutputStream(); } //高效读取文件内容并输出,然后关闭input file try { FileUtils.copyFile(contentInfo.file, output); output.flush(); } catch (Exception e) { logger.error(e.getMessage()); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "responseImage"
"private void responseImage(String contentPath) throws Exception { HttpServletResponse response = Struts2Utils.getResponse(); HttpServletRequest request = Struts2Utils.getRequest(); if (StringUtils.isBlank(contentPath)) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "path parametter is required."); return; } contentPath = URLDecoder.decode(contentPath, "UTF-8"); String realPath = Constants.LOCKER_STORAGE + new String(contentPath.getBytes("iso-8859-1"), "utf-8"); ContentInfo contentInfo = getContentInfo(realPath); //根据Etag或ModifiedSince Header判断客户端的缓存文件是否有效, 如仍有效则设置返回码为304,直接返回. if (!ServletUtils.checkIfModifiedSince(request, response, contentInfo.lastModified) || !ServletUtils.checkIfNoneMatchEtag(request, response, contentInfo.etag)) { return; } ServletUtils.setExpiresHeader(response, ONE_YEAR_SECONDS); ServletUtils.setLastModifiedHeader(response, System.currentTimeMillis()); ServletUtils.setEtag(response, contentInfo.etag); response.setContentType(contentInfo.mimeType); //设置弹出下载文件请求窗口的Header if (request.getParameter("download") != null) { ServletUtils.setFileDownloadHeader(response, contentInfo.fileName); } //构造OutputStream OutputStream output; if (checkAccetptGzip(request) && contentInfo.needGzip) { //使用压缩传输的outputstream, 使用http1.1 trunked编码不设置content-length. output = buildGzipOutputStream(response); } else { //使用普通outputstream, 设置content-length. response.setContentLength(contentInfo.length); output = response.getOutputStream(); } //高效读取文件内容并输出,然后关闭input file try { FileUtils.copyFile(contentInfo.file, output); } catch (Exception e) { logger.error(e.getMessage()); } <MASK>output.flush();</MASK> }"
Inversion-Mutation
megadiff
"@Override public void handleMessage(Message msg) { BluetoothAudioGateway.IncomingConnectionInfo info = (BluetoothAudioGateway.IncomingConnectionInfo)msg.obj; int type = BluetoothHandsfree.TYPE_UNKNOWN; switch(msg.what) { case BluetoothAudioGateway.MSG_INCOMING_HEADSET_CONNECTION: type = BluetoothHandsfree.TYPE_HEADSET; break; case BluetoothAudioGateway.MSG_INCOMING_HANDSFREE_CONNECTION: type = BluetoothHandsfree.TYPE_HANDSFREE; break; } Log.i(TAG, "Incoming rfcomm (" + BluetoothHandsfree.typeToString(type) + ") connection from " + info.mRemoteDevice + "on channel " + info.mRfcommChan); int priority = BluetoothHeadset.PRIORITY_OFF; HeadsetBase headset; try { priority = mBinder.getPriority(info.mRemoteDevice); } catch (RemoteException e) {} if (priority <= BluetoothHeadset.PRIORITY_OFF) { Log.i(TAG, "Rejecting incoming connection because priority = " + priority); headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice, info.mSocketFd, info.mRfcommChan, null); headset.disconnect(); return; } switch (mState) { case BluetoothHeadset.STATE_DISCONNECTED: // headset connecting us, lets join mRemoteDevice = info.mRemoteDevice; setState(BluetoothHeadset.STATE_CONNECTING); headset = new HeadsetBase(mPowerManager, mAdapter, mRemoteDevice, info.mSocketFd, info.mRfcommChan, mConnectedStatusHandler); mHeadsetType = type; mConnectingStatusHandler.obtainMessage(RFCOMM_CONNECTED, headset).sendToTarget(); break; case BluetoothHeadset.STATE_CONNECTING: if (!info.mRemoteDevice.equals(mRemoteDevice)) { // different headset, ignoring Log.i(TAG, "Already attempting connect to " + mRemoteDevice + ", disconnecting " + info.mRemoteDevice); headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice, info.mSocketFd, info.mRfcommChan, null); headset.disconnect(); } // If we are here, we are in danger of a race condition // incoming rfcomm connection, but we are also attempting an // outgoing connection. Lets try and interrupt the outgoing // connection. Log.i(TAG, "Incoming and outgoing connections to " + info.mRemoteDevice + ". Cancel outgoing connection."); if (mConnectThread != null) { mConnectThread.interrupt(); } // Now continue with new connection, including calling callback mHeadset = new HeadsetBase(mPowerManager, mAdapter, mRemoteDevice, info.mSocketFd, info.mRfcommChan, mConnectedStatusHandler); mHeadsetType = type; setState(BluetoothHeadset.STATE_CONNECTED, BluetoothHeadset.RESULT_SUCCESS); mBtHandsfree.connectHeadset(mHeadset, mHeadsetType); // Make sure that old outgoing connect thread is dead. if (mConnectThread != null) { try { // TODO: Don't block in the main thread Log.w(TAG, "Block in main thread to join stale outgoing connection thread"); mConnectThread.join(); } catch (InterruptedException e) { Log.e(TAG, "Connection cancelled twice eh?", e); } mConnectThread = null; } if (DBG) log("Successfully used incoming connection, and cancelled outgoing " + " connection"); break; case BluetoothHeadset.STATE_CONNECTED: Log.i(TAG, "Already connected to " + mRemoteDevice + ", disconnecting " + info.mRemoteDevice); headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice, info.mSocketFd, info.mRfcommChan, null); headset.disconnect(); break; } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handleMessage"
"@Override public void handleMessage(Message msg) { BluetoothAudioGateway.IncomingConnectionInfo info = (BluetoothAudioGateway.IncomingConnectionInfo)msg.obj; int type = BluetoothHandsfree.TYPE_UNKNOWN; switch(msg.what) { case BluetoothAudioGateway.MSG_INCOMING_HEADSET_CONNECTION: type = BluetoothHandsfree.TYPE_HEADSET; break; case BluetoothAudioGateway.MSG_INCOMING_HANDSFREE_CONNECTION: type = BluetoothHandsfree.TYPE_HANDSFREE; break; } Log.i(TAG, "Incoming rfcomm (" + BluetoothHandsfree.typeToString(type) + ") connection from " + info.mRemoteDevice + "on channel " + info.mRfcommChan); int priority = BluetoothHeadset.PRIORITY_OFF; HeadsetBase headset; try { priority = mBinder.getPriority(info.mRemoteDevice); } catch (RemoteException e) {} if (priority <= BluetoothHeadset.PRIORITY_OFF) { Log.i(TAG, "Rejecting incoming connection because priority = " + priority); headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice, info.mSocketFd, info.mRfcommChan, null); headset.disconnect(); return; } switch (mState) { case BluetoothHeadset.STATE_DISCONNECTED: // headset connecting us, lets join <MASK>setState(BluetoothHeadset.STATE_CONNECTING);</MASK> mRemoteDevice = info.mRemoteDevice; headset = new HeadsetBase(mPowerManager, mAdapter, mRemoteDevice, info.mSocketFd, info.mRfcommChan, mConnectedStatusHandler); mHeadsetType = type; mConnectingStatusHandler.obtainMessage(RFCOMM_CONNECTED, headset).sendToTarget(); break; case BluetoothHeadset.STATE_CONNECTING: if (!info.mRemoteDevice.equals(mRemoteDevice)) { // different headset, ignoring Log.i(TAG, "Already attempting connect to " + mRemoteDevice + ", disconnecting " + info.mRemoteDevice); headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice, info.mSocketFd, info.mRfcommChan, null); headset.disconnect(); } // If we are here, we are in danger of a race condition // incoming rfcomm connection, but we are also attempting an // outgoing connection. Lets try and interrupt the outgoing // connection. Log.i(TAG, "Incoming and outgoing connections to " + info.mRemoteDevice + ". Cancel outgoing connection."); if (mConnectThread != null) { mConnectThread.interrupt(); } // Now continue with new connection, including calling callback mHeadset = new HeadsetBase(mPowerManager, mAdapter, mRemoteDevice, info.mSocketFd, info.mRfcommChan, mConnectedStatusHandler); mHeadsetType = type; setState(BluetoothHeadset.STATE_CONNECTED, BluetoothHeadset.RESULT_SUCCESS); mBtHandsfree.connectHeadset(mHeadset, mHeadsetType); // Make sure that old outgoing connect thread is dead. if (mConnectThread != null) { try { // TODO: Don't block in the main thread Log.w(TAG, "Block in main thread to join stale outgoing connection thread"); mConnectThread.join(); } catch (InterruptedException e) { Log.e(TAG, "Connection cancelled twice eh?", e); } mConnectThread = null; } if (DBG) log("Successfully used incoming connection, and cancelled outgoing " + " connection"); break; case BluetoothHeadset.STATE_CONNECTED: Log.i(TAG, "Already connected to " + mRemoteDevice + ", disconnecting " + info.mRemoteDevice); headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice, info.mSocketFd, info.mRfcommChan, null); headset.disconnect(); break; } }"
Inversion-Mutation
megadiff
"private void performOperation(IFileBuffer fileBuffer, IFileBufferOperation operation, IProgressMonitor progressMonitor) throws CoreException, OperationCanceledException { ISchedulingRule rule= fileBuffer.computeCommitRule(); IJobManager manager= Platform.getJobManager(); try { manager.beginRule(rule, progressMonitor); String name= fileBuffer.getLocation().lastSegment(); progressMonitor.beginTask(name, 100); try { IProgressMonitor subMonitor= Progress.getSubMonitor(progressMonitor, 100); operation.run(fileBuffer, subMonitor); subMonitor.done(); } finally { progressMonitor.done(); } } finally { manager.endRule(rule); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "performOperation"
"private void performOperation(IFileBuffer fileBuffer, IFileBufferOperation operation, IProgressMonitor progressMonitor) throws CoreException, OperationCanceledException { ISchedulingRule rule= fileBuffer.computeCommitRule(); IJobManager manager= Platform.getJobManager(); <MASK>manager.beginRule(rule, progressMonitor);</MASK> try { String name= fileBuffer.getLocation().lastSegment(); progressMonitor.beginTask(name, 100); try { IProgressMonitor subMonitor= Progress.getSubMonitor(progressMonitor, 100); operation.run(fileBuffer, subMonitor); subMonitor.done(); } finally { progressMonitor.done(); } } finally { manager.endRule(rule); } }"
Inversion-Mutation
megadiff
"public final void disable() { disableModule(); synchronized (lock) { enabled = false; } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "disable"
"public final void disable() { synchronized (lock) { enabled = false; } <MASK>disableModule();</MASK> }"
Inversion-Mutation
megadiff
"public boolean onTouchEvent(MotionEvent event) { if (myAction != null) { new Handler().post(myAction); } myDialog.dismiss(); return true; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onTouchEvent"
"public boolean onTouchEvent(MotionEvent event) { <MASK>myDialog.dismiss();</MASK> if (myAction != null) { new Handler().post(myAction); } return true; }"
Inversion-Mutation
megadiff
"@Override protected Sample getPoints() throws Exception, InterruptedException, ExecutionException { IplImage grabbed; CanvasFrame frame = null; FrameRecorder recorder = null; Loader.load(opencv_objdetect.class); String urlToDownload = "https://dl.dropbox.com/u/8720454/haarcascade_mcs_mouth.xml"; if(!new File(Utils.getFileNameFromUrl(urlToDownload)).exists()) Utils.get(urlToDownload); CvHaarClassifierCascade classifier = new CvHaarClassifierCascade(cvLoad(Utils.getFileNameFromUrl(urlToDownload))); int width = grabber.getImageWidth(); int height = grabber.getImageHeight(); if(isGui()){ frame = new CanvasFrame(getSample().getId(), CanvasFrame.getDefaultGamma()/grabber.getGamma()); frame.setDefaultCloseOperation(CanvasFrame.EXIT_ON_CLOSE); if(isOutput()){ recorder = FFmpegFrameRecorder.createDefault(getSample().getId().split("\\.")[0] + "-output.MOV",width, height); recorder.start(); } } IplImage manipulated = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 1); CvMemStorage storage = CvMemStorage.create(); while((grabbed = grabber.grab()) != null){ cvClearMemStorage(storage); CvMat grabbedMatrix = grabbed.asCvMat(); cvCvtColor(grabbed, manipulated, CV_RGB2GRAY); CvSeq mouths = cvHaarDetectObjects(manipulated, classifier, storage, 1.8, 1, CV_HAAR_FIND_BIGGEST_OBJECT); CvRect r = new CvRect(cvGetSeqElem(mouths, 0)); channels = grabbed.nChannels(); int x = r.x(), y = r.y(), w = r.width(), h = r.height(); cvRectangle(grabbed, cvPoint(x, y), cvPoint(x+w, y+h), CvScalar.RED, 1, CV_AA, 0); double[] matrix = grabbedMatrix.get(); final double[][] roi = new double[h][w * channels]; for (int i = 0; i < h; i++) { for (int j = 0; j < w * channels; j++) { roi[i][j] = matrix[(x * y * channels) + (i * width) + j]; } } List<Future<int[]>> points = new Vector<Future<int[]>>(); final Future<double[][]> getH = executor.submit(new Callable<double[][]>() { @Override public double[][] call() throws Exception { return getH(roi); } }); final Future<double[][]> getL = executor.submit(new Callable<double[][]>() { @Override public double[][] call() throws Exception { return getL(roi); } }); final Future<double[][][]> getRsup = executor.submit(new Callable<double[][][]>() { @Override public double[][][] call() throws Exception { return getRsup(getH.get(), getL.get()); } }); final Future<double[][]> getRinf = executor.submit(new Callable<double[][]>() { @Override public double[][] call() throws Exception { return getRinf(getH.get(), getL.get()); } }); final Future<int[]> getUpper = executor.submit(new Callable<int[]>() { @Override public int[] call() throws Exception { return getUpper(getRsup.get(), getRinf.get()); } }); points.add(getUpper); final Future<double[][]> getLmini = executor.submit(new Callable<double[][]>() { @Override public double[][] call() throws Exception { return Lmini(getL.get()); } }); final Future<int[]> getRight = executor.submit(new Callable<int[]>() { @Override public int[] call() throws Exception { return getRight(getL.get(), getLmini.get()); } }); points.add(getRight); final Future<int[]> getLeft = executor.submit(new Callable<int[]>() { @Override public int[] call() throws Exception { return getLeft(getL.get(), getLmini.get()); } }); points.add(getLeft); final Future<int[]> getLower = executor.submit(new Callable<int[]>() { @Override public int[] call() throws Exception { return getLower(getLeft.get(), getRight.get(), getRinf.get()); } }); points.add(getLower); List<Integer> frameCoordinates = new Vector<Integer>(); for (Future<int[]> point : points) { int coordinateX = point.get()[0], coordinateY = point.get()[1]; frameCoordinates.add(coordinateX); frameCoordinates.add(coordinateY); if(isGui()){ cvCircle((CvArr)grabbed, new CvPoint(coordinateX + x, coordinateY + y), 10, CvScalar.RED, 3, 0, 0); frame.showImage(grabbed); if(isOutput()){ recorder.record(grabbed); } } } getSample().getMatrix().add(frameCoordinates); } storage.release(); if(isGui()){ frame.dispose(); if(isOutput()){ recorder.stop(); } } return getSample(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getPoints"
"@Override protected Sample getPoints() throws Exception, InterruptedException, ExecutionException { IplImage grabbed; CanvasFrame frame = null; FrameRecorder recorder = null; <MASK>List<Future<int[]>> points = new Vector<Future<int[]>>();</MASK> Loader.load(opencv_objdetect.class); String urlToDownload = "https://dl.dropbox.com/u/8720454/haarcascade_mcs_mouth.xml"; if(!new File(Utils.getFileNameFromUrl(urlToDownload)).exists()) Utils.get(urlToDownload); CvHaarClassifierCascade classifier = new CvHaarClassifierCascade(cvLoad(Utils.getFileNameFromUrl(urlToDownload))); int width = grabber.getImageWidth(); int height = grabber.getImageHeight(); if(isGui()){ frame = new CanvasFrame(getSample().getId(), CanvasFrame.getDefaultGamma()/grabber.getGamma()); frame.setDefaultCloseOperation(CanvasFrame.EXIT_ON_CLOSE); if(isOutput()){ recorder = FFmpegFrameRecorder.createDefault(getSample().getId().split("\\.")[0] + "-output.MOV",width, height); recorder.start(); } } IplImage manipulated = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 1); CvMemStorage storage = CvMemStorage.create(); while((grabbed = grabber.grab()) != null){ cvClearMemStorage(storage); CvMat grabbedMatrix = grabbed.asCvMat(); cvCvtColor(grabbed, manipulated, CV_RGB2GRAY); CvSeq mouths = cvHaarDetectObjects(manipulated, classifier, storage, 1.8, 1, CV_HAAR_FIND_BIGGEST_OBJECT); CvRect r = new CvRect(cvGetSeqElem(mouths, 0)); channels = grabbed.nChannels(); int x = r.x(), y = r.y(), w = r.width(), h = r.height(); cvRectangle(grabbed, cvPoint(x, y), cvPoint(x+w, y+h), CvScalar.RED, 1, CV_AA, 0); double[] matrix = grabbedMatrix.get(); final double[][] roi = new double[h][w * channels]; for (int i = 0; i < h; i++) { for (int j = 0; j < w * channels; j++) { roi[i][j] = matrix[(x * y * channels) + (i * width) + j]; } } final Future<double[][]> getH = executor.submit(new Callable<double[][]>() { @Override public double[][] call() throws Exception { return getH(roi); } }); final Future<double[][]> getL = executor.submit(new Callable<double[][]>() { @Override public double[][] call() throws Exception { return getL(roi); } }); final Future<double[][][]> getRsup = executor.submit(new Callable<double[][][]>() { @Override public double[][][] call() throws Exception { return getRsup(getH.get(), getL.get()); } }); final Future<double[][]> getRinf = executor.submit(new Callable<double[][]>() { @Override public double[][] call() throws Exception { return getRinf(getH.get(), getL.get()); } }); final Future<int[]> getUpper = executor.submit(new Callable<int[]>() { @Override public int[] call() throws Exception { return getUpper(getRsup.get(), getRinf.get()); } }); points.add(getUpper); final Future<double[][]> getLmini = executor.submit(new Callable<double[][]>() { @Override public double[][] call() throws Exception { return Lmini(getL.get()); } }); final Future<int[]> getRight = executor.submit(new Callable<int[]>() { @Override public int[] call() throws Exception { return getRight(getL.get(), getLmini.get()); } }); points.add(getRight); final Future<int[]> getLeft = executor.submit(new Callable<int[]>() { @Override public int[] call() throws Exception { return getLeft(getL.get(), getLmini.get()); } }); points.add(getLeft); final Future<int[]> getLower = executor.submit(new Callable<int[]>() { @Override public int[] call() throws Exception { return getLower(getLeft.get(), getRight.get(), getRinf.get()); } }); points.add(getLower); List<Integer> frameCoordinates = new Vector<Integer>(); for (Future<int[]> point : points) { int coordinateX = point.get()[0], coordinateY = point.get()[1]; frameCoordinates.add(coordinateX); frameCoordinates.add(coordinateY); if(isGui()){ cvCircle((CvArr)grabbed, new CvPoint(coordinateX + x, coordinateY + y), 10, CvScalar.RED, 3, 0, 0); frame.showImage(grabbed); if(isOutput()){ recorder.record(grabbed); } } } getSample().getMatrix().add(frameCoordinates); } storage.release(); if(isGui()){ frame.dispose(); if(isOutput()){ recorder.stop(); } } return getSample(); }"
Inversion-Mutation
megadiff
"public void init( String settingsFile ) { initLog(); SoapUI.setSoapUICore( this ); loadExternalLibraries(); initSettings( settingsFile == null ? DEFAULT_SETTINGS_FILE : settingsFile ); initExtensions( getExtensionClassLoader() ); initCoreComponents(); // this is to provoke initialization SoapVersion.Soap11.equals( SoapVersion.Soap12 ); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "init"
"public void init( String settingsFile ) { initLog(); SoapUI.setSoapUICore( this ); loadExternalLibraries(); initSettings( settingsFile == null ? DEFAULT_SETTINGS_FILE : settingsFile ); <MASK>initCoreComponents();</MASK> initExtensions( getExtensionClassLoader() ); // this is to provoke initialization SoapVersion.Soap11.equals( SoapVersion.Soap12 ); }"
Inversion-Mutation
megadiff
"public static Properties parseRequestLine(String cmd, String args, Properties prop, String virtualHost) { // getting the last request line for debugging purposes String prevRequestLine = prop.containsKey(CONNECTION_PROP_REQUESTLINE)? prop.getProperty(CONNECTION_PROP_REQUESTLINE) : ""; // reset property from previous run prop.clear(); // storing informations about the request prop.setProperty(CONNECTION_PROP_METHOD, cmd); prop.setProperty(CONNECTION_PROP_REQUESTLINE,cmd + " " + args); prop.setProperty(CONNECTION_PROP_PREV_REQUESTLINE,prevRequestLine); // this parses a whole URL if (args.length() == 0) { prop.setProperty(CONNECTION_PROP_HOST, virtualHost); prop.setProperty(CONNECTION_PROP_PATH, "/"); prop.setProperty(CONNECTION_PROP_HTTP_VER, HTTP_VERSION_0_9); prop.setProperty(CONNECTION_PROP_EXT, ""); return prop; } // store the version propery "HTTP" and cut the query at both ends int sep = args.lastIndexOf(" "); if ((sep >= 0)&&(args.substring(sep + 1).toLowerCase().startsWith("http/"))) { // HTTP version is given prop.setProperty(CONNECTION_PROP_HTTP_VER, args.substring(sep + 1).trim()); args = args.substring(0, sep).trim(); // cut off HTTP version mark } else { // HTTP version is not given, it will be treated as ver 0.9 prop.setProperty(CONNECTION_PROP_HTTP_VER, HTTP_VERSION_0_9); } // replacing spaces in the url string correctly args = args.replaceAll(" ","%20"); // properties of the query are stored with the prefix "&" // additionally, the values URL and ARGC are computed String argsString = ""; sep = args.indexOf("?"); if (sep >= 0) { // there are values attached to the query string argsString = args.substring(sep + 1); // cut head from tail of query args = args.substring(0, sep); } prop.setProperty(CONNECTION_PROP_URL, args); // store URL //System.out.println("HTTPD: ARGS=" + argsString); if (argsString.length() != 0) prop.setProperty(CONNECTION_PROP_ARGS, argsString); // store arguments in original form // finally find host string String path; if (args.toUpperCase().startsWith("HTTP://")) { // a host was given. extract it and set path args = args.substring(7); sep = args.indexOf("/"); if (sep < 0) { // this is a malformed url, something like // http://index.html // we are lazy and guess that it means // /index.html // which is a localhost access to the file servlet prop.setProperty(CONNECTION_PROP_HOST, args); path = "/"; } else { // THIS IS THE "GOOD" CASE // a perfect formulated url String dstHostSocket = args.substring(0, sep); prop.setProperty(CONNECTION_PROP_HOST, (httpd.isThisHostName(dstHostSocket)?virtualHost:dstHostSocket)); path = args.substring(sep); // yes, including beginning "/" } } else { // no host in url. set path if (args.startsWith("/")) { // thats also fine, its a perfect localhost access // in this case, we simulate a // http://localhost/s // access by setting a virtual host prop.setProperty(CONNECTION_PROP_HOST, virtualHost); path = args; } else { // the client 'forgot' to set a leading '/' // this is the same case as above, with some lazyness prop.setProperty(CONNECTION_PROP_HOST, virtualHost); path = "/" + args; } } prop.setProperty(CONNECTION_PROP_PATH, path); // find out file extension (we already stripped ?-parameters from args) String ext = ""; // default when no file extension sep = path.lastIndexOf("."); if (sep >= 0) { int ancpos = path.indexOf("#", sep + 1); if (ancpos >= sep) { // ex: /foo/bar.html#xy => html ext = path.substring(sep + 1, ancpos).toLowerCase(); } else { // ex: /foo/bar.php => php ext = path.substring(sep + 1).toLowerCase(); } } prop.setProperty(CONNECTION_PROP_EXT, ext); return prop; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "parseRequestLine"
"public static Properties parseRequestLine(String cmd, String args, Properties prop, String virtualHost) { // getting the last request line for debugging purposes String prevRequestLine = prop.containsKey(CONNECTION_PROP_REQUESTLINE)? prop.getProperty(CONNECTION_PROP_REQUESTLINE) : ""; // reset property from previous run prop.clear(); // storing informations about the request prop.setProperty(CONNECTION_PROP_METHOD, cmd); prop.setProperty(CONNECTION_PROP_REQUESTLINE,cmd + " " + args); prop.setProperty(CONNECTION_PROP_PREV_REQUESTLINE,prevRequestLine); // this parses a whole URL if (args.length() == 0) { prop.setProperty(CONNECTION_PROP_HOST, virtualHost); prop.setProperty(CONNECTION_PROP_PATH, "/"); prop.setProperty(CONNECTION_PROP_HTTP_VER, HTTP_VERSION_0_9); prop.setProperty(CONNECTION_PROP_EXT, ""); return prop; } // store the version propery "HTTP" and cut the query at both ends int sep = args.lastIndexOf(" "); if ((sep >= 0)&&(args.substring(sep + 1).toLowerCase().startsWith("http/"))) { // HTTP version is given prop.setProperty(CONNECTION_PROP_HTTP_VER, args.substring(sep + 1).trim()); args = args.substring(0, sep).trim(); // cut off HTTP version mark } else { // HTTP version is not given, it will be treated as ver 0.9 prop.setProperty(CONNECTION_PROP_HTTP_VER, HTTP_VERSION_0_9); } // replacing spaces in the url string correctly args = args.replaceAll(" ","%20"); // properties of the query are stored with the prefix "&" // additionally, the values URL and ARGC are computed String argsString = ""; sep = args.indexOf("?"); if (sep >= 0) { // there are values attached to the query string argsString = args.substring(sep + 1); // cut head from tail of query args = args.substring(0, sep); } prop.setProperty(CONNECTION_PROP_URL, args); // store URL //System.out.println("HTTPD: ARGS=" + argsString); if (argsString.length() != 0) prop.setProperty(CONNECTION_PROP_ARGS, argsString); // store arguments in original form // finally find host string String path; if (args.toUpperCase().startsWith("HTTP://")) { // a host was given. extract it and set path args = args.substring(7); sep = args.indexOf("/"); if (sep < 0) { // this is a malformed url, something like // http://index.html // we are lazy and guess that it means // /index.html // which is a localhost access to the file servlet prop.setProperty(CONNECTION_PROP_HOST, args); path = "/"; } else { // THIS IS THE "GOOD" CASE // a perfect formulated url String dstHostSocket = args.substring(0, sep); prop.setProperty(CONNECTION_PROP_HOST, (httpd.isThisHostName(dstHostSocket)?virtualHost:dstHostSocket)); path = args.substring(sep); // yes, including beginning "/" } } else { // no host in url. set path if (args.startsWith("/")) { // thats also fine, its a perfect localhost access // in this case, we simulate a // http://localhost/s // access by setting a virtual host prop.setProperty(CONNECTION_PROP_HOST, virtualHost); path = args; } else { // the client 'forgot' to set a leading '/' // this is the same case as above, with some lazyness prop.setProperty(CONNECTION_PROP_HOST, virtualHost); path = "/" + args; } <MASK>prop.setProperty(CONNECTION_PROP_PATH, path);</MASK> } // find out file extension (we already stripped ?-parameters from args) String ext = ""; // default when no file extension sep = path.lastIndexOf("."); if (sep >= 0) { int ancpos = path.indexOf("#", sep + 1); if (ancpos >= sep) { // ex: /foo/bar.html#xy => html ext = path.substring(sep + 1, ancpos).toLowerCase(); } else { // ex: /foo/bar.php => php ext = path.substring(sep + 1).toLowerCase(); } } prop.setProperty(CONNECTION_PROP_EXT, ext); return prop; }"
Inversion-Mutation
megadiff
"public void doGet(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException, ServletException { WaybackRequest wbRequest = (WaybackRequest) httpRequest .getAttribute(WMREQUEST_ATTRIBUTE); ReplayRenderer renderer; try { renderer = wayback.getReplayRenderer(); } catch (ConfigurationException e1) { // e1.printStackTrace(); throw new ServletException(e1); } Resource resource = null; try { ResourceIndex idx = wayback.getResourceIndex(); ResourceStore store = wayback.getResourceStore(); ResultURIConverter uriConverter = wayback.getURIConverter(); if (wbRequest == null) { wbRequest = qp.parseQuery(httpRequest); } SearchResults results = idx.query(wbRequest); // TODO: check which versions are actually accessible right now? SearchResult closest = getClosest(results, wbRequest); resource = store.retrieveResource(closest); String requestedDateStr = wbRequest.get( WaybackConstants.REQUEST_EXACT_DATE); String closestDateStr = closest.get( WaybackConstants.RESULT_CAPTURE_DATE); // some capture dates are not 14 digits, only compare as many // dateStr digits as are in the capture date: if(!closestDateStr.equals( requestedDateStr.substring(0,closestDateStr.length()))) { // redirect to the actual date: renderer.renderRedirect(httpRequest, httpResponse, wbRequest, closest, resource, uriConverter); } else { renderer.renderResource(httpRequest, httpResponse, wbRequest, closest, resource, uriConverter); } } catch (ResourceNotInArchiveException nia) { LOGGER.info("NotInArchive\t" + wbRequest.get(WaybackConstants.REQUEST_URL)); renderer.renderException(httpRequest, httpResponse, wbRequest, nia); } catch (WaybackException wbe) { renderer.renderException(httpRequest, httpResponse, wbRequest, wbe); } catch (Exception e) { // TODO show something Wayback'ish to the user rather than letting // the container deal? //e.printStackTrace(); throw new ServletException(e); } finally { if (resource != null) { resource.close(); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doGet"
"public void doGet(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException, ServletException { WaybackRequest wbRequest = (WaybackRequest) httpRequest .getAttribute(WMREQUEST_ATTRIBUTE); ReplayRenderer renderer; try { renderer = wayback.getReplayRenderer(); } catch (ConfigurationException e1) { // e1.printStackTrace(); throw new ServletException(e1); } Resource resource = null; try { ResourceIndex idx = wayback.getResourceIndex(); ResourceStore store = wayback.getResourceStore(); ResultURIConverter uriConverter = wayback.getURIConverter(); if (wbRequest == null) { wbRequest = qp.parseQuery(httpRequest); } SearchResults results = idx.query(wbRequest); // TODO: check which versions are actually accessible right now? SearchResult closest = getClosest(results, wbRequest); String requestedDateStr = wbRequest.get( WaybackConstants.REQUEST_EXACT_DATE); String closestDateStr = closest.get( WaybackConstants.RESULT_CAPTURE_DATE); // some capture dates are not 14 digits, only compare as many // dateStr digits as are in the capture date: if(!closestDateStr.equals( requestedDateStr.substring(0,closestDateStr.length()))) { // redirect to the actual date: renderer.renderRedirect(httpRequest, httpResponse, wbRequest, closest, resource, uriConverter); } else { <MASK>resource = store.retrieveResource(closest);</MASK> renderer.renderResource(httpRequest, httpResponse, wbRequest, closest, resource, uriConverter); } } catch (ResourceNotInArchiveException nia) { LOGGER.info("NotInArchive\t" + wbRequest.get(WaybackConstants.REQUEST_URL)); renderer.renderException(httpRequest, httpResponse, wbRequest, nia); } catch (WaybackException wbe) { renderer.renderException(httpRequest, httpResponse, wbRequest, wbe); } catch (Exception e) { // TODO show something Wayback'ish to the user rather than letting // the container deal? //e.printStackTrace(); throw new ServletException(e); } finally { if (resource != null) { resource.close(); } } }"
Inversion-Mutation
megadiff
"public Main(DeviceEntry defaultDevice) { this.logQueueAppender = new QueueAppender(1024); Logger.addAppender(logQueueAppender); JMenuBar menuBar = new JMenuBar(); JMenu menuFile = new JMenu("File"); menuOpenJADFile = new JMenuItem("Open JAD File..."); menuOpenJADFile.addActionListener(menuOpenJADFileListener); menuFile.add(menuOpenJADFile); menuOpenJADURL = new JMenuItem("Open JAD URL..."); menuOpenJADURL.addActionListener(menuOpenJADURLListener); menuFile.add(menuOpenJADURL); JMenuItem menuItemTmp = new JMenuItem("Close MIDlet"); menuItemTmp.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK)); menuItemTmp.addActionListener(menuCloseMidletListener); menuFile.add(menuItemTmp); menuFile.addSeparator(); JMRUMenu urlsMRU = new JMRUMenu("Recent MIDlets..."); urlsMRU.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { if (event instanceof JMRUMenu.MRUActionEvent) { Common.openJadUrlSafe(((MidletURLReference) ((JMRUMenu.MRUActionEvent) event).getSourceMRU()) .getUrl()); if (recordStoreManagerDialog != null) { recordStoreManagerDialog.refresh(); } } } }); Config.getUrlsMRU().setListener(urlsMRU); menuFile.add(urlsMRU); menuFile.addSeparator(); menuSaveForWeb = new JMenuItem("Save for Web..."); menuSaveForWeb.addActionListener(menuSaveForWebListener); menuFile.add(menuSaveForWeb); menuFile.addSeparator(); JMenuItem menuItem = new JMenuItem("Exit"); menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK)); menuItem.addActionListener(menuExitListener); menuFile.add(menuItem); JMenu menuOptions = new JMenu("Options"); menuSelectDevice = new JMenuItem("Select device..."); menuSelectDevice.addActionListener(menuSelectDeviceListener); menuOptions.add(menuSelectDevice); menuStartCapture = new JMenuItem("Start capture to GIF..."); menuStartCapture.addActionListener(menuStartCaptureListener); menuOptions.add(menuStartCapture); menuStopCapture = new JMenuItem("Stop capture"); menuStopCapture.setEnabled(false); menuStopCapture.addActionListener(menuStopCaptureListener); menuOptions.add(menuStopCapture); menuMIDletNetworkConnection = new JCheckBoxMenuItem("MIDlet Network access"); menuMIDletNetworkConnection.setState(true); menuMIDletNetworkConnection.addActionListener(menuMIDletNetworkConnectionListener); menuOptions.add(menuMIDletNetworkConnection); menuRecordStoreManager = new JCheckBoxMenuItem("Record Store Manager"); menuRecordStoreManager.setState(false); menuRecordStoreManager.addActionListener(menuRecordStoreManagerListener); menuOptions.add(menuRecordStoreManager); menuLogConsole = new JCheckBoxMenuItem("Log console"); menuLogConsole.setState(false); menuLogConsole.addActionListener(menuLogConsoleListener); menuOptions.add(menuLogConsole); menuOptions.addSeparator(); JCheckBoxMenuItem menuShowMouseCoordinates = new JCheckBoxMenuItem("Mouse coordinates"); menuShowMouseCoordinates.setState(false); menuShowMouseCoordinates.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { devicePanel.switchShowMouseCoordinates(); } }); menuOptions.add(menuShowMouseCoordinates); JMenu menuHelp = new JMenu("Help"); JMenuItem menuAbout = new JMenuItem("About"); menuAbout.addActionListener(menuAboutListener); menuHelp.add(menuAbout); menuBar.add(menuFile); menuBar.add(menuOptions); menuBar.add(menuHelp); setJMenuBar(menuBar); setTitle("MicroEmulator"); this.setIconImage(Toolkit.getDefaultToolkit().getImage(Main.class.getResource("/org/microemu/icon.png"))); addWindowListener(windowListener); Config.loadConfig(defaultDevice, emulatorContext); Rectangle window = Config.getWindow("main", new Rectangle(0, 0, 160, 120)); this.setLocation(window.x, window.y); getContentPane().add(createContents(getContentPane()), "Center"); selectDevicePanel = new SwingSelectDevicePanel(emulatorContext); this.common = new Common(emulatorContext); this.common.setStatusBarListener(statusBarListener); this.common.setResponseInterfaceListener(responseInterfaceListener); this.common.loadImplementationsFromConfig(); this.resizeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { if (resizeDeviceDisplayDialog == null) { resizeDeviceDisplayDialog = new ResizeDeviceDisplayDialog(); } DeviceDisplayImpl deviceDisplay = (DeviceDisplayImpl) DeviceFactory.getDevice().getDeviceDisplay(); resizeDeviceDisplayDialog.setDeviceDisplaySize(deviceDisplay.getFullWidth(), deviceDisplay .getFullHeight()); if (SwingDialogWindow.show(Main.this, "Enter new size...", resizeDeviceDisplayDialog, true)) { deviceDisplay.setDisplayRectangle(new Rectangle(0, 0, resizeDeviceDisplayDialog .getDeviceDisplayWidth(), resizeDeviceDisplayDialog.getDeviceDisplayHeight())); ((SwingDisplayComponent) devicePanel.getDisplayComponent()).init(); MIDletAccess ma = MIDletBridge.getMIDletAccess(); if (ma == null) { return; } DisplayAccess da = ma.getDisplayAccess(); if (da != null) { da.sizeChanged(da.getCurrent().getWidth(), da.getCurrent().getHeight()); deviceDisplay.repaint(0, 0, deviceDisplay.getFullWidth(), deviceDisplay.getFullHeight()); } pack(); } } }); JPanel statusPanel = new JPanel(); statusPanel.setLayout(new BorderLayout()); statusPanel.add(statusBar, "West"); statusPanel.add(this.resizeButton, "East"); getContentPane().add(statusPanel, "South"); Message.addListener(new SwingErrorMessageDialogPanel(this)); devicePanel.setTransferHandler(new DropTransferHandler()); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "Main"
"public Main(DeviceEntry defaultDevice) { this.logQueueAppender = new QueueAppender(1024); Logger.addAppender(logQueueAppender); JMenuBar menuBar = new JMenuBar(); JMenu menuFile = new JMenu("File"); menuOpenJADFile = new JMenuItem("Open JAD File..."); menuOpenJADFile.addActionListener(menuOpenJADFileListener); menuFile.add(menuOpenJADFile); menuOpenJADURL = new JMenuItem("Open JAD URL..."); menuOpenJADURL.addActionListener(menuOpenJADURLListener); menuFile.add(menuOpenJADURL); JMenuItem menuItemTmp = new JMenuItem("Close MIDlet"); menuItemTmp.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK)); menuItemTmp.addActionListener(menuCloseMidletListener); menuFile.add(menuItemTmp); menuFile.addSeparator(); JMRUMenu urlsMRU = new JMRUMenu("Recent MIDlets..."); urlsMRU.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { if (event instanceof JMRUMenu.MRUActionEvent) { Common.openJadUrlSafe(((MidletURLReference) ((JMRUMenu.MRUActionEvent) event).getSourceMRU()) .getUrl()); if (recordStoreManagerDialog != null) { recordStoreManagerDialog.refresh(); } } } }); Config.getUrlsMRU().setListener(urlsMRU); menuFile.add(urlsMRU); menuFile.addSeparator(); menuSaveForWeb = new JMenuItem("Save for Web..."); menuSaveForWeb.addActionListener(menuSaveForWebListener); menuFile.add(menuSaveForWeb); menuFile.addSeparator(); JMenuItem menuItem = new JMenuItem("Exit"); menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK)); menuItem.addActionListener(menuExitListener); menuFile.add(menuItem); JMenu menuOptions = new JMenu("Options"); menuSelectDevice = new JMenuItem("Select device..."); menuSelectDevice.addActionListener(menuSelectDeviceListener); menuOptions.add(menuSelectDevice); menuStartCapture = new JMenuItem("Start capture to GIF..."); menuStartCapture.addActionListener(menuStartCaptureListener); menuOptions.add(menuStartCapture); menuStopCapture = new JMenuItem("Stop capture"); menuStopCapture.setEnabled(false); menuStopCapture.addActionListener(menuStopCaptureListener); menuOptions.add(menuStopCapture); menuMIDletNetworkConnection = new JCheckBoxMenuItem("MIDlet Network access"); menuMIDletNetworkConnection.setState(true); menuMIDletNetworkConnection.addActionListener(menuMIDletNetworkConnectionListener); menuOptions.add(menuMIDletNetworkConnection); menuRecordStoreManager = new JCheckBoxMenuItem("Record Store Manager"); menuRecordStoreManager.setState(false); menuRecordStoreManager.addActionListener(menuRecordStoreManagerListener); menuOptions.add(menuRecordStoreManager); menuLogConsole = new JCheckBoxMenuItem("Log console"); menuLogConsole.setState(false); menuLogConsole.addActionListener(menuLogConsoleListener); menuOptions.add(menuLogConsole); menuOptions.addSeparator(); JCheckBoxMenuItem menuShowMouseCoordinates = new JCheckBoxMenuItem("Mouse coordinates"); menuShowMouseCoordinates.setState(false); menuShowMouseCoordinates.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { devicePanel.switchShowMouseCoordinates(); } }); menuOptions.add(menuShowMouseCoordinates); JMenu menuHelp = new JMenu("Help"); JMenuItem menuAbout = new JMenuItem("About"); menuAbout.addActionListener(menuAboutListener); menuHelp.add(menuAbout); menuBar.add(menuFile); menuBar.add(menuOptions); menuBar.add(menuHelp); setJMenuBar(menuBar); setTitle("MicroEmulator"); this.setIconImage(Toolkit.getDefaultToolkit().getImage(Main.class.getResource("/org/microemu/icon.png"))); addWindowListener(windowListener); Config.loadConfig(defaultDevice, emulatorContext); <MASK>this.common.loadImplementationsFromConfig();</MASK> Rectangle window = Config.getWindow("main", new Rectangle(0, 0, 160, 120)); this.setLocation(window.x, window.y); getContentPane().add(createContents(getContentPane()), "Center"); selectDevicePanel = new SwingSelectDevicePanel(emulatorContext); this.common = new Common(emulatorContext); this.common.setStatusBarListener(statusBarListener); this.common.setResponseInterfaceListener(responseInterfaceListener); this.resizeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { if (resizeDeviceDisplayDialog == null) { resizeDeviceDisplayDialog = new ResizeDeviceDisplayDialog(); } DeviceDisplayImpl deviceDisplay = (DeviceDisplayImpl) DeviceFactory.getDevice().getDeviceDisplay(); resizeDeviceDisplayDialog.setDeviceDisplaySize(deviceDisplay.getFullWidth(), deviceDisplay .getFullHeight()); if (SwingDialogWindow.show(Main.this, "Enter new size...", resizeDeviceDisplayDialog, true)) { deviceDisplay.setDisplayRectangle(new Rectangle(0, 0, resizeDeviceDisplayDialog .getDeviceDisplayWidth(), resizeDeviceDisplayDialog.getDeviceDisplayHeight())); ((SwingDisplayComponent) devicePanel.getDisplayComponent()).init(); MIDletAccess ma = MIDletBridge.getMIDletAccess(); if (ma == null) { return; } DisplayAccess da = ma.getDisplayAccess(); if (da != null) { da.sizeChanged(da.getCurrent().getWidth(), da.getCurrent().getHeight()); deviceDisplay.repaint(0, 0, deviceDisplay.getFullWidth(), deviceDisplay.getFullHeight()); } pack(); } } }); JPanel statusPanel = new JPanel(); statusPanel.setLayout(new BorderLayout()); statusPanel.add(statusBar, "West"); statusPanel.add(this.resizeButton, "East"); getContentPane().add(statusPanel, "South"); Message.addListener(new SwingErrorMessageDialogPanel(this)); devicePanel.setTransferHandler(new DropTransferHandler()); }"
Inversion-Mutation
megadiff
"public void writeMimeMessage(BufferedReader reader, OutputStream os, MimeHeader mimeHeader) throws IOException { String line; // with alternative, there are two body forms (plain+html) if ("multipart/alternative".equals(mimeHeader.contentType)) { attachmentIndex--; } while (((line = reader.readLine()) != null) && !line.equals(mimeHeader.boundary + "--")) { os.write(line.getBytes()); os.write('\r'); os.write('\n'); // detect part boundary start if (line.equals(mimeHeader.boundary)) { // process current part header MimeHeader partHeader = new MimeHeader(); partHeader.processHeaders(reader, os); // detect inner mime message if (partHeader.contentType != null && partHeader.contentType.startsWith("multipart") && partHeader.boundary != null) { writeMimeMessage(reader, os, partHeader); } // body part else if (attachmentIndex <= 0) { attachmentIndex++; writeBody(os, partHeader); } else { Attachment attachment = attachmentsMap.get(partHeader.name); // try to get attachment by index, only if no name found if (attachment == null && partHeader.name == null) { attachment = attachmentsMap.get(String.valueOf(attachmentIndex)); } attachmentIndex++; if (attachment == null) { // only warn, could happen depending on IIS config //throw new IOException("Attachment " + partHeader.name + " not found in " + messageUrl); logger.warn("Attachment " + partHeader.name + " not found in " + messageUrl); } else { writeAttachment(os, partHeader, attachment); } } } } // write mime end marker if (line != null) { os.write(line.getBytes()); os.write('\r'); os.write('\n'); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "writeMimeMessage"
"public void writeMimeMessage(BufferedReader reader, OutputStream os, MimeHeader mimeHeader) throws IOException { String line; // with alternative, there are two body forms (plain+html) if ("multipart/alternative".equals(mimeHeader.contentType)) { attachmentIndex--; } while (((line = reader.readLine()) != null) && !line.equals(mimeHeader.boundary + "--")) { os.write(line.getBytes()); os.write('\r'); os.write('\n'); // detect part boundary start if (line.equals(mimeHeader.boundary)) { // process current part header MimeHeader partHeader = new MimeHeader(); partHeader.processHeaders(reader, os); // detect inner mime message if (partHeader.contentType != null && partHeader.contentType.startsWith("multipart") && partHeader.boundary != null) { writeMimeMessage(reader, os, partHeader); } // body part else if (attachmentIndex <= 0) { <MASK>attachmentIndex++;</MASK> writeBody(os, partHeader); } else { Attachment attachment = attachmentsMap.get(partHeader.name); // try to get attachment by index, only if no name found if (attachment == null && partHeader.name == null) { attachment = attachmentsMap.get(String.valueOf(attachmentIndex)); } if (attachment == null) { // only warn, could happen depending on IIS config //throw new IOException("Attachment " + partHeader.name + " not found in " + messageUrl); logger.warn("Attachment " + partHeader.name + " not found in " + messageUrl); } else { <MASK>attachmentIndex++;</MASK> writeAttachment(os, partHeader, attachment); } } } } // write mime end marker if (line != null) { os.write(line.getBytes()); os.write('\r'); os.write('\n'); } }"
Inversion-Mutation
megadiff
"private void writeToWithPunc(BufferedWriter bw, String[][] textOutput) throws IOException { GetString getString = GetString.altGetString( textOutput, toChunkedCorpus().getArrays(), alpha); for (int sent = 0; sent < corpus.length; sent++) { int chunkI = 0; for (int seg = 0; seg < corpus[sent].length; seg++) { for (int[] chunk: corpus[sent][seg]) { if (chunk.length > 1) bw.write("("); for (int wrd = 0; wrd < chunk.length; wrd++) { bw.write(getString.getString(sent, chunkI, wrd)); if (wrd < chunk.length - 1) bw.write(' '); } bw.write(chunk.length > 1 ? ") " : " "); chunkI++; } bw.write(" ; "); } bw.write('\n'); } bw.close(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "writeToWithPunc"
"private void writeToWithPunc(BufferedWriter bw, String[][] textOutput) throws IOException { GetString getString = GetString.altGetString( textOutput, toChunkedCorpus().getArrays(), alpha); for (int sent = 0; sent < corpus.length; sent++) { for (int seg = 0; seg < corpus[sent].length; seg++) { <MASK>int chunkI = 0;</MASK> for (int[] chunk: corpus[sent][seg]) { if (chunk.length > 1) bw.write("("); for (int wrd = 0; wrd < chunk.length; wrd++) { bw.write(getString.getString(sent, chunkI, wrd)); if (wrd < chunk.length - 1) bw.write(' '); } bw.write(chunk.length > 1 ? ") " : " "); chunkI++; } bw.write(" ; "); } bw.write('\n'); } bw.close(); }"
Inversion-Mutation
megadiff
"private boolean synchronizeProgram() { if (m_gtp == null) { showError(i18n("MSG_NO_PROGRAM_ATTACHED"), "", false); return false; } if (! checkCommandInProgress()) return false; String name = getProgramName(); if (m_gtp.isProgramDead()) { String mainMessage = format(i18n("MSG_PROGRAM_TERMINATED"), name); String optionalMessage = ""; if (m_shell.isLastTextNonGTP()) { showShell(); optionalMessage = format(i18n("MSG_PROGRAM_TERMINATED_CHECK_GTP"), name); } else { showShell(); optionalMessage = format(i18n("MSG_PROGRAM_TERMINATED_REATTACH"), name); } showError(mainMessage, optionalMessage, false); // If program died, menu items need to be updated updateViews(false); return false; } boolean wasOutOfSync = isOutOfSync(); try { ConstGameInfo info = getGameInfo(); m_gtp.synchronize(getBoard(), info.getKomi(), info.getTimeSettings()); } catch (GtpError e) { if (wasOutOfSync) { String mainMessage = format(i18n("MSG_OUT_OF_SYNC"), name); String optionalMessage = format(i18n("MSG_OUT_OF_SYNC_2"), name); showError(mainMessage, optionalMessage, false); } else { String mainMessage = format(i18n("MSG_NOSYNC"), name); String command = null; if (e.getCommand() != null) command = formatCommand(e.getCommand()); String message = e.getMessage(); String response = null; if (! message.trim().equals("")) response = message; String optionalMessage; if (command == null) optionalMessage = format(i18n("MSG_NOSYNC_ERROR"), name, message); else if (response == null) optionalMessage = format(i18n("MSG_NOSYNC_FAILURE"), command, name); else optionalMessage = format(i18n("MSG_NOSYNC_FAILURE_RESPONSE"), command, name, response); showWarning(mainMessage, optionalMessage, true); } return false; } return true; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "synchronizeProgram"
"private boolean synchronizeProgram() { if (m_gtp == null) { showError(i18n("MSG_NO_PROGRAM_ATTACHED"), "", false); <MASK>return false;</MASK> } if (! checkCommandInProgress()) <MASK>return false;</MASK> String name = getProgramName(); if (m_gtp.isProgramDead()) { String mainMessage = format(i18n("MSG_PROGRAM_TERMINATED"), name); String optionalMessage = ""; if (m_shell.isLastTextNonGTP()) { showShell(); optionalMessage = format(i18n("MSG_PROGRAM_TERMINATED_CHECK_GTP"), name); } else { showShell(); optionalMessage = format(i18n("MSG_PROGRAM_TERMINATED_REATTACH"), name); } showError(mainMessage, optionalMessage, false); // If program died, menu items need to be updated updateViews(false); <MASK>return false;</MASK> } boolean wasOutOfSync = isOutOfSync(); try { ConstGameInfo info = getGameInfo(); m_gtp.synchronize(getBoard(), info.getKomi(), info.getTimeSettings()); } catch (GtpError e) { if (wasOutOfSync) { String mainMessage = format(i18n("MSG_OUT_OF_SYNC"), name); String optionalMessage = format(i18n("MSG_OUT_OF_SYNC_2"), name); showError(mainMessage, optionalMessage, false); <MASK>return false;</MASK> } else { String mainMessage = format(i18n("MSG_NOSYNC"), name); String command = null; if (e.getCommand() != null) command = formatCommand(e.getCommand()); String message = e.getMessage(); String response = null; if (! message.trim().equals("")) response = message; String optionalMessage; if (command == null) optionalMessage = format(i18n("MSG_NOSYNC_ERROR"), name, message); else if (response == null) optionalMessage = format(i18n("MSG_NOSYNC_FAILURE"), command, name); else optionalMessage = format(i18n("MSG_NOSYNC_FAILURE_RESPONSE"), command, name, response); showWarning(mainMessage, optionalMessage, true); } } return true; }"
Inversion-Mutation
megadiff
"protected void taskFunc() { int ret; Buffer data = Buffer.create(); data.ensureSize (readSize); data.offset = 0; try { data.length = input.read (data.data, 0, readSize); } catch (Exception e) { e.printStackTrace(); data.length = 0; } if (data.length <= 0) { /* EOS */ data.free(); Debug.log(Debug.INFO, this+" reached EOS"); pushEvent (Event.newEOS()); postMessage (Message.newStreamStatus (this, false, Pad.UNEXPECTED, "reached EOS")); pauseTask(); } else { if (srcpad.getCaps() == null) { String typeMime; typeMime = ElementFactory.typeFindMime (data.data, data.offset, data.length); if (typeMime != null) { if (!typeMime.equals (mime)) { Debug.log(Debug.WARNING, "server contentType: "+mime+" disagrees with our typeFind: " +typeMime); } Debug.log(Debug.INFO, "using typefind contentType: "+typeMime); mime = typeMime; } else { Debug.log(Debug.INFO, "typefind failed, using server contentType: "+mime); } outCaps = new Caps (mime); srcpad.setCaps (outCaps); } data.caps = outCaps; data.setFlag (com.fluendo.jst.Buffer.FLAG_DISCONT, discont); discont = false; if ((ret = push(data)) != OK) { if (isFlowFatal(ret) || ret == Pad.NOT_LINKED) { postMessage (Message.newError (this, "error: "+getFlowName (ret))); pushEvent (Event.newEOS()); } postMessage (Message.newStreamStatus (this, false, ret, "reason: "+getFlowName (ret))); pauseTask(); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "taskFunc"
"protected void taskFunc() { int ret; Buffer data = Buffer.create(); data.ensureSize (readSize); data.offset = 0; try { data.length = input.read (data.data, 0, readSize); } catch (Exception e) { e.printStackTrace(); data.length = 0; } if (data.length <= 0) { /* EOS */ data.free(); Debug.log(Debug.INFO, this+" reached EOS"); <MASK>pushEvent (Event.newEOS());</MASK> postMessage (Message.newStreamStatus (this, false, Pad.UNEXPECTED, "reached EOS")); pauseTask(); } else { if (srcpad.getCaps() == null) { String typeMime; typeMime = ElementFactory.typeFindMime (data.data, data.offset, data.length); if (typeMime != null) { if (!typeMime.equals (mime)) { Debug.log(Debug.WARNING, "server contentType: "+mime+" disagrees with our typeFind: " +typeMime); } Debug.log(Debug.INFO, "using typefind contentType: "+typeMime); mime = typeMime; } else { Debug.log(Debug.INFO, "typefind failed, using server contentType: "+mime); } outCaps = new Caps (mime); srcpad.setCaps (outCaps); } data.caps = outCaps; data.setFlag (com.fluendo.jst.Buffer.FLAG_DISCONT, discont); discont = false; if ((ret = push(data)) != OK) { if (isFlowFatal(ret) || ret == Pad.NOT_LINKED) { postMessage (Message.newError (this, "error: "+getFlowName (ret))); } postMessage (Message.newStreamStatus (this, false, ret, "reason: "+getFlowName (ret))); pauseTask(); <MASK>pushEvent (Event.newEOS());</MASK> } } }"
Inversion-Mutation
megadiff
"@Override public List<LegendElement> getLegendElements() { List<LegendElement> legendItems = new ArrayList<LegendElement>(); legendItems.add(LegendElement.createTask("blocker", BugzillaImages.OVERLAY_CRITICAL)); //$NON-NLS-1$ legendItems.add(LegendElement.createTask("critical", BugzillaImages.OVERLAY_CRITICAL)); //$NON-NLS-1$ legendItems.add(LegendElement.createTask("major", BugzillaImages.OVERLAY_CRITICAL)); //$NON-NLS-1$ legendItems.add(LegendElement.createTask("normal", null)); //$NON-NLS-1$ legendItems.add(LegendElement.createTask("minor", BugzillaImages.OVERLAY_MAJOR)); //$NON-NLS-1$ legendItems.add(LegendElement.createTask("enhancement", BugzillaImages.OVERLAY_ENHANCEMENT)); //$NON-NLS-1$ legendItems.add(LegendElement.createTask("trivial", BugzillaImages.OVERLAY_TRIVIAL)); //$NON-NLS-1$ return legendItems; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getLegendElements"
"@Override public List<LegendElement> getLegendElements() { List<LegendElement> legendItems = new ArrayList<LegendElement>(); legendItems.add(LegendElement.createTask("blocker", BugzillaImages.OVERLAY_CRITICAL)); //$NON-NLS-1$ legendItems.add(LegendElement.createTask("critical", BugzillaImages.OVERLAY_CRITICAL)); //$NON-NLS-1$ legendItems.add(LegendElement.createTask("major", BugzillaImages.OVERLAY_CRITICAL)); //$NON-NLS-1$ <MASK>legendItems.add(LegendElement.createTask("minor", BugzillaImages.OVERLAY_MAJOR)); //$NON-NLS-1$</MASK> legendItems.add(LegendElement.createTask("normal", null)); //$NON-NLS-1$ legendItems.add(LegendElement.createTask("enhancement", BugzillaImages.OVERLAY_ENHANCEMENT)); //$NON-NLS-1$ legendItems.add(LegendElement.createTask("trivial", BugzillaImages.OVERLAY_TRIVIAL)); //$NON-NLS-1$ return legendItems; }"
Inversion-Mutation
megadiff
"private void updateProviderListenersLocked(String provider, boolean enabled) { int listeners = 0; LocationProviderProxy p = mProvidersByName.get(provider); if (p == null) { return; } ArrayList<Receiver> deadReceivers = null; ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider); if (records != null) { final int N = records.size(); for (int i=0; i<N; i++) { UpdateRecord record = records.get(i); // Sends a notification message to the receiver if (!record.mReceiver.callProviderEnabledLocked(provider, enabled)) { if (deadReceivers == null) { deadReceivers = new ArrayList<Receiver>(); } deadReceivers.add(record.mReceiver); } listeners++; } } if (deadReceivers != null) { for (int i=deadReceivers.size()-1; i>=0; i--) { removeUpdatesLocked(deadReceivers.get(i)); } } if (enabled) { p.enable(); if (listeners > 0) { p.setMinTime(getMinTimeLocked(provider)); p.enableLocationTracking(true); } } else { p.enableLocationTracking(false); p.disable(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "updateProviderListenersLocked"
"private void updateProviderListenersLocked(String provider, boolean enabled) { int listeners = 0; LocationProviderProxy p = mProvidersByName.get(provider); if (p == null) { return; } ArrayList<Receiver> deadReceivers = null; ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider); if (records != null) { final int N = records.size(); for (int i=0; i<N; i++) { UpdateRecord record = records.get(i); // Sends a notification message to the receiver if (!record.mReceiver.callProviderEnabledLocked(provider, enabled)) { if (deadReceivers == null) { deadReceivers = new ArrayList<Receiver>(); <MASK>deadReceivers.add(record.mReceiver);</MASK> } } listeners++; } } if (deadReceivers != null) { for (int i=deadReceivers.size()-1; i>=0; i--) { removeUpdatesLocked(deadReceivers.get(i)); } } if (enabled) { p.enable(); if (listeners > 0) { p.setMinTime(getMinTimeLocked(provider)); p.enableLocationTracking(true); } } else { p.enableLocationTracking(false); p.disable(); } }"
Inversion-Mutation
megadiff
"public @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
"@Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, final BuildListener listener) throws InterruptedException, IOException { final SCTMTestSuiteResult rootSuite = new SCTMTestSuiteResult("root"); FilePath workspace = build.getWorkspace(); FilePath resultRootPath = workspace.child(String.format("SCTMResults/%d", build.getNumber())); List<FilePath> resultFiles; try { resultFiles = findAllResultFiles(resultRootPath); } catch (SCTMArchiverException e) { listener.fatalError(MessageFormat.format("FATAL ERROR: Cannot find any result files, because: {0}", e.getMessage())); LOGGER.log(Level.SEVERE, "output.xml files not found", e); build.setResult(Result.FAILURE); return false; } ExecutorService executor = Executors.newFixedThreadPool(4); for (final FilePath resultFilePath : resultFiles) { executor.execute(new Runnable() { @Override public void run() { try { SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); OutputXMLParserHandler handler = new OutputXMLParserHandler(rootSuite, resultFilePath.getParent() .getParent().getName()); parser.parse(resultFilePath.read(), handler); } catch (Exception e) { listener.fatalError(MessageFormat.format("FATAL ERROR: Result cannot be parsed, because: {0}", e.getMessage())); LOGGER.log(Level.SEVERE, "SCTMResult cannot be parsed", e); } } }); } executor.shutdown(); executor.awaitTermination(10, TimeUnit.MINUTES); rootSuite.calculateConfigurationResults(); build.getActions().add(new SCTMResultAction(build, rootSuite, listener)); build.setResult(rootSuite.getFailCount() > 0 ? Result.UNSTABLE : Result.SUCCESS); return true; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "perform"
"@Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, final BuildListener listener) throws InterruptedException, IOException { final SCTMTestSuiteResult rootSuite = new SCTMTestSuiteResult("root"); FilePath workspace = build.getWorkspace(); FilePath resultRootPath = workspace.child(String.format("SCTMResults/%d", build.getNumber())); List<FilePath> resultFiles; try { resultFiles = findAllResultFiles(resultRootPath); } catch (SCTMArchiverException e) { listener.fatalError(MessageFormat.format("FATAL ERROR: Cannot find any result files, because: {0}", e.getMessage())); LOGGER.log(Level.SEVERE, "output.xml files not found", e); build.setResult(Result.FAILURE); return false; } ExecutorService executor = Executors.newFixedThreadPool(4); for (final FilePath resultFilePath : resultFiles) { executor.execute(new Runnable() { @Override public void run() { try { SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); OutputXMLParserHandler handler = new OutputXMLParserHandler(rootSuite, resultFilePath.getParent() .getParent().getName()); parser.parse(resultFilePath.read(), handler); } catch (Exception e) { listener.fatalError(MessageFormat.format("FATAL ERROR: Result cannot be parsed, because: {0}", e.getMessage())); LOGGER.log(Level.SEVERE, "SCTMResult cannot be parsed", e); } <MASK>rootSuite.calculateConfigurationResults();</MASK> } }); } executor.shutdown(); executor.awaitTermination(10, TimeUnit.MINUTES); build.getActions().add(new SCTMResultAction(build, rootSuite, listener)); build.setResult(rootSuite.getFailCount() > 0 ? Result.UNSTABLE : Result.SUCCESS); return true; }"
Inversion-Mutation
megadiff
"public void install() throws IOException { if (isUpToDate()) { notifyInstallComplete(); return; } if (!confirmInstall()) { notifyInstallComplete(); return; } destinationDir = installDirChooser.getInstallDir(); if (destinationDir != null) { bar = new JProgressBar(0, 1); bar.setAlignmentX(0.0F); monitor = new JWindow(); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.setBackground(Color.white); label = new JLabel(Resources.getString("ResourceExtracter.installing")); //$NON-NLS-1$ label.setHorizontalTextPosition(SwingConstants.LEFT); label.setBackground(Color.white); label.setForeground(Color.black); label.setAlignmentX(0.0F); panel.add(label); panel.add(bar); panel.setBorder(new BevelBorder(BevelBorder.RAISED, Color.lightGray, Color.darkGray)); monitor.getContentPane().add(panel); bar.setPreferredSize(new Dimension(400, bar.getPreferredSize().height)); monitor.pack(); Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); monitor.setLocation(d.width / 2 - monitor.getWidth() / 2, d.height / 2 - monitor.getHeight() / 2); monitor.setVisible(true); final IOException[] ex = new IOException[1]; Runnable runnable = new Runnable() { public void run() { try { extract(); storeInstallInfo(); installSucceeded(); } catch (IOException e) { ex[0] = e; } } }; Thread thread = new Thread(runnable); thread.start(); if (ex[0] != null) { throw ex[0]; } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "install"
"public void install() throws IOException { if (isUpToDate()) { notifyInstallComplete(); return; } if (!confirmInstall()) { notifyInstallComplete(); return; } destinationDir = installDirChooser.getInstallDir(); if (destinationDir != null) { bar = new JProgressBar(0, 1); <MASK>bar.setPreferredSize(new Dimension(400, bar.getPreferredSize().height));</MASK> bar.setAlignmentX(0.0F); monitor = new JWindow(); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.setBackground(Color.white); label = new JLabel(Resources.getString("ResourceExtracter.installing")); //$NON-NLS-1$ label.setHorizontalTextPosition(SwingConstants.LEFT); label.setBackground(Color.white); label.setForeground(Color.black); label.setAlignmentX(0.0F); panel.add(label); panel.add(bar); panel.setBorder(new BevelBorder(BevelBorder.RAISED, Color.lightGray, Color.darkGray)); monitor.getContentPane().add(panel); monitor.pack(); Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); monitor.setLocation(d.width / 2 - monitor.getWidth() / 2, d.height / 2 - monitor.getHeight() / 2); monitor.setVisible(true); final IOException[] ex = new IOException[1]; Runnable runnable = new Runnable() { public void run() { try { extract(); storeInstallInfo(); installSucceeded(); } catch (IOException e) { ex[0] = e; } } }; Thread thread = new Thread(runnable); thread.start(); if (ex[0] != null) { throw ex[0]; } } }"
Inversion-Mutation
megadiff
"public boolean shouldAlwaysShow(Object parent, AbstractTask task, int depth) { return task.isActive() || TasksUiPlugin.getTaskActivityManager().isCompletedToday(task) || hasChanges(parent, task) || hasInterestingSubTasks(parent, task, depth) // note that following condition is wrapped in ()! || (!task.isCompleted() && (LocalRepositoryConnector.DEFAULT_SUMMARY.equals(task.getSummary()) || shouldShowInFocusedWorkweekDateContainer(parent, task) || TasksUiPlugin.getTaskActivityManager().isOverdue(task) || isInterestingForThisWeek(parent, task))); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "shouldAlwaysShow"
"public boolean shouldAlwaysShow(Object parent, AbstractTask task, int depth) { return task.isActive() || TasksUiPlugin.getTaskActivityManager().isCompletedToday(task) <MASK>|| hasInterestingSubTasks(parent, task, depth)</MASK> || hasChanges(parent, task) // note that following condition is wrapped in ()! || (!task.isCompleted() && (LocalRepositoryConnector.DEFAULT_SUMMARY.equals(task.getSummary()) || shouldShowInFocusedWorkweekDateContainer(parent, task) || TasksUiPlugin.getTaskActivityManager().isOverdue(task) || isInterestingForThisWeek(parent, task))); }"
Inversion-Mutation
megadiff
"@Test public void testBackgroundConnect() throws Exception { final int CONNECTION_TIMEOUT_MS = 4000; CuratorZookeeperClient client = new CuratorZookeeperClient(server.getConnectString(), 10000, CONNECTION_TIMEOUT_MS, null, new RetryOneTime(1)); try { Assert.assertFalse(client.isConnected()); client.start(); outer: do { for ( int i = 0; i < (CONNECTION_TIMEOUT_MS / 1000); ++i ) { if ( client.isConnected() ) { break outer; } Thread.sleep(CONNECTION_TIMEOUT_MS); } Assert.fail(); } while ( false ); } finally { client.close(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "testBackgroundConnect"
"@Test public void testBackgroundConnect() throws Exception { final int CONNECTION_TIMEOUT_MS = 4000; CuratorZookeeperClient client = new CuratorZookeeperClient(server.getConnectString(), 10000, CONNECTION_TIMEOUT_MS, null, new RetryOneTime(1)); <MASK>client.start();</MASK> try { Assert.assertFalse(client.isConnected()); outer: do { for ( int i = 0; i < (CONNECTION_TIMEOUT_MS / 1000); ++i ) { if ( client.isConnected() ) { break outer; } Thread.sleep(CONNECTION_TIMEOUT_MS); } Assert.fail(); } while ( false ); } finally { client.close(); } }"
Inversion-Mutation
megadiff
"private void renderLights(Graphics2D g, PlayerView view) { // Setup timer.start("lights-1"); Graphics2D newG = (Graphics2D)g.create(); Area clip = new Area(g.getClip()); if (visibleScreenArea != null) { clip.intersect(visibleScreenArea); } SwingUtil.useAntiAliasing(newG); timer.stop("lights-1"); timer.start("lights-2"); AffineTransform af = g.getTransform(); af.translate(getViewOffsetX(), getViewOffsetY()); af.scale(getScale(), getScale()); newG.setTransform(af); newG.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, AppPreferences.getVisionOverlayOpacity()/255.0f)); timer.stop("lights-2"); if (renderedLightMap == null) { timer.start("lights-3"); // Organize Map<Paint, List<Area>> colorMap = new HashMap<Paint, List<Area>>(); for (DrawableLight light : zoneView.getDrawableLights()) { List<Area> areaList = colorMap.get(light.getPaint().getPaint()); if (areaList == null) { areaList = new ArrayList<Area>(); colorMap.put(light.getPaint().getPaint(), areaList); } areaList.add(new Area(light.getArea())); } timer.stop("lights-3"); timer.start("lights-4"); // Combine same colors to avoid ugly overlap for (List<Area> areaList : colorMap.values()) { while (areaList.size() > 1) { Area a1 = areaList.remove(0); Area a2 = areaList.remove(0); a1.add(a2); areaList.add(a1); } // Cut out the bright light if (areaList.size() > 0) { Area area = areaList.get(0); for (Area brightArea : zoneView.getBrightLights()) { area.subtract(brightArea); } } } renderedLightMap = new LinkedHashMap<Paint, Area>(); for (Entry<Paint, List<Area>> entry : colorMap.entrySet()) { renderedLightMap.put(entry.getKey(), entry.getValue().get(0)); } timer.stop("lights-4"); } // Draw timer.start("lights-5"); for (Entry<Paint, Area> entry : renderedLightMap.entrySet()) { newG.setPaint(entry.getKey()); newG.fill(entry.getValue()); } timer.stop("lights-5"); newG.dispose(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "renderLights"
"private void renderLights(Graphics2D g, PlayerView view) { // Setup timer.start("lights-1"); Graphics2D newG = (Graphics2D)g.create(); Area clip = new Area(g.getClip()); if (visibleScreenArea != null) { clip.intersect(visibleScreenArea); } SwingUtil.useAntiAliasing(newG); timer.stop("lights-1"); timer.start("lights-2"); AffineTransform af = g.getTransform(); af.translate(getViewOffsetX(), getViewOffsetY()); af.scale(getScale(), getScale()); newG.setTransform(af); newG.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, AppPreferences.getVisionOverlayOpacity()/255.0f)); timer.stop("lights-2"); <MASK>timer.start("lights-3");</MASK> if (renderedLightMap == null) { // Organize Map<Paint, List<Area>> colorMap = new HashMap<Paint, List<Area>>(); for (DrawableLight light : zoneView.getDrawableLights()) { List<Area> areaList = colorMap.get(light.getPaint().getPaint()); if (areaList == null) { areaList = new ArrayList<Area>(); colorMap.put(light.getPaint().getPaint(), areaList); } areaList.add(new Area(light.getArea())); } timer.stop("lights-3"); timer.start("lights-4"); // Combine same colors to avoid ugly overlap for (List<Area> areaList : colorMap.values()) { while (areaList.size() > 1) { Area a1 = areaList.remove(0); Area a2 = areaList.remove(0); a1.add(a2); areaList.add(a1); } // Cut out the bright light if (areaList.size() > 0) { Area area = areaList.get(0); for (Area brightArea : zoneView.getBrightLights()) { area.subtract(brightArea); } } } renderedLightMap = new LinkedHashMap<Paint, Area>(); for (Entry<Paint, List<Area>> entry : colorMap.entrySet()) { renderedLightMap.put(entry.getKey(), entry.getValue().get(0)); } timer.stop("lights-4"); } // Draw timer.start("lights-5"); for (Entry<Paint, Area> entry : renderedLightMap.entrySet()) { newG.setPaint(entry.getKey()); newG.fill(entry.getValue()); } timer.stop("lights-5"); newG.dispose(); }"
Inversion-Mutation
megadiff
"public void addSeamRuntime(String name, String version, String seamHome) { log.info("Adding Seam Runtime: " + name + "\nVersion: " + version + "\nHome: " + seamHome); SWTBot wiz = open.preferenceOpen(ActionItem.Preference.JBossToolsWebSeam.LABEL); SWTBotTable tbRuntimeEnvironments = bot.table(); boolean createRuntime = true; // first check if Environment doesn't exist int numRows = tbRuntimeEnvironments.rowCount(); if (numRows > 0) { int currentRow = 0; while (createRuntime && currentRow < numRows) { if (tbRuntimeEnvironments.cell(currentRow, 1).equalsIgnoreCase( name)) { createRuntime = false; } else { currentRow++; } } } if (createRuntime) { wiz.button("Add").click(); bot.shell(IDELabel.Shell.NEW_SEAM_RUNTIME).activate(); bot.text(0).setText(seamHome); bot.text(1).setText(name); // find and select version String[] versions = bot.comboBox().items(); int myIndex =0; for (int index=0;index<versions.length;index++) { if (version.equals(versions[index])) { myIndex=index; break; } } bot.comboBox().setSelection(myIndex); open.finish(bot.activeShell().bot()); } open.finish(wiz, IDELabel.Button.OK); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addSeamRuntime"
"public void addSeamRuntime(String name, String version, String seamHome) { log.info("Adding Seam Runtime: " + name + "\nVersion: " + version + "\nHome: " + seamHome); SWTBot wiz = open.preferenceOpen(ActionItem.Preference.JBossToolsWebSeam.LABEL); SWTBotTable tbRuntimeEnvironments = bot.table(); boolean createRuntime = true; // first check if Environment doesn't exist int numRows = tbRuntimeEnvironments.rowCount(); if (numRows > 0) { int currentRow = 0; while (createRuntime && currentRow < numRows) { if (tbRuntimeEnvironments.cell(currentRow, 1).equalsIgnoreCase( name)) { createRuntime = false; } else { currentRow++; } } } if (createRuntime) { wiz.button("Add").click(); bot.shell(IDELabel.Shell.NEW_SEAM_RUNTIME).activate(); bot.text(0).setText(seamHome); bot.text(1).setText(name); // find and select version String[] versions = bot.comboBox().items(); int myIndex =0; for (int index=0;index<versions.length;index++) { if (version.equals(versions[index])) { myIndex=index; break; } } bot.comboBox().setSelection(myIndex); open.finish(bot.activeShell().bot()); <MASK>open.finish(wiz, IDELabel.Button.OK);</MASK> } }"
Inversion-Mutation
megadiff
"public WebSpherePropertiesPanel() { setLayout(new GridBagLayout()); { JLabel hostLabel = new JLabel(); Mnemonics.setLocalizedText(hostLabel, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Host")); add(hostLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 0, 2, 0), 0, 0)); hostField = new JTextField(); hostLabel.setLabelFor(hostField); hostField.getDocument().addDocumentListener(new SimpleDocumentListener() { @Override protected void updated() { update(); resetConnectionTestResults(); } }); add(hostField, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, WEST, HORIZONTAL, new Insets(2, 5, 2, 0), 0, 0)); } { JLabel portLabel = new JLabel(); Mnemonics.setLocalizedText(portLabel, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Port")); add(portLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 0, 2, 0), 0, 0)); portField = new JTextField(6); portLabel.setLabelFor(portField); portField.getDocument().addDocumentListener(new SimpleDocumentListener() { @Override protected void updated() { update(); resetConnectionTestResults(); } }); add(portField, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0, WEST, NONE, new Insets(2, 5, 2, 0), 0, 0)); } { securityCheckbox = new JCheckBox(); Mnemonics.setLocalizedText(securityCheckbox, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Security_enabled")); securityCheckbox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { update(); resetConnectionTestResults(); }; }); add(securityCheckbox, new GridBagConstraints(0, 2, REMAINDER, 1, 0.0, 0.0, WEST, NONE, new Insets(8, 0, 2, 0), 0, 0)); } { JLabel usernameLabel = new JLabel(); Mnemonics.setLocalizedText(usernameLabel, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Username")); add(usernameLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 15, 2, 0), 0, 0)); usernameField = new JTextField(12); usernameLabel.setLabelFor(usernameField); usernameField.getDocument().addDocumentListener(new SimpleDocumentListener() { @Override protected void updated() { update(); resetConnectionTestResults(); } }); add(usernameField, new GridBagConstraints(1, 3, 1, 1, 1.0, 0.0, WEST, NONE, new Insets(2, 5, 2, 0), 0, 0)); } { JLabel passwordLabel = new JLabel(); Mnemonics.setLocalizedText(passwordLabel, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Password")); add(passwordLabel, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 15, 2, 0), 0, 0)); passwordField = new JPasswordField(12); passwordLabel.setLabelFor(passwordField); passwordField.getDocument().addDocumentListener(new SimpleDocumentListener() { @Override protected void updated() { update(); resetConnectionTestResults(); } }); add(passwordField, new GridBagConstraints(1, 4, 1, 1, 1.0, 0.0, WEST, NONE, new Insets(2, 5, 2, 0), 0, 0)); } { saveCheckbox = new JCheckBox(); // NOI18N Mnemonics.setLocalizedText(saveCheckbox, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Save_security_credentials")); saveCheckbox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { update(); }; }); add(saveCheckbox, new GridBagConstraints(0, 5, REMAINDER, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 15, 2, 0), 0, 0)); } { testConnectionButton = new JButton(new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { testConnection(); } }); Mnemonics.setLocalizedText(testConnectionButton, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Test_connection")); add(testConnectionButton, new GridBagConstraints(0, 6, REMAINDER, 1, 0.0, 0.0, WEST, NONE, new Insets(5, 0, 2, 0), 0, 0)); } { testConnectionResultField = new JTextField(); testConnectionResultField.setEditable(false); testConnectionResultField.setBorder(BorderFactory.createEmptyBorder()); add(testConnectionResultField, new GridBagConstraints(0, 7, REMAINDER, 1, 1.0, 0.0, WEST, HORIZONTAL, new Insets(2, 0, 2, 0), 0, 0)); } add(Spacer.create(), new GridBagConstraints(0, 8, 2, 1, 1.0, 1.0, NORTHWEST, BOTH, new Insets(0, 0, 0, 0), 0, 0)); update(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "WebSpherePropertiesPanel"
"public WebSpherePropertiesPanel() { setLayout(new GridBagLayout()); { JLabel hostLabel = new JLabel(); Mnemonics.setLocalizedText(hostLabel, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Host")); add(hostLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 0, 2, 0), 0, 0)); hostField = new JTextField(); hostLabel.setLabelFor(hostField); hostField.getDocument().addDocumentListener(new SimpleDocumentListener() { @Override protected void updated() { update(); <MASK>resetConnectionTestResults();</MASK> } }); add(hostField, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, WEST, HORIZONTAL, new Insets(2, 5, 2, 0), 0, 0)); } { JLabel portLabel = new JLabel(); Mnemonics.setLocalizedText(portLabel, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Port")); add(portLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 0, 2, 0), 0, 0)); portField = new JTextField(6); portLabel.setLabelFor(portField); portField.getDocument().addDocumentListener(new SimpleDocumentListener() { @Override protected void updated() { update(); <MASK>resetConnectionTestResults();</MASK> } }); add(portField, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0, WEST, NONE, new Insets(2, 5, 2, 0), 0, 0)); } { securityCheckbox = new JCheckBox(); Mnemonics.setLocalizedText(securityCheckbox, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Security_enabled")); securityCheckbox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { update(); }; }); add(securityCheckbox, new GridBagConstraints(0, 2, REMAINDER, 1, 0.0, 0.0, WEST, NONE, new Insets(8, 0, 2, 0), 0, 0)); } { JLabel usernameLabel = new JLabel(); Mnemonics.setLocalizedText(usernameLabel, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Username")); add(usernameLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 15, 2, 0), 0, 0)); usernameField = new JTextField(12); usernameLabel.setLabelFor(usernameField); usernameField.getDocument().addDocumentListener(new SimpleDocumentListener() { @Override protected void updated() { update(); <MASK>resetConnectionTestResults();</MASK> } }); add(usernameField, new GridBagConstraints(1, 3, 1, 1, 1.0, 0.0, WEST, NONE, new Insets(2, 5, 2, 0), 0, 0)); } { JLabel passwordLabel = new JLabel(); Mnemonics.setLocalizedText(passwordLabel, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Password")); add(passwordLabel, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 15, 2, 0), 0, 0)); passwordField = new JPasswordField(12); passwordLabel.setLabelFor(passwordField); passwordField.getDocument().addDocumentListener(new SimpleDocumentListener() { @Override protected void updated() { update(); <MASK>resetConnectionTestResults();</MASK> } }); add(passwordField, new GridBagConstraints(1, 4, 1, 1, 1.0, 0.0, WEST, NONE, new Insets(2, 5, 2, 0), 0, 0)); } { saveCheckbox = new JCheckBox(); // NOI18N Mnemonics.setLocalizedText(saveCheckbox, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Save_security_credentials")); saveCheckbox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { update(); <MASK>resetConnectionTestResults();</MASK> }; }); add(saveCheckbox, new GridBagConstraints(0, 5, REMAINDER, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 15, 2, 0), 0, 0)); } { testConnectionButton = new JButton(new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { testConnection(); } }); Mnemonics.setLocalizedText(testConnectionButton, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Test_connection")); add(testConnectionButton, new GridBagConstraints(0, 6, REMAINDER, 1, 0.0, 0.0, WEST, NONE, new Insets(5, 0, 2, 0), 0, 0)); } { testConnectionResultField = new JTextField(); testConnectionResultField.setEditable(false); testConnectionResultField.setBorder(BorderFactory.createEmptyBorder()); add(testConnectionResultField, new GridBagConstraints(0, 7, REMAINDER, 1, 1.0, 0.0, WEST, HORIZONTAL, new Insets(2, 0, 2, 0), 0, 0)); } add(Spacer.create(), new GridBagConstraints(0, 8, 2, 1, 1.0, 1.0, NORTHWEST, BOTH, new Insets(0, 0, 0, 0), 0, 0)); update(); }"
Inversion-Mutation
megadiff
"@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String requestUri = req.getRequestURI(); String resourcePath = RESOURCE_FOLDER + getResourcePath(requestUri); URL url = ResourceServlet.class.getResource(resourcePath); if (logger.isLoggable(Level.FINE)){ logger.log(Level.INFO,"Request URI: " + requestUri); logger.log(Level.INFO,"resourcePath: " + requestUri); logger.log(Level.INFO,"resource url: " + requestUri); } if (url == null) { boolean error = true; if(requestUri.endsWith(".js")){ //try optimized version first if (requestUri.contains("scripts/betterform/betterform-")) { if (ResourceServlet.class.getResource(resourcePath) == null) { resourcePath = resourcePath.replace("betterform-", "BfRequired"); if (ResourceServlet.class.getResource(resourcePath) != null) { error=false; } } } } if(error) { logger.log(Level.WARNING, "Resource \"{0}\" not found", resourcePath); resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } if (logger.isLoggable(Level.FINE)) logger.log(Level.FINE, "Streaming resource \"{0}\"", resourcePath); InputStream inputStream = null; try { inputStream = ResourceServlet.class.getResourceAsStream(resourcePath); String mimeType = getResourceContentType(resourcePath); if (mimeType == null) { logger.log(Level.WARNING, "MimeType for \"{0}\" not found. Sending not found", resourcePath); resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } resp.setContentType(mimeType); resp.setStatus(HttpServletResponse.SC_OK); setCaching(req, resp); streamResource(req, resp, mimeType, inputStream); if (logger.isLoggable(Level.FINE)) logger.log(Level.FINE, "Resource \"{0}\" streamed succesfully", resourcePath); } catch (Exception exception) { logger.log(Level.SEVERE, "Error in streaming resource \"{0}\". Exception is \"{1}\"", new Object[]{resourcePath, exception.getMessage()}); } finally { if (inputStream != null) { inputStream.close(); } resp.getOutputStream().flush(); resp.getOutputStream().close(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doGet"
"@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String requestUri = req.getRequestURI(); String resourcePath = RESOURCE_FOLDER + getResourcePath(requestUri); URL url = ResourceServlet.class.getResource(resourcePath); if (logger.isLoggable(Level.FINE)){ logger.log(Level.INFO,"Request URI: " + requestUri); logger.log(Level.INFO,"resourcePath: " + requestUri); logger.log(Level.INFO,"resource url: " + requestUri); } if (url == null) { <MASK>logger.log(Level.WARNING, "Resource \"{0}\" not found", resourcePath);</MASK> boolean error = true; if(requestUri.endsWith(".js")){ //try optimized version first if (requestUri.contains("scripts/betterform/betterform-")) { if (ResourceServlet.class.getResource(resourcePath) == null) { resourcePath = resourcePath.replace("betterform-", "BfRequired"); if (ResourceServlet.class.getResource(resourcePath) != null) { error=false; } } } } if(error) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } if (logger.isLoggable(Level.FINE)) logger.log(Level.FINE, "Streaming resource \"{0}\"", resourcePath); InputStream inputStream = null; try { inputStream = ResourceServlet.class.getResourceAsStream(resourcePath); String mimeType = getResourceContentType(resourcePath); if (mimeType == null) { logger.log(Level.WARNING, "MimeType for \"{0}\" not found. Sending not found", resourcePath); resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } resp.setContentType(mimeType); resp.setStatus(HttpServletResponse.SC_OK); setCaching(req, resp); streamResource(req, resp, mimeType, inputStream); if (logger.isLoggable(Level.FINE)) logger.log(Level.FINE, "Resource \"{0}\" streamed succesfully", resourcePath); } catch (Exception exception) { logger.log(Level.SEVERE, "Error in streaming resource \"{0}\". Exception is \"{1}\"", new Object[]{resourcePath, exception.getMessage()}); } finally { if (inputStream != null) { inputStream.close(); } resp.getOutputStream().flush(); resp.getOutputStream().close(); } }"
Inversion-Mutation
megadiff
"@Override public void setValue(Date date) { monthPicker.setValue(date); if (date != null) { updateDateTextBox(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setValue"
"@Override public void setValue(Date date) { if (date != null) { <MASK>monthPicker.setValue(date);</MASK> updateDateTextBox(); } }"
Inversion-Mutation
megadiff
"public synchronized boolean next(Writable key, Writable value) throws IOException { if (!(key instanceof Text)) { throw new IllegalArgumentException("Key should be of type Text but: " + key.getClass().getName()); } if (!(value instanceof Text)) { throw new IllegalArgumentException("Value should be of type Text but: " + value.getClass().getName()); } Text tKey = (Text) key; Text tValue = (Text) value; byte[] line; while (true) { if (gzipped_) { // figure EOS from readLine } else { long pos = in_.getPos(); if (pos >= end_) return false; } line = UTF8ByteArrayUtils.readLine((InputStream) in_); if (line == null) return false; try { Text.validateUTF8(line); } catch (MalformedInputException m) { System.err.println("line=" + line + "|" + new Text(line)); System.out.flush(); } try { int tab = UTF8ByteArrayUtils.findTab(line); if (tab == -1) { tKey.set(line); tValue.set(""); } else { UTF8ByteArrayUtils.splitKeyVal(line, tKey, tValue, tab); } break; } catch (MalformedInputException e) { LOG.warn(StringUtils.stringifyException(e)); } } numRecStats(line, 0, line.length); return true; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "next"
"public synchronized boolean next(Writable key, Writable value) throws IOException { if (!(key instanceof Text)) { throw new IllegalArgumentException("Key should be of type Text but: " + key.getClass().getName()); } if (!(value instanceof Text)) { throw new IllegalArgumentException("Value should be of type Text but: " + value.getClass().getName()); } Text tKey = (Text) key; Text tValue = (Text) value; byte[] line; while (true) { if (gzipped_) { // figure EOS from readLine } else { long pos = in_.getPos(); if (pos >= end_) return false; } line = UTF8ByteArrayUtils.readLine((InputStream) in_); try { Text.validateUTF8(line); } catch (MalformedInputException m) { System.err.println("line=" + line + "|" + new Text(line)); System.out.flush(); } <MASK>if (line == null) return false;</MASK> try { int tab = UTF8ByteArrayUtils.findTab(line); if (tab == -1) { tKey.set(line); tValue.set(""); } else { UTF8ByteArrayUtils.splitKeyVal(line, tKey, tValue, tab); } break; } catch (MalformedInputException e) { LOG.warn(StringUtils.stringifyException(e)); } } numRecStats(line, 0, line.length); return true; }"
Inversion-Mutation
megadiff
"public synchronized void termLogging(boolean explain) { // enumerate the errors int errs = 0; for(Iterator it = allErrors.iterator(); it.hasNext(); ) { MessageLog el = (MessageLog)it.next(); el.index = ++errs; } for(Iterator it = allWarnings.iterator(); it.hasNext(); ) { MessageLog el = (MessageLog)it.next(); el.index = ++errs; } // Set as assigned before removing it synchronized(allLoggers) { currentLogger = this; } if (errs == 0) { delete(); return; } // if (db_errorchangedroutine != 0) (*db_errorchangedroutine)(); if (errs > 0 && explain) { if (!alreadyExplained) { alreadyExplained = true; SwingUtilities.invokeLater(new Runnable() { public void run() { // To print consistent message in message window String extraMsg = "errors/warnings"; if (getNumErrors() == 0) extraMsg = "warnings"; else if (getNumWarnings() == 0) extraMsg = "errors"; String msg = errorSystem + " found "+getNumErrors()+" errors, "+getNumWarnings()+" warnings!"; System.out.println(msg); if (getNumLogs() > 0) { System.out.println("Type > and < to step through " + extraMsg + ", or open the ERRORS view in the explorer"); } if (getNumErrors() > 0 && !Main.BATCHMODE) { JOptionPane.showMessageDialog(TopLevel.getCurrentJFrame(), msg, errorSystem + " finished with Errors", JOptionPane.INFORMATION_MESSAGE); } } }); } } SwingUtilities.invokeLater(new Runnable() { public void run() {WindowFrame.wantToRedoErrorTree(); } }); terminated = true; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "termLogging"
"public synchronized void termLogging(boolean explain) { // enumerate the errors int errs = 0; for(Iterator it = allErrors.iterator(); it.hasNext(); ) { MessageLog el = (MessageLog)it.next(); el.index = ++errs; } for(Iterator it = allWarnings.iterator(); it.hasNext(); ) { MessageLog el = (MessageLog)it.next(); el.index = ++errs; } // Set as assigned before removing it synchronized(allLoggers) { currentLogger = this; } if (errs == 0) { delete(); return; } // if (db_errorchangedroutine != 0) (*db_errorchangedroutine)(); if (errs > 0 && explain) { if (!alreadyExplained) { alreadyExplained = true; SwingUtilities.invokeLater(new Runnable() { public void run() { // To print consistent message in message window String extraMsg = "errors/warnings"; if (getNumErrors() == 0) extraMsg = "warnings"; else if (getNumWarnings() == 0) extraMsg = "errors"; String msg = errorSystem + " found "+getNumErrors()+" errors, "+getNumWarnings()+" warnings!"; if (getNumLogs() > 0) { <MASK>System.out.println(msg);</MASK> System.out.println("Type > and < to step through " + extraMsg + ", or open the ERRORS view in the explorer"); } if (getNumErrors() > 0 && !Main.BATCHMODE) { JOptionPane.showMessageDialog(TopLevel.getCurrentJFrame(), msg, errorSystem + " finished with Errors", JOptionPane.INFORMATION_MESSAGE); } } }); } } SwingUtilities.invokeLater(new Runnable() { public void run() {WindowFrame.wantToRedoErrorTree(); } }); terminated = true; }"
Inversion-Mutation
megadiff
"public void run() { // To print consistent message in message window String extraMsg = "errors/warnings"; if (getNumErrors() == 0) extraMsg = "warnings"; else if (getNumWarnings() == 0) extraMsg = "errors"; String msg = errorSystem + " found "+getNumErrors()+" errors, "+getNumWarnings()+" warnings!"; System.out.println(msg); if (getNumLogs() > 0) { System.out.println("Type > and < to step through " + extraMsg + ", or open the ERRORS view in the explorer"); } if (getNumErrors() > 0 && !Main.BATCHMODE) { JOptionPane.showMessageDialog(TopLevel.getCurrentJFrame(), msg, errorSystem + " finished with Errors", JOptionPane.INFORMATION_MESSAGE); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"public void run() { // To print consistent message in message window String extraMsg = "errors/warnings"; if (getNumErrors() == 0) extraMsg = "warnings"; else if (getNumWarnings() == 0) extraMsg = "errors"; String msg = errorSystem + " found "+getNumErrors()+" errors, "+getNumWarnings()+" warnings!"; if (getNumLogs() > 0) { <MASK>System.out.println(msg);</MASK> System.out.println("Type > and < to step through " + extraMsg + ", or open the ERRORS view in the explorer"); } if (getNumErrors() > 0 && !Main.BATCHMODE) { JOptionPane.showMessageDialog(TopLevel.getCurrentJFrame(), msg, errorSystem + " finished with Errors", JOptionPane.INFORMATION_MESSAGE); } }"
Inversion-Mutation
megadiff
"protected final void updateSizeCheck() { final Rectangle oClientArea = clientArea; final Rectangle nClientArea = GLCanvas.this.getClientArea(); if ( nClientArea != null && ( nClientArea.width != oClientArea.width || nClientArea.height != oClientArea.height ) ) { clientArea = nClientArea; // write back new value GLDrawableImpl _drawable = drawable; if( null != _drawable ) { if(DEBUG) { System.err.println("GLCanvas.sizeChanged: ("+Thread.currentThread().getName()+"): "+nClientArea.width+"x"+nClientArea.height+" - surfaceHandle 0x"+Long.toHexString(getNativeSurface().getSurfaceHandle())); } if( ! _drawable.getChosenGLCapabilities().isOnscreen() ) { final RecursiveLock _lock = lock; _lock.lock(); try { final GLDrawableImpl _drawableNew = GLDrawableHelper.resizeOffscreenDrawable(_drawable, context, nClientArea.width, nClientArea.height); if(_drawable != _drawableNew) { // write back drawable = _drawableNew; } } finally { _lock.unlock(); } } sendReshape = true; // async if display() doesn't get called below, but avoiding deadlock } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "updateSizeCheck"
"protected final void updateSizeCheck() { final Rectangle oClientArea = clientArea; final Rectangle nClientArea = GLCanvas.this.getClientArea(); if ( nClientArea != null && ( nClientArea.width != oClientArea.width || nClientArea.height != oClientArea.height ) ) { clientArea = nClientArea; // write back new value GLDrawableImpl _drawable = drawable; if( null != _drawable ) { if(DEBUG) { System.err.println("GLCanvas.sizeChanged: ("+Thread.currentThread().getName()+"): "+nClientArea.width+"x"+nClientArea.height+" - surfaceHandle 0x"+Long.toHexString(getNativeSurface().getSurfaceHandle())); } if( ! _drawable.getChosenGLCapabilities().isOnscreen() ) { final RecursiveLock _lock = lock; _lock.lock(); try { final GLDrawableImpl _drawableNew = GLDrawableHelper.resizeOffscreenDrawable(_drawable, context, nClientArea.width, nClientArea.height); if(_drawable != _drawableNew) { // write back drawable = _drawableNew; } } finally { _lock.unlock(); } <MASK>sendReshape = true; // async if display() doesn't get called below, but avoiding deadlock</MASK> } } } }"
Inversion-Mutation
megadiff
"public void getDissemination(Context context, String PID, String bDefPID, String methodName, Property[] userParms, Date asOfDateTime, HttpServletResponse response, HttpServletRequest request) throws IOException, ServerException { ServletOutputStream out = null; MIMETypedStream dissemination = null; dissemination = s_access.getDissemination(context, PID, bDefPID, methodName, userParms, asOfDateTime); out = response.getOutputStream(); if (dissemination != null) { // testing to see what's in request header that might be of interest for (Enumeration e= request.getHeaderNames(); e.hasMoreElements();) { String name = (String)e.nextElement(); Enumeration headerValues = request.getHeaders(name); StringBuffer sb = new StringBuffer(); while (headerValues.hasMoreElements()) { sb.append((String) headerValues.nextElement()); } String value = sb.toString(); if (fedora.server.Debug.DEBUG) System.out.println("FEDORASERVLET REQUEST HEADER CONTAINED: "+name+" : "+value); response.setHeader(name,value); } // Dissemination was successful; // Return MIMETypedStream back to browser client if (dissemination.MIMEType.equalsIgnoreCase("application/fedora-redirect")) { // A MIME type of application/fedora-redirect signals that the // MIMETypedStream returned from the dissemination is a special // Fedora-specific MIME type. In this case, the Fedora server will // not proxy the datastream, but instead perform a simple redirect to // the URL contained within the body of the MIMETypedStream. This // special MIME type is used primarily for streaming media where it // is more efficient to stream the data directly between the streaming // server and the browser client rather than proxy it through the // Fedora server. BufferedReader br = new BufferedReader( new InputStreamReader(dissemination.getStream())); StringBuffer sb = new StringBuffer(); String line = null; while ((line = br.readLine()) != null) { sb.append(line); } response.sendRedirect(sb.toString()); } else { response.setContentType(dissemination.MIMEType); Property[] headerArray = dissemination.header; if(headerArray != null) { for(int i=0; i<headerArray.length; i++) { if(headerArray[i].name != null && !(headerArray[i].name.equalsIgnoreCase("content-type"))) { response.addHeader(headerArray[i].name, headerArray[i].value); if (fedora.server.Debug.DEBUG) System.out.println("THIS WAS ADDED TO FEDORASERVLET RESPONSE HEADER FROM ORIGINATING PROVIDER "+headerArray[i].name+" : "+headerArray[i].value); } } } long startTime = new Date().getTime(); int byteStream = 0; InputStream dissemResult = dissemination.getStream(); byte[] buffer = new byte[255]; while ((byteStream = dissemResult.read(buffer)) != -1) { out.write(buffer, 0, byteStream); } buffer = null; dissemResult.close(); dissemResult = null; long stopTime = new Date().getTime(); long interval = stopTime - startTime; logger.logFiner("[FedoraAccessServlet] Read InputStream " + interval + " milliseconds."); } } else { // Dissemination request failed; echo back request parameter. String message = "[FedoraAccessServlet] No Dissemination Result " + " was returned."; showURLParms(PID, bDefPID, methodName, asOfDateTime, userParms, response, message); logger.logInfo(message); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getDissemination"
"public void getDissemination(Context context, String PID, String bDefPID, String methodName, Property[] userParms, Date asOfDateTime, HttpServletResponse response, HttpServletRequest request) throws IOException, ServerException { ServletOutputStream out = null; MIMETypedStream dissemination = null; dissemination = s_access.getDissemination(context, PID, bDefPID, methodName, userParms, asOfDateTime); if (dissemination != null) { // testing to see what's in request header that might be of interest for (Enumeration e= request.getHeaderNames(); e.hasMoreElements();) { String name = (String)e.nextElement(); Enumeration headerValues = request.getHeaders(name); StringBuffer sb = new StringBuffer(); while (headerValues.hasMoreElements()) { sb.append((String) headerValues.nextElement()); } String value = sb.toString(); if (fedora.server.Debug.DEBUG) System.out.println("FEDORASERVLET REQUEST HEADER CONTAINED: "+name+" : "+value); response.setHeader(name,value); } // Dissemination was successful; // Return MIMETypedStream back to browser client if (dissemination.MIMEType.equalsIgnoreCase("application/fedora-redirect")) { // A MIME type of application/fedora-redirect signals that the // MIMETypedStream returned from the dissemination is a special // Fedora-specific MIME type. In this case, the Fedora server will // not proxy the datastream, but instead perform a simple redirect to // the URL contained within the body of the MIMETypedStream. This // special MIME type is used primarily for streaming media where it // is more efficient to stream the data directly between the streaming // server and the browser client rather than proxy it through the // Fedora server. BufferedReader br = new BufferedReader( new InputStreamReader(dissemination.getStream())); StringBuffer sb = new StringBuffer(); String line = null; while ((line = br.readLine()) != null) { sb.append(line); } response.sendRedirect(sb.toString()); } else { response.setContentType(dissemination.MIMEType); Property[] headerArray = dissemination.header; if(headerArray != null) { for(int i=0; i<headerArray.length; i++) { if(headerArray[i].name != null && !(headerArray[i].name.equalsIgnoreCase("content-type"))) { response.addHeader(headerArray[i].name, headerArray[i].value); if (fedora.server.Debug.DEBUG) System.out.println("THIS WAS ADDED TO FEDORASERVLET RESPONSE HEADER FROM ORIGINATING PROVIDER "+headerArray[i].name+" : "+headerArray[i].value); } } } <MASK>out = response.getOutputStream();</MASK> long startTime = new Date().getTime(); int byteStream = 0; InputStream dissemResult = dissemination.getStream(); byte[] buffer = new byte[255]; while ((byteStream = dissemResult.read(buffer)) != -1) { out.write(buffer, 0, byteStream); } buffer = null; dissemResult.close(); dissemResult = null; long stopTime = new Date().getTime(); long interval = stopTime - startTime; logger.logFiner("[FedoraAccessServlet] Read InputStream " + interval + " milliseconds."); } } else { // Dissemination request failed; echo back request parameter. String message = "[FedoraAccessServlet] No Dissemination Result " + " was returned."; showURLParms(PID, bDefPID, methodName, asOfDateTime, userParms, response, message); logger.logInfo(message); } }"
Inversion-Mutation
megadiff
"@Override public void paintComponent(Graphics g) { super.paintComponent(g); if(appStateIndicator.getState() != ApplicationState.RUNNING) { return; } showCoordinates(); // Briefly lock the sim to update entity shapes and stuff. double time = 0.0; synchronized (sim.getLock()) { if(lockEntity != null) { // TODO: JCC - Remove before finalizing. //lockEntity.setHeading(lockEntity.getHeading() + Math.PI/6400); // TODO: JCC - Clean up. Now centers on the actual entity rather than the shadow. Double agl = (Double) lockEntity.getProperty(EntityConstants.PROPERTY_AGL); transformer.setRotation(-lockEntity.getHeading() + Math.PI/2); showPosition(EntityShape.adjustPositionForShadow(lockEntity.getPosition(), agl), false); } time = sim.getTime(); shapeAdapter.update(); detonationShapes.update(); speechBubbles.update(); shapeSystem.update(transformer); } // Set up the graphics contexts... Graphics2D g2d = (Graphics2D) g; SwingTools.enableAntiAliasing(g2d); Graphics2D g2dCopy = (Graphics2D) g2d.create(); SwingTools.enableAntiAliasing(g2dCopy); // Now draw everything again. None of the following code should be // dependent on a sim lock. if(map != null) { map.draw(g2d, transformer); } grid.draw(g2d); factory.setGraphics2D(g2dCopy, getWidth(), getHeight()); timedShapes.update(time); shapeSystem.draw(factory); shapeSystem.displayErrors(factory); //shapeSystem.displayDebugging(factory, transformer); g2dCopy.dispose(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "paintComponent"
"@Override public void paintComponent(Graphics g) { super.paintComponent(g); if(appStateIndicator.getState() != ApplicationState.RUNNING) { return; } showCoordinates(); // Briefly lock the sim to update entity shapes and stuff. double time = 0.0; synchronized (sim.getLock()) { if(lockEntity != null) { // TODO: JCC - Remove before finalizing. //lockEntity.setHeading(lockEntity.getHeading() + Math.PI/6400); // TODO: JCC - Clean up. Now centers on the actual entity rather than the shadow. Double agl = (Double) lockEntity.getProperty(EntityConstants.PROPERTY_AGL); <MASK>showPosition(EntityShape.adjustPositionForShadow(lockEntity.getPosition(), agl), false);</MASK> transformer.setRotation(-lockEntity.getHeading() + Math.PI/2); } time = sim.getTime(); shapeAdapter.update(); detonationShapes.update(); speechBubbles.update(); shapeSystem.update(transformer); } // Set up the graphics contexts... Graphics2D g2d = (Graphics2D) g; SwingTools.enableAntiAliasing(g2d); Graphics2D g2dCopy = (Graphics2D) g2d.create(); SwingTools.enableAntiAliasing(g2dCopy); // Now draw everything again. None of the following code should be // dependent on a sim lock. if(map != null) { map.draw(g2d, transformer); } grid.draw(g2d); factory.setGraphics2D(g2dCopy, getWidth(), getHeight()); timedShapes.update(time); shapeSystem.draw(factory); shapeSystem.displayErrors(factory); //shapeSystem.displayDebugging(factory, transformer); g2dCopy.dispose(); }"
Inversion-Mutation
megadiff
"public Player(Socket client, PacketManager pm, byte opCode) { super(client, pm); ID = getFreeID(); this.chat = new Messages(pm.server); if (opCode != 255) { Packet packet = pm.getPacket(opCode); if (packet == null) { pm.server.Log("Client sent " + opCode); pm.server.Log("How do..?"); } else { byte[] message = new byte[packet.length]; try { reader.read(message); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (message.length < packet.length) { pm.server.Log("Bad packet.."); } else packet.Handle(message, pm.server, this); } } Listen(); pm.server.Add(tick); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "Player"
"public Player(Socket client, PacketManager pm, byte opCode) { super(client, pm); ID = getFreeID(); if (opCode != 255) { Packet packet = pm.getPacket(opCode); if (packet == null) { pm.server.Log("Client sent " + opCode); pm.server.Log("How do..?"); } else { byte[] message = new byte[packet.length]; try { reader.read(message); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (message.length < packet.length) { pm.server.Log("Bad packet.."); } else packet.Handle(message, pm.server, this); } } Listen(); pm.server.Add(tick); <MASK>this.chat = new Messages(pm.server);</MASK> }"
Inversion-Mutation
megadiff
"@Override protected void onCreate(Bundle savedInstanceState) { ThemeManager.setTheme(this); super.onCreate(savedInstanceState); //int sdk = Build.VERSION.SDK_INT; //if (sdk < 11) { requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); setContentView(R.layout.main); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title); //} }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCreate"
"@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //int sdk = Build.VERSION.SDK_INT; //if (sdk < 11) { requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); <MASK>ThemeManager.setTheme(this);</MASK> setContentView(R.layout.main); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title); //} }"
Inversion-Mutation
megadiff
"@Override protected Void doInBackground(Void... params) { if (pickedTheme.contains("STOCK")) { readUIValuesFromXML(pickedTheme); } else { Intent mvSdUi = new Intent("com.cyanogenmod.cmparts.RESTORE_CMPARTS_UI"); mvSdUi.putExtra("filename", pickedTheme); mActivity.sendBroadcast(mvSdUi); } 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... params) { if (pickedTheme.contains("STOCK")) { readUIValuesFromXML(pickedTheme); <MASK>return null;</MASK> } else { Intent mvSdUi = new Intent("com.cyanogenmod.cmparts.RESTORE_CMPARTS_UI"); mvSdUi.putExtra("filename", pickedTheme); mActivity.sendBroadcast(mvSdUi); } }"
Inversion-Mutation
megadiff
"public final void togglePaneExpanded(final TogglePaneStateEvent stateEventParam) { //TODO check that the source corresponds to a toggle pane that actually belongs to this accordion final TogglePaneState state = stateEventParam.getSource(); Reqs.PRE_COND.Logic.requireTrue(isTogglePaneBelongingToThisAccordion(state), "Expanded toggle pane does not belong to this accordion!"); if (maximumOneTogglePaneExpanded) { Reqs.PRE_COND.Logic.requireTrue(expandedTogglePaneStates.size() <= 1, "There must be maximum one expanded pane."); final List<TogglePaneState> expandedTogglePanesStatesCopy = new ArrayList<TogglePaneState>(expandedTogglePaneStates); for (final TogglePaneState current : expandedTogglePanesStatesCopy) { current.toggleContent(); //collapse all expanded panes } Reqs.POST_COND.Logic.requireTrue(expandedTogglePaneStates.size() == 1, "There must be exactly one expanded pane."); } expandedTogglePaneStates.add(stateEventParam.getSource()); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "togglePaneExpanded"
"public final void togglePaneExpanded(final TogglePaneStateEvent stateEventParam) { //TODO check that the source corresponds to a toggle pane that actually belongs to this accordion final TogglePaneState state = stateEventParam.getSource(); Reqs.PRE_COND.Logic.requireTrue(isTogglePaneBelongingToThisAccordion(state), "Expanded toggle pane does not belong to this accordion!"); if (maximumOneTogglePaneExpanded) { Reqs.PRE_COND.Logic.requireTrue(expandedTogglePaneStates.size() <= 1, "There must be maximum one expanded pane."); final List<TogglePaneState> expandedTogglePanesStatesCopy = new ArrayList<TogglePaneState>(expandedTogglePaneStates); for (final TogglePaneState current : expandedTogglePanesStatesCopy) { current.toggleContent(); //collapse all expanded panes } } expandedTogglePaneStates.add(stateEventParam.getSource()); <MASK>Reqs.POST_COND.Logic.requireTrue(expandedTogglePaneStates.size() == 1, "There must be exactly one expanded pane.");</MASK> }"
Inversion-Mutation
megadiff
"public static TextPaint getPaint(BaseDanmaku danmaku) { PAINT.setTextSize(danmaku.textSize); applyTextScaleConfig(danmaku, PAINT); if (HAS_SHADOW) { PAINT.setShadowLayer(3.0f, 0, 0, danmaku.textShadowColor); } else { PAINT.clearShadowLayer(); } PAINT.setAntiAlias(ANTI_ALIAS); return PAINT; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getPaint"
"public static TextPaint getPaint(BaseDanmaku danmaku) { PAINT.setTextSize(danmaku.textSize); applyTextScaleConfig(danmaku, PAINT); <MASK>PAINT.setAntiAlias(ANTI_ALIAS);</MASK> if (HAS_SHADOW) { PAINT.setShadowLayer(3.0f, 0, 0, danmaku.textShadowColor); } else { PAINT.clearShadowLayer(); } return PAINT; }"
Inversion-Mutation
megadiff
"private Table getPlaceInGroupForm() throws RemoteException { Table table = new Table(); table.setCellpadding(5); table.setWidth(Table.HUNDRED_PERCENT); table.setHeight(Table.HUNDRED_PERCENT); int row = 1; ChildCareApplication application = getBusiness().getApplication(_applicationID); boolean hasBankId = false; hasBankId = new NBSLoginBusinessBean().hasBankLogin(application.getOwner()); if (hasBankId) { table.add(getSmallText(localize("child_care.child_care_time", "Time") + ":"), 1, row); table.add(getSmallText(getCareTime(application.getCareTime())), 1, row++); table.add(new HiddenInput(PARAMETER_CHILDCARE_TIME, application.getCareTime()), 1, 1); } else { table.add(getSmallHeader(localize("child_care.enter_child_care_time", "Enter child care time:")), 1, row++); table.add(getSmallText(localize("child_care.child_care_time", "Time") + ":"), 1, row); if (isUsePredefinedCareTimeValues()) { DropdownMenu menu = getCareTimeMenu(PARAMETER_CHILDCARE_TIME); table.add(menu, 1, row++); } else { TextInput textInput = (TextInput) getStyledInterface(new TextInput(PARAMETER_CHILDCARE_TIME)); textInput.setLength(2); textInput.setMaxlength(2); textInput.setAsNotEmpty(localize("child_care.child_care_time_required", "You must fill in the child care time.")); textInput.setAsIntegers(localize("child_care.only_integers_allowed", "Not a valid child care time.")); table.add(textInput, 1, row++); } } if (getBusiness().hasFutureActivePlacementsNotWithProvider(getSession().getChildID(), getSession().getChildCareID(), application.getFromDate())) { ChildCareApplication futureApplication = getBusiness().getFirstFuturePlacementNotWithProvider(getSession().getChildID(), getSession().getChildCareID(), application.getFromDate()); if (futureApplication != null) { IWTimestamp futureStartDate = new IWTimestamp(futureApplication.getFromDate()); futureStartDate.addDays(-1); IWTimestamp startDate = new IWTimestamp(application.getFromDate()); startDate.addDays(1); table.add(getSmallHeader(localize("child_care.termination_date", "Termination date") + ":"), 1, row); DateInput termination = (DateInput) getStyledInterface(new DateInput(PARAMETER_TERMINATION_DATE)); termination.setLatestPossibleDate(futureStartDate.getDate(), localize("child_care.contract_dates_overlap", "You can not choose a date which overlaps another contract.")); termination.setEarliestPossibleDate(startDate.getDate(), localize("child_care.start_and_end_dates_overlap", "You can not choose a termination date the same as the start date.")); termination.setAsNotEmpty(localize("child_care.must_choose_termination_date", "You have to choose a termination date")); table.add(termination, 1, row++); } } /* *******restricting the classes being chosen */ Collection types = null; SchoolBusiness schBuiz = getBusiness().getSchoolBusiness(); SchoolCategory typeChildcare = schBuiz.getCategoryChildcare(); try { types = application.getProvider().findRelatedSchoolTypes(typeChildcare); } catch (IDORelationshipException e) { e.printStackTrace(); } catch (EJBException e) { e.printStackTrace(); } SchoolClassDropdownDouble schoolClasses = new SchoolClassDropdownDouble(getSession().getParameterSchoolTypeID(), getSession().getParameterGroupID()); // schoolClasses.setLayoutVertical(true); // schoolClasses.setPrimaryLabel(getSmallText(localize("child_care.schooltype", // "Type")+":")); // schoolClasses.setSecondaryLabel(getSmallText(localize("child_care.group", // "Group")+":")); // schoolClasses.setVerticalSpaceBetween(15); // schoolClasses.setSpaceBetween(15); // schoolClasses.setNoDataListEntry(localize("child_care.no_school_classes","No // school classes")); schoolClasses = (SchoolClassDropdownDouble) getStyledInterface(schoolClasses); // int classID = archive.getSchoolClassMember().getSchoolClassId(); if (getChildcareID() != -1) { if (!types.isEmpty()) { Map typeGroupMap = getBusiness().getSchoolTypeClassMap(types, application.getProviderId(), getSession().getSeasonID(), null, null, localize("child_care.no_school_classes", "No school classes")); if (typeGroupMap != null) { Iterator iter = typeGroupMap.keySet().iterator(); while (iter.hasNext()) { SchoolType schoolType = (SchoolType) iter.next(); schoolClasses.addMenuElement(schoolType.getPrimaryKey().toString(), schoolType.getSchoolTypeName(), (Map) typeGroupMap.get(schoolType)); } } } } Table dropdownTable = new Table(); int dropRow = 1; schoolClasses.addEmptyElement(localize("child_care.choose_schooltype", "Choose here"), localize("child_care.choose_schoolgroup", "Choose here")); // DropdownMenu schoolTypes = getSchoolTypes(-1, -1); // DropdownMenu schoolTypes = schoolClasses.getPrimaryDropdown(); // schoolClasses.getPrimaryDropdown().addMenuElementFirst("-1",localize("child_care.choose_schooltype","Choose // here")); schoolClasses.getPrimaryDropdown().setAsNotEmpty(localize("child_care.must_select_a_type", "You must select a type."), "-1"); dropdownTable.add(getSmallText(localize("child_care.schooltype", "Type") + ":"), 1, dropRow); dropdownTable.add(schoolClasses.getPrimaryDropdown(), 2, dropRow++); // dropdownTable.add(schoolClasses); // DropdownMenu groups = getGroups(-1, -1) // DropdownMenu groups = schoolClasses.getSecondaryDropdown(); // schoolClasses.getSecondaryDropdown().addMenuElementFirst("-1",localize("child_care.choose_schoolgroup","Choose // here")); schoolClasses.getSecondaryDropdown().setAsNotEmpty(localize("child_care.must_select_a_group", "You must select a group. If one does not exist, you will have to create one first."), "-1"); dropdownTable.add(getSmallText(localize("child_care.group", "Group") + ":"), 1, dropRow); dropdownTable.add(schoolClasses.getSecondaryDropdown(), 2, dropRow++); // dropdownTable.add(getSmallText(localize("child_care.school_type_and_school_class", // "School type and class")+":"), 1, dropRow); // table.add(mSchoolType, 2, row++); dropdownTable.add(schoolClasses, 2, dropRow); if (_showEmploymentDrop) { DropdownMenu employmentTypes = getEmploymentTypes(PARAMETER_EMPLOYMENT_TYPE, -1); employmentTypes.setAsNotEmpty(localize("child_care.must_select_employment_type", "You must select employment type."), "-1"); dropdownTable.add(getSmallText(localize("child_care.employment_type", "Employment type") + ":"), 1, dropRow); dropdownTable.add(employmentTypes, 2, dropRow); } table.add(dropdownTable, 1, row++); SubmitButton placeInGroup = (SubmitButton) getStyledInterface(new SubmitButton(localize("child_care.place_in_group", "Place in group"), PARAMETER_ACTION, String.valueOf(ACTION_PLACE_IN_GROUP))); _submitButton = placeInGroup; _child = application.getChild(); _addCareTimeScript = isUsePredefinedCareTimeValues(); close.setOnClick("javascript:findObj('" + PARAMETER_CLOSE + "').value = 'true';"); form.add(new HiddenInput(PARAMETER_CLOSE, "false")); table.add(placeInGroup, 1, row); table.add(Text.getNonBrakingSpace(), 1, row); table.add(close, 1, row); table.setHeight(row, Table.HUNDRED_PERCENT); table.setRowVerticalAlignment(row, Table.VERTICAL_ALIGN_BOTTOM); form.setToDisableOnSubmit(placeInGroup, true); return table; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getPlaceInGroupForm"
"private Table getPlaceInGroupForm() throws RemoteException { Table table = new Table(); table.setCellpadding(5); table.setWidth(Table.HUNDRED_PERCENT); table.setHeight(Table.HUNDRED_PERCENT); int row = 1; ChildCareApplication application = getBusiness().getApplication(_applicationID); boolean hasBankId = false; hasBankId = new NBSLoginBusinessBean().hasBankLogin(application.getOwner()); if (hasBankId) { table.add(getSmallText(localize("child_care.child_care_time", "Time") + ":"), 1, row); table.add(getSmallText(getCareTime(application.getCareTime())), 1, row++); table.add(new HiddenInput(PARAMETER_CHILDCARE_TIME, application.getCareTime()), 1, 1); } else { table.add(getSmallHeader(localize("child_care.enter_child_care_time", "Enter child care time:")), 1, row++); table.add(getSmallText(localize("child_care.child_care_time", "Time") + ":"), 1, row); if (isUsePredefinedCareTimeValues()) { DropdownMenu menu = getCareTimeMenu(PARAMETER_CHILDCARE_TIME); table.add(menu, 1, row++); } else { TextInput textInput = (TextInput) getStyledInterface(new TextInput(PARAMETER_CHILDCARE_TIME)); textInput.setLength(2); textInput.setMaxlength(2); textInput.setAsNotEmpty(localize("child_care.child_care_time_required", "You must fill in the child care time.")); textInput.setAsIntegers(localize("child_care.only_integers_allowed", "Not a valid child care time.")); table.add(textInput, 1, row++); } } if (getBusiness().hasFutureActivePlacementsNotWithProvider(getSession().getChildID(), getSession().getChildCareID(), application.getFromDate())) { ChildCareApplication futureApplication = getBusiness().getFirstFuturePlacementNotWithProvider(getSession().getChildID(), getSession().getChildCareID(), application.getFromDate()); if (futureApplication != null) { IWTimestamp futureStartDate = new IWTimestamp(futureApplication.getFromDate()); futureStartDate.addDays(-1); IWTimestamp startDate = new IWTimestamp(application.getFromDate()); startDate.addDays(1); table.add(getSmallHeader(localize("child_care.termination_date", "Termination date") + ":"), 1, row); DateInput termination = (DateInput) getStyledInterface(new DateInput(PARAMETER_TERMINATION_DATE)); termination.setLatestPossibleDate(futureStartDate.getDate(), localize("child_care.contract_dates_overlap", "You can not choose a date which overlaps another contract.")); termination.setEarliestPossibleDate(startDate.getDate(), localize("child_care.start_and_end_dates_overlap", "You can not choose a termination date the same as the start date.")); termination.setAsNotEmpty(localize("child_care.must_choose_termination_date", "You have to choose a termination date")); table.add(termination, 1, row++); } } /* *******restricting the classes being chosen */ Collection types = null; SchoolBusiness schBuiz = getBusiness().getSchoolBusiness(); SchoolCategory typeChildcare = schBuiz.getCategoryChildcare(); try { types = application.getProvider().findRelatedSchoolTypes(typeChildcare); } catch (IDORelationshipException e) { e.printStackTrace(); } catch (EJBException e) { e.printStackTrace(); } SchoolClassDropdownDouble schoolClasses = new SchoolClassDropdownDouble(getSession().getParameterSchoolTypeID(), getSession().getParameterGroupID()); // schoolClasses.setLayoutVertical(true); // schoolClasses.setPrimaryLabel(getSmallText(localize("child_care.schooltype", // "Type")+":")); // schoolClasses.setSecondaryLabel(getSmallText(localize("child_care.group", // "Group")+":")); // schoolClasses.setVerticalSpaceBetween(15); // schoolClasses.setSpaceBetween(15); // schoolClasses.setNoDataListEntry(localize("child_care.no_school_classes","No // school classes")); schoolClasses = (SchoolClassDropdownDouble) getStyledInterface(schoolClasses); // int classID = archive.getSchoolClassMember().getSchoolClassId(); if (getChildcareID() != -1) { if (!types.isEmpty()) { Map typeGroupMap = getBusiness().getSchoolTypeClassMap(types, application.getProviderId(), getSession().getSeasonID(), null, null, localize("child_care.no_school_classes", "No school classes")); if (typeGroupMap != null) { Iterator iter = typeGroupMap.keySet().iterator(); while (iter.hasNext()) { SchoolType schoolType = (SchoolType) iter.next(); schoolClasses.addMenuElement(schoolType.getPrimaryKey().toString(), schoolType.getSchoolTypeName(), (Map) typeGroupMap.get(schoolType)); } } } } Table dropdownTable = new Table(); int dropRow = 1; schoolClasses.addEmptyElement(localize("child_care.choose_schooltype", "Choose here"), localize("child_care.choose_schoolgroup", "Choose here")); // DropdownMenu schoolTypes = getSchoolTypes(-1, -1); // DropdownMenu schoolTypes = schoolClasses.getPrimaryDropdown(); // schoolClasses.getPrimaryDropdown().addMenuElementFirst("-1",localize("child_care.choose_schooltype","Choose // here")); schoolClasses.getPrimaryDropdown().setAsNotEmpty(localize("child_care.must_select_a_type", "You must select a type."), "-1"); dropdownTable.add(getSmallText(localize("child_care.schooltype", "Type") + ":"), 1, dropRow); dropdownTable.add(schoolClasses.getPrimaryDropdown(), 2, dropRow++); // dropdownTable.add(schoolClasses); // DropdownMenu groups = getGroups(-1, -1) // DropdownMenu groups = schoolClasses.getSecondaryDropdown(); // schoolClasses.getSecondaryDropdown().addMenuElementFirst("-1",localize("child_care.choose_schoolgroup","Choose // here")); schoolClasses.getSecondaryDropdown().setAsNotEmpty(localize("child_care.must_select_a_group", "You must select a group. If one does not exist, you will have to create one first."), "-1"); dropdownTable.add(getSmallText(localize("child_care.group", "Group") + ":"), 1, dropRow); dropdownTable.add(schoolClasses.getSecondaryDropdown(), 2, dropRow++); // dropdownTable.add(getSmallText(localize("child_care.school_type_and_school_class", // "School type and class")+":"), 1, dropRow); // table.add(mSchoolType, 2, row++); dropdownTable.add(schoolClasses, 2, dropRow); if (_showEmploymentDrop) { DropdownMenu employmentTypes = getEmploymentTypes(PARAMETER_EMPLOYMENT_TYPE, -1); employmentTypes.setAsNotEmpty(localize("child_care.must_select_employment_type", "You must select employment type."), "-1"); dropdownTable.add(getSmallText(localize("child_care.employment_type", "Employment type") + ":"), 1, dropRow); dropdownTable.add(employmentTypes, 2, dropRow); } table.add(dropdownTable, 1, row++); SubmitButton placeInGroup = (SubmitButton) getStyledInterface(new SubmitButton(localize("child_care.place_in_group", "Place in group"), PARAMETER_ACTION, String.valueOf(ACTION_PLACE_IN_GROUP))); <MASK>form.setToDisableOnSubmit(placeInGroup, true);</MASK> _submitButton = placeInGroup; _child = application.getChild(); _addCareTimeScript = isUsePredefinedCareTimeValues(); close.setOnClick("javascript:findObj('" + PARAMETER_CLOSE + "').value = 'true';"); form.add(new HiddenInput(PARAMETER_CLOSE, "false")); table.add(placeInGroup, 1, row); table.add(Text.getNonBrakingSpace(), 1, row); table.add(close, 1, row); table.setHeight(row, Table.HUNDRED_PERCENT); table.setRowVerticalAlignment(row, Table.VERTICAL_ALIGN_BOTTOM); return table; }"
Inversion-Mutation
megadiff
"public void documentChanged(DocumentEvent e) { if (fWidgetCommand.event == e) updateTextListeners(fWidgetCommand); fLastSentSelectionChange= null; handleVisibleDocumentChanged(e); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "documentChanged"
"public void documentChanged(DocumentEvent e) { <MASK>handleVisibleDocumentChanged(e);</MASK> if (fWidgetCommand.event == e) updateTextListeners(fWidgetCommand); fLastSentSelectionChange= null; }"
Inversion-Mutation
megadiff
"public Callback getObservers() { Callback callback = new Callback(); callback.attachForwardingObserver(propManager); callback.attachForwardingObserver(movementMonitor); callback.attachForwardedObserver(movementMonitor); callback.attachForwardedObserver(estateManager); callback.attachForwardedObserver(sceneManager); return callback; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getObservers"
"public Callback getObservers() { Callback callback = new Callback(); callback.attachForwardingObserver(propManager); callback.attachForwardingObserver(movementMonitor); callback.attachForwardedObserver(estateManager); callback.attachForwardedObserver(sceneManager); <MASK>callback.attachForwardedObserver(movementMonitor);</MASK> return callback; }"
Inversion-Mutation
megadiff
"@Override public Type typeCheck(Environment env, TypeList qualifiers, NameScope scope) { Pattern pattern = state.initPattern; Expression exp = state.initExpression; boolean canBeExecuted = false; if (pattern instanceof IdentifierPattern && exp instanceof EqualsExpression) { EqualsExpression ee = (EqualsExpression)exp; ee.left.typeCheck(env, null, scope); if (ee.left instanceof VariableExpression) { Type rhs = ee.right.typeCheck(env, null, scope); if (rhs.isRecord()) { RecordType rt = rhs.getRecord(); canBeExecuted = rt.name.equals(state.name); } } } else { exp.typeCheck(env, null, scope); } if (!canBeExecuted) { warning(5010, "State init expression cannot be executed"); detail("Expected", "p == p = mk_Record(...)"); } state.canBeExecuted = canBeExecuted; return new BooleanType(location); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "typeCheck"
"@Override public Type typeCheck(Environment env, TypeList qualifiers, NameScope scope) { Pattern pattern = state.initPattern; Expression exp = state.initExpression; boolean canBeExecuted = false; if (pattern instanceof IdentifierPattern && exp instanceof EqualsExpression) { EqualsExpression ee = (EqualsExpression)exp; if (ee.left instanceof VariableExpression) { <MASK>ee.left.typeCheck(env, null, scope);</MASK> Type rhs = ee.right.typeCheck(env, null, scope); if (rhs.isRecord()) { RecordType rt = rhs.getRecord(); canBeExecuted = rt.name.equals(state.name); } } } else { exp.typeCheck(env, null, scope); } if (!canBeExecuted) { warning(5010, "State init expression cannot be executed"); detail("Expected", "p == p = mk_Record(...)"); } state.canBeExecuted = canBeExecuted; return new BooleanType(location); }"
Inversion-Mutation
megadiff
"private void initSuggest() { String locale = mSubtypeSwitcher.getInputLocaleStr(); Locale savedLocale = mSubtypeSwitcher.changeSystemLocale(new Locale(locale)); if (mSuggest != null) { mSuggest.close(); } final SharedPreferences prefs = mPrefs; mQuickFixes = isQuickFixesEnabled(prefs); final Resources res = mResources; int mainDicResId = Utils.getMainDictionaryResourceId(res); mSuggest = new Suggest(this, mainDicResId); loadAndSetAutoCorrectionThreshold(prefs); updateAutoTextEnabled(); mUserDictionary = new UserDictionary(this, locale); mSuggest.setUserDictionary(mUserDictionary); mContactsDictionary = new ContactsDictionary(this, Suggest.DIC_CONTACTS); mSuggest.setContactsDictionary(mContactsDictionary); mAutoDictionary = new AutoDictionary(this, this, locale, Suggest.DIC_AUTO); mSuggest.setAutoDictionary(mAutoDictionary); mUserBigramDictionary = new UserBigramDictionary(this, this, locale, Suggest.DIC_USER); mSuggest.setUserBigramDictionary(mUserBigramDictionary); updateCorrectionMode(); mWordSeparators = res.getString(R.string.word_separators); mSentenceSeparators = res.getString(R.string.sentence_separators); mSubtypeSwitcher.changeSystemLocale(savedLocale); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "initSuggest"
"private void initSuggest() { <MASK>updateAutoTextEnabled();</MASK> String locale = mSubtypeSwitcher.getInputLocaleStr(); Locale savedLocale = mSubtypeSwitcher.changeSystemLocale(new Locale(locale)); if (mSuggest != null) { mSuggest.close(); } final SharedPreferences prefs = mPrefs; mQuickFixes = isQuickFixesEnabled(prefs); final Resources res = mResources; int mainDicResId = Utils.getMainDictionaryResourceId(res); mSuggest = new Suggest(this, mainDicResId); loadAndSetAutoCorrectionThreshold(prefs); mUserDictionary = new UserDictionary(this, locale); mSuggest.setUserDictionary(mUserDictionary); mContactsDictionary = new ContactsDictionary(this, Suggest.DIC_CONTACTS); mSuggest.setContactsDictionary(mContactsDictionary); mAutoDictionary = new AutoDictionary(this, this, locale, Suggest.DIC_AUTO); mSuggest.setAutoDictionary(mAutoDictionary); mUserBigramDictionary = new UserBigramDictionary(this, this, locale, Suggest.DIC_USER); mSuggest.setUserBigramDictionary(mUserBigramDictionary); updateCorrectionMode(); mWordSeparators = res.getString(R.string.word_separators); mSentenceSeparators = res.getString(R.string.sentence_separators); mSubtypeSwitcher.changeSystemLocale(savedLocale); }"
Inversion-Mutation
megadiff
"@EventHandler(priority = EventPriority.HIGH) public void onPlayerInteractEvent (PlayerInteractEvent event) { // Check whether the block still exists if (event.getClickedBlock() == null) return; // Check the player did something to a sign if (!(event.getClickedBlock().getState() instanceof Sign)) return; // Check that that something was a right click if (!(event.getAction() == Action.RIGHT_CLICK_BLOCK)) return; Sign sign = (Sign) event.getClickedBlock().getState(); // Check that this is *our* sign if (sign.getLine(0).equalsIgnoreCase("[ArenaControl]")) { // Check the player's permissions if (event.getPlayer().hasPermission("ArenaControl.apply")) { // Assign the template on the third line to the // arena on the second line assignTemplateToArena(sign.getLine(1), sign.getLine(2), event.getPlayer()); } else { event.getPlayer().sendMessage("You don't have permission."); return; } event.setCancelled(true); } // Successful, so eat the event. }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onPlayerInteractEvent"
"@EventHandler(priority = EventPriority.HIGH) public void onPlayerInteractEvent (PlayerInteractEvent event) { // Check whether the block still exists if (event.getClickedBlock() == null) return; // Check the player did something to a sign if (!(event.getClickedBlock().getState() instanceof Sign)) return; // Check that that something was a right click if (!(event.getAction() == Action.RIGHT_CLICK_BLOCK)) return; Sign sign = (Sign) event.getClickedBlock().getState(); // Check that this is *our* sign if (sign.getLine(0).equalsIgnoreCase("[ArenaControl]")) { // Check the player's permissions if (event.getPlayer().hasPermission("ArenaControl.apply")) { // Assign the template on the third line to the // arena on the second line assignTemplateToArena(sign.getLine(1), sign.getLine(2), event.getPlayer()); } else { event.getPlayer().sendMessage("You don't have permission."); return; } } // Successful, so eat the event. <MASK>event.setCancelled(true);</MASK> }"
Inversion-Mutation
megadiff
"protected void drawCrosshairs(double[] beamCentre, double length, Color colour, Color labelColour, String nameStub, String labelText) { if (!active) return; // We are likely off screen. if (crosshairs == null) { try { final String regionName = RegionUtils.getUniqueName(nameStub, plottingSystem); crosshairs = plottingSystem.createRegion(regionName, RegionType.LINE); crosshairs.setUserRegion(false); } catch (Exception e) { logger.error("Can't create region", e); return; } final LinearROI lroi = new LinearROI(length, 0); lroi.setMidPoint(beamCentre); lroi.setCrossHair(true); crosshairs.setROI(lroi); crosshairs.setRegionColor(colour); crosshairs.setAlpha(100); crosshairs.setShowPosition(false); crosshairs.setUserObject(RING_TYPE.BEAM_CENTRE); crosshairs.setLabel(labelText); crosshairs.setShowLabel(true); plottingSystem.addRegion(crosshairs); crosshairs.setMobile(false); // NOTE: Must be done **AFTER** calling the // addRegion method. crosshairs.toBack(); } else { LinearROI lroi = (LinearROI) crosshairs.getROI(); lroi.setLength(length); lroi.setMidPoint(beamCentre); crosshairs.setRegionColor(colour); crosshairs.setLabel(labelText); crosshairs.toBack(); // crosshairs.setROI(lroi); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "drawCrosshairs"
"protected void drawCrosshairs(double[] beamCentre, double length, Color colour, Color labelColour, String nameStub, String labelText) { if (!active) return; // We are likely off screen. if (crosshairs == null) { try { final String regionName = RegionUtils.getUniqueName(nameStub, plottingSystem); crosshairs = plottingSystem.createRegion(regionName, RegionType.LINE); } catch (Exception e) { logger.error("Can't create region", e); return; } final LinearROI lroi = new LinearROI(length, 0); lroi.setMidPoint(beamCentre); lroi.setCrossHair(true); crosshairs.setROI(lroi); crosshairs.setRegionColor(colour); crosshairs.setAlpha(100); <MASK>crosshairs.setUserRegion(false);</MASK> crosshairs.setShowPosition(false); crosshairs.setUserObject(RING_TYPE.BEAM_CENTRE); crosshairs.setLabel(labelText); crosshairs.setShowLabel(true); plottingSystem.addRegion(crosshairs); crosshairs.setMobile(false); // NOTE: Must be done **AFTER** calling the // addRegion method. crosshairs.toBack(); } else { LinearROI lroi = (LinearROI) crosshairs.getROI(); lroi.setLength(length); lroi.setMidPoint(beamCentre); crosshairs.setRegionColor(colour); crosshairs.setLabel(labelText); crosshairs.toBack(); // crosshairs.setROI(lroi); } }"
Inversion-Mutation
megadiff
"public void visitCompilationUnit(GNode n) { printer.p("#include <iostream>\n"); printer.p("#include <sstream>\n"); printer.p("#include \"out.h\"\n"); printer.pln(); visit(n); printer.flush(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "visitCompilationUnit"
"public void visitCompilationUnit(GNode n) { <MASK>printer.p("#include \"out.h\"\n");</MASK> printer.p("#include <iostream>\n"); printer.p("#include <sstream>\n"); printer.pln(); visit(n); printer.flush(); }"
Inversion-Mutation
megadiff
"protected XSAttributeUseImpl traverseLocal(Element attrDecl, XSDocumentInfo schemaDoc, SchemaGrammar grammar, XSComplexTypeDecl enclosingCT) { // General Attribute Checking Object[] attrValues = fAttrChecker.checkAttributes(attrDecl, false, schemaDoc); String defaultAtt = (String) attrValues[XSAttributeChecker.ATTIDX_DEFAULT]; String fixedAtt = (String) attrValues[XSAttributeChecker.ATTIDX_FIXED]; String nameAtt = (String) attrValues[XSAttributeChecker.ATTIDX_NAME]; QName refAtt = (QName) attrValues[XSAttributeChecker.ATTIDX_REF]; XInt useAtt = (XInt) attrValues[XSAttributeChecker.ATTIDX_USE]; // get 'attribute declaration' XSAttributeDecl attribute = null; if (attrDecl.getAttributeNode(SchemaSymbols.ATT_REF) != null) { if (refAtt != null) { attribute = (XSAttributeDecl)fSchemaHandler.getGlobalDecl(schemaDoc, XSDHandler.ATTRIBUTE_TYPE, refAtt, attrDecl); Element child = DOMUtil.getFirstChildElement(attrDecl); if (child != null && DOMUtil.getLocalName(child).equals(SchemaSymbols.ELT_ANNOTATION)) { // REVISIT: put this somewhere traverseAnnotationDecl(child, attrValues, false, schemaDoc); child = DOMUtil.getNextSiblingElement(child); } if (child != null) { reportSchemaError("src-attribute.3.2", new Object[]{refAtt.rawname}, child); } // for error reporting nameAtt = refAtt.localpart; } else { attribute = null; } } else { attribute = traverseNamedAttr(attrDecl, attrValues, schemaDoc, grammar, false, enclosingCT); } // get 'value constraint' short consType = XSConstants.VC_NONE; if (defaultAtt != null) { consType = XSConstants.VC_DEFAULT; } else if (fixedAtt != null) { consType = XSConstants.VC_FIXED; defaultAtt = fixedAtt; fixedAtt = null; } XSAttributeUseImpl attrUse = null; if (attribute != null) { if (fSchemaHandler.fDeclPool !=null) { attrUse = fSchemaHandler.fDeclPool.getAttributeUse(); } else { attrUse = new XSAttributeUseImpl(); } attrUse.fAttrDecl = attribute; attrUse.fUse = useAtt.shortValue(); attrUse.fConstraintType = consType; if (defaultAtt != null) { attrUse.fDefault = new ValidatedInfo(); attrUse.fDefault.normalizedValue = defaultAtt; } } //src-attribute // 1 default and fixed must not both be present. if (defaultAtt != null && fixedAtt != null) { reportSchemaError("src-attribute.1", new Object[]{nameAtt}, attrDecl); } // 2 If default and use are both present, use must have the actual value optional. if (consType == XSConstants.VC_DEFAULT && useAtt != null && useAtt.intValue() != SchemaSymbols.USE_OPTIONAL) { reportSchemaError("src-attribute.2", new Object[]{nameAtt}, attrDecl); } // a-props-correct if (defaultAtt != null && attrUse != null) { // 2 if there is a {value constraint}, the canonical lexical representation of its value must be valid with respect to the {type definition} as defined in String Valid (3.14.4). fValidationState.setNamespaceSupport(schemaDoc.fNamespaceSupport); try { checkDefaultValid(attrUse); } catch (InvalidDatatypeValueException ide) { reportSchemaError (ide.getKey(), ide.getArgs(), attrDecl); reportSchemaError ("a-props-correct.2", new Object[]{nameAtt, defaultAtt}, attrDecl); } // 3 If the {type definition} is or is derived from ID then there must not be a {value constraint}. if (((XSSimpleType)attribute.getTypeDefinition()).isIDType() ) { reportSchemaError ("a-props-correct.3", new Object[]{nameAtt}, attrDecl); } // check 3.5.6 constraint // Attribute Use Correct // 2 If the {attribute declaration} has a fixed {value constraint}, then if the attribute use itself has a {value constraint}, it must also be fixed and its value must match that of the {attribute declaration}'s {value constraint}. if (attrUse.fAttrDecl.getConstraintType() == XSConstants.VC_FIXED && attrUse.fConstraintType != XSConstants.VC_NONE) { if (attrUse.fConstraintType != XSConstants.VC_FIXED || !attrUse.fAttrDecl.getValInfo().actualValue.equals(attrUse.fDefault.actualValue)) { reportSchemaError ("au-props-correct.2", new Object[]{nameAtt, attrUse.fAttrDecl.getValInfo().stringValue()}, attrDecl); } } } fAttrChecker.returnAttrArray(attrValues, schemaDoc); return attrUse; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "traverseLocal"
"protected XSAttributeUseImpl traverseLocal(Element attrDecl, XSDocumentInfo schemaDoc, SchemaGrammar grammar, XSComplexTypeDecl enclosingCT) { // General Attribute Checking Object[] attrValues = fAttrChecker.checkAttributes(attrDecl, false, schemaDoc); String defaultAtt = (String) attrValues[XSAttributeChecker.ATTIDX_DEFAULT]; String fixedAtt = (String) attrValues[XSAttributeChecker.ATTIDX_FIXED]; String nameAtt = (String) attrValues[XSAttributeChecker.ATTIDX_NAME]; QName refAtt = (QName) attrValues[XSAttributeChecker.ATTIDX_REF]; XInt useAtt = (XInt) attrValues[XSAttributeChecker.ATTIDX_USE]; // get 'attribute declaration' XSAttributeDecl attribute = null; if (attrDecl.getAttributeNode(SchemaSymbols.ATT_REF) != null) { if (refAtt != null) { attribute = (XSAttributeDecl)fSchemaHandler.getGlobalDecl(schemaDoc, XSDHandler.ATTRIBUTE_TYPE, refAtt, attrDecl); Element child = DOMUtil.getFirstChildElement(attrDecl); if (child != null && DOMUtil.getLocalName(child).equals(SchemaSymbols.ELT_ANNOTATION)) { // REVISIT: put this somewhere traverseAnnotationDecl(child, attrValues, false, schemaDoc); child = DOMUtil.getNextSiblingElement(child); } if (child != null) { reportSchemaError("src-attribute.3.2", new Object[]{refAtt.rawname}, child); } // for error reporting nameAtt = refAtt.localpart; } else { attribute = null; } } else { attribute = traverseNamedAttr(attrDecl, attrValues, schemaDoc, grammar, false, enclosingCT); } // get 'value constraint' short consType = XSConstants.VC_NONE; if (defaultAtt != null) { consType = XSConstants.VC_DEFAULT; } else if (fixedAtt != null) { consType = XSConstants.VC_FIXED; defaultAtt = fixedAtt; fixedAtt = null; } XSAttributeUseImpl attrUse = null; if (attribute != null) { if (fSchemaHandler.fDeclPool !=null) { attrUse = fSchemaHandler.fDeclPool.getAttributeUse(); } else { attrUse = new XSAttributeUseImpl(); } attrUse.fAttrDecl = attribute; attrUse.fUse = useAtt.shortValue(); attrUse.fConstraintType = consType; if (defaultAtt != null) { attrUse.fDefault = new ValidatedInfo(); attrUse.fDefault.normalizedValue = defaultAtt; } } <MASK>fAttrChecker.returnAttrArray(attrValues, schemaDoc);</MASK> //src-attribute // 1 default and fixed must not both be present. if (defaultAtt != null && fixedAtt != null) { reportSchemaError("src-attribute.1", new Object[]{nameAtt}, attrDecl); } // 2 If default and use are both present, use must have the actual value optional. if (consType == XSConstants.VC_DEFAULT && useAtt != null && useAtt.intValue() != SchemaSymbols.USE_OPTIONAL) { reportSchemaError("src-attribute.2", new Object[]{nameAtt}, attrDecl); } // a-props-correct if (defaultAtt != null && attrUse != null) { // 2 if there is a {value constraint}, the canonical lexical representation of its value must be valid with respect to the {type definition} as defined in String Valid (3.14.4). fValidationState.setNamespaceSupport(schemaDoc.fNamespaceSupport); try { checkDefaultValid(attrUse); } catch (InvalidDatatypeValueException ide) { reportSchemaError (ide.getKey(), ide.getArgs(), attrDecl); reportSchemaError ("a-props-correct.2", new Object[]{nameAtt, defaultAtt}, attrDecl); } // 3 If the {type definition} is or is derived from ID then there must not be a {value constraint}. if (((XSSimpleType)attribute.getTypeDefinition()).isIDType() ) { reportSchemaError ("a-props-correct.3", new Object[]{nameAtt}, attrDecl); } // check 3.5.6 constraint // Attribute Use Correct // 2 If the {attribute declaration} has a fixed {value constraint}, then if the attribute use itself has a {value constraint}, it must also be fixed and its value must match that of the {attribute declaration}'s {value constraint}. if (attrUse.fAttrDecl.getConstraintType() == XSConstants.VC_FIXED && attrUse.fConstraintType != XSConstants.VC_NONE) { if (attrUse.fConstraintType != XSConstants.VC_FIXED || !attrUse.fAttrDecl.getValInfo().actualValue.equals(attrUse.fDefault.actualValue)) { reportSchemaError ("au-props-correct.2", new Object[]{nameAtt, attrUse.fAttrDecl.getValInfo().stringValue()}, attrDecl); } } } return attrUse; }"