type
stringclasses 1
value | dataset
stringclasses 1
value | input
stringlengths 75
160k
| instruction
stringlengths 117
171
| output
stringlengths 88
168k
|
---|---|---|---|---|
Inversion-Mutation | megadiff | "public void onClick(View v) {
switch(v.getId()){
case R.id.searchHallButton:
startActivity = new Intent("android.intent.action.GOOGLEMAPSEARCHLOCATION");
break;
case R.id.microwaveButton:
startActivity = new Intent("android.intent.action.CAMPUSMENUACTIVITY");
startActivity.putExtra("Show locations", MICROWAVEBUTTON);;
break;
case R.id.findRestaurantsButton:
startActivity = new Intent("android.intent.action.CAMPUSMENUACTIVITY");
startActivity.putExtra("Show locations", RESTAURANTBUTTON);
break;
case R.id.atmButton:
startActivity = new Intent("android.intent.action.CAMPUSMENUACTIVITY");
startActivity.putExtra("Show locations", ATMBUTTON);
break;
case R.id.groupRoomButton:
//Start the group room activity
startActivity = new Intent("android.intent.action.GROUPROOM");
break;
case R.id.checkinButton:
if(gotInternetConnection()){
startActivity = new Intent("android.intent.action.CHECKINACTIVITY");
}else{
Context context = getApplicationContext();
Toast.makeText(context, "Internet connection needed for this option", Toast.LENGTH_LONG).show();
okToStartActivity = false;
}
break;
case R.id.checkbusButton:
if(gotInternetConnection()){
startActivity = new Intent("android.intent.action.CHECKBUSACTIVITY");
}
else
{
okToStartActivity = false;
Context context = getApplicationContext();
Toast.makeText(context, "Internet connection needed for this option", Toast.LENGTH_LONG).show();
}
break;
}
if(okToStartActivity){
setActivityString(startActivity.getAction());
startActivity(startActivity);
}
okToStartActivity = true;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onClick" | "public void onClick(View v) {
switch(v.getId()){
case R.id.searchHallButton:
startActivity = new Intent("android.intent.action.GOOGLEMAPSEARCHLOCATION");
break;
case R.id.microwaveButton:
startActivity = new Intent("android.intent.action.CAMPUSMENUACTIVITY");
startActivity.putExtra("Show locations", MICROWAVEBUTTON);;
break;
case R.id.findRestaurantsButton:
startActivity = new Intent("android.intent.action.CAMPUSMENUACTIVITY");
startActivity.putExtra("Show locations", RESTAURANTBUTTON);
break;
case R.id.atmButton:
startActivity = new Intent("android.intent.action.CAMPUSMENUACTIVITY");
startActivity.putExtra("Show locations", ATMBUTTON);
break;
case R.id.groupRoomButton:
//Start the group room activity
startActivity = new Intent("android.intent.action.GROUPROOM");
break;
case R.id.checkinButton:
if(gotInternetConnection()){
startActivity = new Intent("android.intent.action.CHECKINACTIVITY");
}else{
Context context = getApplicationContext();
Toast.makeText(context, "Internet connection needed for this option", Toast.LENGTH_LONG).show();
okToStartActivity = false;
}
break;
case R.id.checkbusButton:
if(gotInternetConnection()){
startActivity = new Intent("android.intent.action.CHECKBUSACTIVITY");
}
else
{
okToStartActivity = false;
Context context = getApplicationContext();
Toast.makeText(context, "Internet connection needed for this option", Toast.LENGTH_LONG).show();
}
break;
}
if(okToStartActivity){
setActivityString(startActivity.getAction());
startActivity(startActivity);
<MASK>okToStartActivity = true;</MASK>
}
}" |
Inversion-Mutation | megadiff | "public boolean isAccessible() {
JSch jsch = new JSch();
try {
jsch.addIdentity(Configuration.get("AMAZON_SSH_IDENTITY"));
jsch.setKnownHosts(Configuration.get("SSH_KNOWN_HOSTS"));
} catch (JSchException e) {
e.printStackTrace();
}
Session session;
try {
session = jsch.getSession("ubuntu", hostname);
session.setConfig("StrictHostKeyChecking", "no");
session.connect(5000);
} catch (JSchException e) {
return false;
}
return true;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "isAccessible" | "public boolean isAccessible() {
JSch jsch = new JSch();
try {
jsch.addIdentity(Configuration.get("AMAZON_SSH_IDENTITY"));
jsch.setKnownHosts(Configuration.get("SSH_KNOWN_HOSTS"));
} catch (JSchException e) {
e.printStackTrace();
}
Session session;
try {
session = jsch.getSession("ubuntu", hostname);
session.connect(5000);
} catch (JSchException e) {
return false;
}
<MASK>session.setConfig("StrictHostKeyChecking", "no");</MASK>
return true;
}" |
Inversion-Mutation | megadiff | "@Override
protected void onPause() {
mDbFrontendProvider.get().closeDatabase();
super.onPause();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onPause" | "@Override
protected void onPause() {
<MASK>super.onPause();</MASK>
mDbFrontendProvider.get().closeDatabase();
}" |
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 void initialize(Concept concept, ConceptName conceptName, Locale locale) {
if (concept != null) {
conceptId = concept.getConceptId();
ConceptName conceptShortName = concept.getShortNameInLocale(locale);
name = shortName = description = "";
if (conceptName != null) {
conceptNameId = conceptName.getConceptNameId();
name = WebUtil.escapeHTML(conceptName.getName());
// if the name hit is not the preferred one, put the preferred one here
if (!conceptName.isPreferred()) {
ConceptName preferredNameObj = concept.getPreferredName(locale);
preferredName = preferredNameObj.getName();
}
}
if (conceptShortName != null) {
shortName = WebUtil.escapeHTML(conceptShortName.getName());
}
ConceptDescription conceptDescription = concept.getDescription(locale, false);
if (conceptDescription != null) {
description = WebUtil.escapeHTML(conceptDescription.getDescription());
}
retired = concept.isRetired();
hl7Abbreviation = concept.getDatatype().getHl7Abbreviation();
className = concept.getConceptClass().getName();
isSet = concept.isSet();
isNumeric = concept.isNumeric();
if (isNumeric) {
// TODO: There's probably a better way to do this, but just doing "(ConceptNumeric) concept" throws "java.lang.ClassCastException: org.openmrs.Concept$$EnhancerByCGLIB$$85e62ac7"
ConceptNumeric num = Context.getConceptService().getConceptNumeric(concept.getConceptId());
hiAbsolute = num.getHiAbsolute();
hiCritical = num.getHiCritical();
hiNormal = num.getHiNormal();
lowAbsolute = num.getLowAbsolute();
lowCritical = num.getLowCritical();
lowNormal = num.getLowNormal();
units = num.getUnits();
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "initialize" | "private void initialize(Concept concept, ConceptName conceptName, Locale locale) {
if (concept != null) {
conceptId = concept.getConceptId();
<MASK>conceptNameId = conceptName.getConceptNameId();</MASK>
ConceptName conceptShortName = concept.getShortNameInLocale(locale);
name = shortName = description = "";
if (conceptName != null) {
name = WebUtil.escapeHTML(conceptName.getName());
// if the name hit is not the preferred one, put the preferred one here
if (!conceptName.isPreferred()) {
ConceptName preferredNameObj = concept.getPreferredName(locale);
preferredName = preferredNameObj.getName();
}
}
if (conceptShortName != null) {
shortName = WebUtil.escapeHTML(conceptShortName.getName());
}
ConceptDescription conceptDescription = concept.getDescription(locale, false);
if (conceptDescription != null) {
description = WebUtil.escapeHTML(conceptDescription.getDescription());
}
retired = concept.isRetired();
hl7Abbreviation = concept.getDatatype().getHl7Abbreviation();
className = concept.getConceptClass().getName();
isSet = concept.isSet();
isNumeric = concept.isNumeric();
if (isNumeric) {
// TODO: There's probably a better way to do this, but just doing "(ConceptNumeric) concept" throws "java.lang.ClassCastException: org.openmrs.Concept$$EnhancerByCGLIB$$85e62ac7"
ConceptNumeric num = Context.getConceptService().getConceptNumeric(concept.getConceptId());
hiAbsolute = num.getHiAbsolute();
hiCritical = num.getHiCritical();
hiNormal = num.getHiNormal();
lowAbsolute = num.getLowAbsolute();
lowCritical = num.getLowCritical();
lowNormal = num.getLowNormal();
units = num.getUnits();
}
}
}" |
Inversion-Mutation | megadiff | "protected void removeScoping(KernelControllerContext context) throws Throwable
{
KernelController controller = (KernelController)context.getController();
KernelMetaDataRepository repository = controller.getKernel().getMetaDataRepository();
ScopeKey scopeKey = context.getInstallScope();
if (scopeKey != null)
{
// find scoped controller
MutableMetaDataRepository mmdr = repository.getMetaDataRepository();
MetaDataRetrieval mdr = mmdr.getMetaDataRetrieval(scopeKey);
if (mdr == null)
{
throw new IllegalArgumentException("Expecting MetaDataRetrieval instance in scope: " + scopeKey);
}
MetaDataItem<ScopedKernelController> controllerItem = mdr.retrieveMetaData(ScopedKernelController.class);
if (controllerItem == null)
{
throw new IllegalArgumentException("Expecting ScopedKernelController instance in scope:" + scopeKey);
}
ScopedKernelController scopedController = controllerItem.getValue();
scopedController.removeControllerContext(context);
context.setController(scopedController.getUnderlyingController());
if (scopedController.isActive() == false)
{
try
{
((MutableMetaData)mdr).removeMetaData(ScopedKernelController.class);
}
finally
{
scopedController.release();
}
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "removeScoping" | "protected void removeScoping(KernelControllerContext context) throws Throwable
{
KernelController controller = (KernelController)context.getController();
KernelMetaDataRepository repository = controller.getKernel().getMetaDataRepository();
ScopeKey scopeKey = context.getInstallScope();
if (scopeKey != null)
{
// find scoped controller
MutableMetaDataRepository mmdr = repository.getMetaDataRepository();
MetaDataRetrieval mdr = mmdr.getMetaDataRetrieval(scopeKey);
if (mdr == null)
{
throw new IllegalArgumentException("Expecting MetaDataRetrieval instance in scope: " + scopeKey);
}
MetaDataItem<ScopedKernelController> controllerItem = mdr.retrieveMetaData(ScopedKernelController.class);
if (controllerItem == null)
{
throw new IllegalArgumentException("Expecting ScopedKernelController instance in scope:" + scopeKey);
}
ScopedKernelController scopedController = controllerItem.getValue();
scopedController.removeControllerContext(context);
if (scopedController.isActive() == false)
{
try
{
((MutableMetaData)mdr).removeMetaData(ScopedKernelController.class);
<MASK>context.setController(scopedController.getUnderlyingController());</MASK>
}
finally
{
scopedController.release();
}
}
}
}" |
Inversion-Mutation | megadiff | "private void addSelectionHandlerToTabPanel(boolean left)
{
setGenericObjects(left);
final TabPanel tabPanelFinal = tabPanel;
final ArrayList<AbstractDocument> docListFinal = docList;
final ArrayList<TextArea> contentsListFinal = contentsList;
final ArrayList<TextBox> titleListFinal = titleList;
final Button lockButtonFinal = lockButton;
final Button removeTabButtonFinal = removeTabButton;
final Button refreshFinal = refresh;
final HorizontalPanel hPanelFinal = hPanel;
final Button saveDocButtonFinal = saveDocButton;
tabPanelFinal.addSelectionHandler(new SelectionHandler<Integer>() {
public void onSelection(SelectionEvent<Integer> event) {
int ind = tabPanelFinal.getTabBar().getSelectedTab();
hPanelFinal.clear();
if (docListFinal.get(ind) instanceof LockedDocument) {
// enable and add the save button
enableButton(saveDocButtonFinal);
hPanelFinal.add(saveDocButtonFinal);
// Enable the fields since have the lock
titleListFinal.get(ind).setEnabled(true);
contentsListFinal.get(ind).setEnabled(true);
// disable the refresh button
disableButton(refreshFinal);
}
else {
// enable and add the lock button
enableButton(lockButtonFinal);
hPanelFinal.add(lockButtonFinal);
// Disabling the fields since you don't have the lock
titleListFinal.get(ind).setEnabled(false);
contentsListFinal.get(ind).setEnabled(false);
// enable the refresh button
enableButton(refreshFinal);
}
// add removeTab and refresh buttons, enable removeTab
enableButton(removeTabButtonFinal);
hPanelFinal.add(refreshFinal);
hPanelFinal.add(removeTabButtonFinal);
}
});
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addSelectionHandlerToTabPanel" | "private void addSelectionHandlerToTabPanel(boolean left)
{
setGenericObjects(left);
final TabPanel tabPanelFinal = tabPanel;
final ArrayList<AbstractDocument> docListFinal = docList;
final ArrayList<TextArea> contentsListFinal = contentsList;
final ArrayList<TextBox> titleListFinal = titleList;
final Button lockButtonFinal = lockButton;
final Button removeTabButtonFinal = removeTabButton;
final Button refreshFinal = refresh;
final HorizontalPanel hPanelFinal = hPanel;
final Button saveDocButtonFinal = saveDocButton;
tabPanelFinal.addSelectionHandler(new SelectionHandler<Integer>() {
public void onSelection(SelectionEvent<Integer> event) {
int ind = tabPanelFinal.getTabBar().getSelectedTab();
hPanelFinal.clear();
if (docListFinal.get(ind) instanceof LockedDocument) {
// enable and add the save button
enableButton(saveDocButtonFinal);
hPanelFinal.add(saveDocButtonFinal);
// Enable the fields since have the lock
titleListFinal.get(ind).setEnabled(true);
contentsListFinal.get(ind).setEnabled(true);
// disable the refresh button
disableButton(refreshFinal);
}
else {
// enable and add the lock button
enableButton(lockButtonFinal);
hPanelFinal.add(lockButtonFinal);
// Disabling the fields since you don't have the lock
titleListFinal.get(ind).setEnabled(false);
contentsListFinal.get(ind).setEnabled(false);
// enable the refresh button
enableButton(refreshFinal);
}
// add removeTab and refresh buttons, enable removeTab
enableButton(removeTabButtonFinal);
<MASK>hPanelFinal.add(removeTabButtonFinal);</MASK>
hPanelFinal.add(refreshFinal);
}
});
}" |
Inversion-Mutation | megadiff | "public void onSelection(SelectionEvent<Integer> event) {
int ind = tabPanelFinal.getTabBar().getSelectedTab();
hPanelFinal.clear();
if (docListFinal.get(ind) instanceof LockedDocument) {
// enable and add the save button
enableButton(saveDocButtonFinal);
hPanelFinal.add(saveDocButtonFinal);
// Enable the fields since have the lock
titleListFinal.get(ind).setEnabled(true);
contentsListFinal.get(ind).setEnabled(true);
// disable the refresh button
disableButton(refreshFinal);
}
else {
// enable and add the lock button
enableButton(lockButtonFinal);
hPanelFinal.add(lockButtonFinal);
// Disabling the fields since you don't have the lock
titleListFinal.get(ind).setEnabled(false);
contentsListFinal.get(ind).setEnabled(false);
// enable the refresh button
enableButton(refreshFinal);
}
// add removeTab and refresh buttons, enable removeTab
enableButton(removeTabButtonFinal);
hPanelFinal.add(refreshFinal);
hPanelFinal.add(removeTabButtonFinal);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onSelection" | "public void onSelection(SelectionEvent<Integer> event) {
int ind = tabPanelFinal.getTabBar().getSelectedTab();
hPanelFinal.clear();
if (docListFinal.get(ind) instanceof LockedDocument) {
// enable and add the save button
enableButton(saveDocButtonFinal);
hPanelFinal.add(saveDocButtonFinal);
// Enable the fields since have the lock
titleListFinal.get(ind).setEnabled(true);
contentsListFinal.get(ind).setEnabled(true);
// disable the refresh button
disableButton(refreshFinal);
}
else {
// enable and add the lock button
enableButton(lockButtonFinal);
hPanelFinal.add(lockButtonFinal);
// Disabling the fields since you don't have the lock
titleListFinal.get(ind).setEnabled(false);
contentsListFinal.get(ind).setEnabled(false);
// enable the refresh button
enableButton(refreshFinal);
}
// add removeTab and refresh buttons, enable removeTab
enableButton(removeTabButtonFinal);
<MASK>hPanelFinal.add(removeTabButtonFinal);</MASK>
hPanelFinal.add(refreshFinal);
}" |
Inversion-Mutation | megadiff | "@Override
public boolean dispatchKeyEvent(KeyEvent event) {
// Do this on key down to handle a few of the system keys.
boolean up = event.getAction() == KeyEvent.ACTION_UP;
switch (event.getKeyCode()) {
// Volume keys and camera keys dismiss the alarm
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_VOLUME_DOWN:
case KeyEvent.KEYCODE_CAMERA:
case KeyEvent.KEYCODE_FOCUS:
if (up) {
switch (mVolumeBehavior) {
case 1:
snooze();
break;
case 2:
dismiss(false);
break;
default:
break;
}
}
return true;
default:
break;
}
return super.dispatchKeyEvent(event);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "dispatchKeyEvent" | "@Override
public boolean dispatchKeyEvent(KeyEvent event) {
// Do this on key down to handle a few of the system keys.
boolean up = event.getAction() == KeyEvent.ACTION_UP;
switch (event.getKeyCode()) {
// Volume keys and camera keys dismiss the alarm
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_VOLUME_DOWN:
case KeyEvent.KEYCODE_CAMERA:
case KeyEvent.KEYCODE_FOCUS:
if (up) {
switch (mVolumeBehavior) {
case 1:
snooze();
break;
case 2:
dismiss(false);
break;
default:
break;
}
}
return true;
default:
break;
<MASK>return super.dispatchKeyEvent(event);</MASK>
}
}" |
Inversion-Mutation | megadiff | "@Override
protected boolean init(CommandSender sender, String[] args) {
if (outputs.length==0) {
error(sender, "Expecting at least 1 output pin.");
return false;
}
if (args.length>0) {
try {
dataPin = (outputs.length==1?0:1);
this.initWireless(sender, args[0]);
return true;
} catch (IllegalArgumentException ie) {
error(sender, ie.getMessage());
return false;
}
} else {
error(sender, "Channel name is missing.");
return false;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "init" | "@Override
protected boolean init(CommandSender sender, String[] args) {
if (outputs.length==0) {
error(sender, "Expecting at least 1 output pin.");
return false;
}
if (args.length>0) {
try {
this.initWireless(sender, args[0]);
<MASK>dataPin = (outputs.length==1?0:1);</MASK>
return true;
} catch (IllegalArgumentException ie) {
error(sender, ie.getMessage());
return false;
}
} else {
error(sender, "Channel name is missing.");
return false;
}
}" |
Inversion-Mutation | megadiff | "@Override
public final void onGetRequest(final HttpServletRequest request, final HttpServletResponse response, final ServletAdapter[] servletAdapters) throws Exception {
String pathInfo = request.getPathInfo();
if (!StringUtility.hasText(pathInfo)) {
// ensure proper resource loading if trailing slash is missing
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
final String baseUrl = JaxWsHelper.getBaseAddress(request, false);
IPath contextPath = new Path(request.getRequestURI()).addTrailingSeparator().makeAbsolute();
if (contextPath.isUNC()) {
contextPath = contextPath.makeUNC(false);
}
final URI redirectUri = new UriBuilder(baseUrl).path(contextPath.toString()).createURI();
response.setHeader("Location", redirectUri.toString());
return;
}
if (pathInfo == null || pathInfo.endsWith("/") || pathInfo.equals("")) {
pathInfo = "/" + HTML_STATUS_PAGE_TEMPLATE; // status page
}
byte[] content = new byte[0];
if (new Path(pathInfo).lastSegment().equals(HTML_STATUS_PAGE_TEMPLATE)) {
// status page
String html = createHtmlStatusPage(request.getContextPath(), servletAdapters);
if (html != null) {
content = html.getBytes("UTF-8");
}
}
else {
// other resource (e.g. image file)
URL url = resolveResourceURL(pathInfo);
if (url != null) {
content = IOUtility.getContent(url.openStream(), true);
}
else {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
}
String contentType = FileUtility.getContentTypeForExtension(new Path(pathInfo).getFileExtension());
if (contentType == null) {
contentType = "application/unknown";
}
response.setContentType(contentType);
response.setContentLength(content.length);
response.setStatus(HttpServletResponse.SC_OK);
response.getOutputStream().write(content);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onGetRequest" | "@Override
public final void onGetRequest(final HttpServletRequest request, final HttpServletResponse response, final ServletAdapter[] servletAdapters) throws Exception {
String pathInfo = request.getPathInfo();
if (!StringUtility.hasText(pathInfo)) {
// ensure proper resource loading if trailing slash is missing
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
final String baseUrl = JaxWsHelper.getBaseAddress(request, false);
IPath contextPath = new Path(request.getRequestURI()).addTrailingSeparator().makeAbsolute();
if (contextPath.isUNC()) {
contextPath = contextPath.makeUNC(false);
}
final URI redirectUri = new UriBuilder(baseUrl).path(contextPath.toString()).createURI();
response.setHeader("Location", redirectUri.toString());
return;
}
if (pathInfo == null || pathInfo.endsWith("/") || pathInfo.equals("")) {
pathInfo = "/" + HTML_STATUS_PAGE_TEMPLATE; // status page
}
byte[] content = new byte[0];
if (new Path(pathInfo).lastSegment().equals(HTML_STATUS_PAGE_TEMPLATE)) {
// status page
String html = createHtmlStatusPage(request.getContextPath(), servletAdapters);
if (html != null) {
content = html.getBytes("UTF-8");
}
}
else {
// other resource (e.g. image file)
URL url = resolveResourceURL(pathInfo);
if (url != null) {
content = IOUtility.getContent(url.openStream(), true);
}
else {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
}
String contentType = FileUtility.getContentTypeForExtension(new Path(pathInfo).getFileExtension());
if (contentType == null) {
contentType = "application/unknown";
}
response.setContentType(contentType);
response.setContentLength(content.length);
<MASK>response.getOutputStream().write(content);</MASK>
response.setStatus(HttpServletResponse.SC_OK);
}" |
Inversion-Mutation | megadiff | "@Override
public void start() {
LOGGER.info("Starting HTTP server");
InetSocketAddress bindAddress = new InetSocketAddress(configuration.getHttpServerPort());
// Configure the server.
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup) //
.channel(NioServerSocketChannel.class) //
.childOption(ChannelOption.ALLOCATOR, UnpooledByteBufAllocator.DEFAULT) //
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(final SocketChannel channel) {
ChannelPipeline pipeline = channel.pipeline();
pipeline.addLast("decoder", new HttpRequestDecoder()) //
.addLast("aggregator", new HttpObjectAggregator(MAX_CONTENT_LENGTH))//
.addLast("encoder", new HttpResponseEncoder())//
.addLast("chunkedWriter", new ChunkedWriteHandler())//
// Add HTTP request handler
.addLast("httpChannelHandler", injector.getInstance(ChannelInboundHandler.class));
}
});
// Bind and start server to accept incoming connections.
try {
bootstrap.bind(bindAddress).sync();
} catch (InterruptedException e) {
LOGGER.error(e.getMessage(), e);
}
LOGGER.info("HTTP server bound on " + bindAddress);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "start" | "@Override
public void start() {
LOGGER.info("Starting HTTP server");
InetSocketAddress bindAddress = new InetSocketAddress(configuration.getHttpServerPort());
// Configure the server.
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup) //
.channel(NioServerSocketChannel.class) //
.childOption(ChannelOption.ALLOCATOR, UnpooledByteBufAllocator.DEFAULT) //
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(final SocketChannel channel) {
ChannelPipeline pipeline = channel.pipeline();
pipeline.addLast("decoder", new HttpRequestDecoder()) //
.addLast("aggregator", new HttpObjectAggregator(MAX_CONTENT_LENGTH))//
<MASK>.addLast("chunkedWriter", new ChunkedWriteHandler())//</MASK>
.addLast("encoder", new HttpResponseEncoder())//
// Add HTTP request handler
.addLast("httpChannelHandler", injector.getInstance(ChannelInboundHandler.class));
}
});
// Bind and start server to accept incoming connections.
try {
bootstrap.bind(bindAddress).sync();
} catch (InterruptedException e) {
LOGGER.error(e.getMessage(), e);
}
LOGGER.info("HTTP server bound on " + bindAddress);
}" |
Inversion-Mutation | megadiff | "@Override
protected void initChannel(final SocketChannel channel) {
ChannelPipeline pipeline = channel.pipeline();
pipeline.addLast("decoder", new HttpRequestDecoder()) //
.addLast("aggregator", new HttpObjectAggregator(MAX_CONTENT_LENGTH))//
.addLast("encoder", new HttpResponseEncoder())//
.addLast("chunkedWriter", new ChunkedWriteHandler())//
// Add HTTP request handler
.addLast("httpChannelHandler", injector.getInstance(ChannelInboundHandler.class));
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "initChannel" | "@Override
protected void initChannel(final SocketChannel channel) {
ChannelPipeline pipeline = channel.pipeline();
pipeline.addLast("decoder", new HttpRequestDecoder()) //
.addLast("aggregator", new HttpObjectAggregator(MAX_CONTENT_LENGTH))//
<MASK>.addLast("chunkedWriter", new ChunkedWriteHandler())//</MASK>
.addLast("encoder", new HttpResponseEncoder())//
// Add HTTP request handler
.addLast("httpChannelHandler", injector.getInstance(ChannelInboundHandler.class));
}" |
Inversion-Mutation | megadiff | "void doShutdown() {
if (active.compareAndSet(true, false)) {
logger.log(Level.INFO, "HazelcastClient[" + this.id + "] is shutting down.");
out.shutdown();
in.shutdown();
connectionManager.shutdown();
listenerManager.shutdown();
ClientThreadContext.shutdown();
lsClients.remove(HazelcastClient.this);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doShutdown" | "void doShutdown() {
if (active.compareAndSet(true, false)) {
logger.log(Level.INFO, "HazelcastClient[" + this.id + "] is shutting down.");
<MASK>connectionManager.shutdown();</MASK>
out.shutdown();
in.shutdown();
listenerManager.shutdown();
ClientThreadContext.shutdown();
lsClients.remove(HazelcastClient.this);
}
}" |
Inversion-Mutation | megadiff | "public void displayNews(ImageCache cacheMap, String news,
JProgressBar progressBar) {
textPane.getDocument().putProperty("imageCache", cacheMap);
textPane.setText(news.toString());
textPane.setCaretPosition(0);
newsScroll.setVisible(true);
progressBar.getParent().setVisible(false);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "displayNews" | "public void displayNews(ImageCache cacheMap, String news,
JProgressBar progressBar) {
textPane.getDocument().putProperty("imageCache", cacheMap);
textPane.setText(news.toString());
textPane.setCaretPosition(0);
<MASK>progressBar.getParent().setVisible(false);</MASK>
newsScroll.setVisible(true);
}" |
Inversion-Mutation | megadiff | "private void bindMailboxItem(View view, Context context, Cursor cursor, boolean isLastChild)
{
// Reset the view (in case it was recycled) and prepare for binding
AccountFolderListItem itemView = (AccountFolderListItem) view;
itemView.bindViewInit(this, false);
// Invisible (not "gone") to maintain spacing
view.findViewById(R.id.chip).setVisibility(View.INVISIBLE);
String text = cursor.getString(MAILBOX_DISPLAY_NAME);
if (text != null) {
TextView nameView = (TextView) view.findViewById(R.id.name);
nameView.setText(text);
}
// TODO get/track live folder status
text = null;
TextView statusView = (TextView) view.findViewById(R.id.status);
if (text != null) {
statusView.setText(text);
statusView.setVisibility(View.VISIBLE);
} else {
statusView.setVisibility(View.GONE);
}
int count = -1;
text = cursor.getString(MAILBOX_UNREAD_COUNT);
if (text != null) {
count = Integer.valueOf(text);
}
TextView unreadCountView = (TextView) view.findViewById(R.id.new_message_count);
TextView allCountView = (TextView) view.findViewById(R.id.all_message_count);
int id = cursor.getInt(MAILBOX_COLUMN_ID);
// If the unread count is zero, not to show countView.
if (count > 0) {
if (id == Mailbox.QUERY_ALL_FAVORITES
|| id == Mailbox.QUERY_ALL_DRAFTS
|| id == Mailbox.QUERY_ALL_OUTBOX) {
allCountView.setVisibility(View.GONE);
unreadCountView.setVisibility(View.VISIBLE);
unreadCountView.setText(text);
} else {
unreadCountView.setVisibility(View.GONE);
allCountView.setVisibility(View.VISIBLE);
allCountView.setText(text);
}
} else {
allCountView.setVisibility(View.GONE);
unreadCountView.setVisibility(View.GONE);
}
view.findViewById(R.id.folder_button).setVisibility(View.GONE);
view.findViewById(R.id.folder_separator).setVisibility(View.GONE);
view.findViewById(R.id.default_sender).setVisibility(View.GONE);
view.findViewById(R.id.folder_icon).setVisibility(View.VISIBLE);
((ImageView)view.findViewById(R.id.folder_icon)).setImageDrawable(
Utility.FolderProperties.getInstance(context).getSummaryMailboxIconIds(id));
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "bindMailboxItem" | "private void bindMailboxItem(View view, Context context, Cursor cursor, boolean isLastChild)
{
// Reset the view (in case it was recycled) and prepare for binding
AccountFolderListItem itemView = (AccountFolderListItem) view;
itemView.bindViewInit(this, false);
// Invisible (not "gone") to maintain spacing
view.findViewById(R.id.chip).setVisibility(View.INVISIBLE);
String text = cursor.getString(MAILBOX_DISPLAY_NAME);
if (text != null) {
TextView nameView = (TextView) view.findViewById(R.id.name);
nameView.setText(text);
}
// TODO get/track live folder status
text = null;
TextView statusView = (TextView) view.findViewById(R.id.status);
if (text != null) {
statusView.setText(text);
statusView.setVisibility(View.VISIBLE);
} else {
statusView.setVisibility(View.GONE);
}
int count = -1;
text = cursor.getString(MAILBOX_UNREAD_COUNT);
if (text != null) {
count = Integer.valueOf(text);
}
TextView unreadCountView = (TextView) view.findViewById(R.id.new_message_count);
TextView allCountView = (TextView) view.findViewById(R.id.all_message_count);
// If the unread count is zero, not to show countView.
if (count > 0) {
<MASK>int id = cursor.getInt(MAILBOX_COLUMN_ID);</MASK>
if (id == Mailbox.QUERY_ALL_FAVORITES
|| id == Mailbox.QUERY_ALL_DRAFTS
|| id == Mailbox.QUERY_ALL_OUTBOX) {
allCountView.setVisibility(View.GONE);
unreadCountView.setVisibility(View.VISIBLE);
unreadCountView.setText(text);
} else {
unreadCountView.setVisibility(View.GONE);
allCountView.setVisibility(View.VISIBLE);
allCountView.setText(text);
}
} else {
allCountView.setVisibility(View.GONE);
unreadCountView.setVisibility(View.GONE);
}
view.findViewById(R.id.folder_button).setVisibility(View.GONE);
view.findViewById(R.id.folder_separator).setVisibility(View.GONE);
view.findViewById(R.id.default_sender).setVisibility(View.GONE);
view.findViewById(R.id.folder_icon).setVisibility(View.VISIBLE);
((ImageView)view.findViewById(R.id.folder_icon)).setImageDrawable(
Utility.FolderProperties.getInstance(context).getSummaryMailboxIconIds(id));
}" |
Inversion-Mutation | megadiff | "public static void main(String[] args) {
objectSet.add(new DomainObject("Helga"));
objectSet.add(new DomainObject("Walter"));
objectSet.add(new DomainObject("Hannah"));
objectSet.add(new DomainObject("Paul"));
objectSet.add(new DomainObject("Claudia"));
for (DomainObject domainObject : objectSet) {
LOGGER.debug(domainObject.id);
}
Set<DomainObject> objectSet = new HashSet<DomainObject>();
objectSet.add(new DomainObject("Helga", ""));
objectSet.add(new DomainObject("Walter", ""));
objectSet.add(new DomainObject("Hannah", ""));
objectSet.add(new DomainObject("Paul", ""));
objectSet.add(new DomainObject("Claudia", ""));
for (DomainObject domainObject : objectSet) {
LOGGER.debug(domainObject.id);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "main" | "public static void main(String[] args) {
<MASK>Set<DomainObject> objectSet = new HashSet<DomainObject>();</MASK>
objectSet.add(new DomainObject("Helga"));
objectSet.add(new DomainObject("Walter"));
objectSet.add(new DomainObject("Hannah"));
objectSet.add(new DomainObject("Paul"));
objectSet.add(new DomainObject("Claudia"));
for (DomainObject domainObject : objectSet) {
LOGGER.debug(domainObject.id);
}
objectSet.add(new DomainObject("Helga", ""));
objectSet.add(new DomainObject("Walter", ""));
objectSet.add(new DomainObject("Hannah", ""));
objectSet.add(new DomainObject("Paul", ""));
objectSet.add(new DomainObject("Claudia", ""));
for (DomainObject domainObject : objectSet) {
LOGGER.debug(domainObject.id);
}
}" |
Inversion-Mutation | megadiff | "@Override
public void testFailure(Failure failure) throws Exception {
if (current == null) {
// The test probably failed before it could start, ie in @BeforeClass
current = new TestResult();
results.add(current); // must add it here since testFinished() never was called.
current.name = "Before any test started, maybe in @BeforeClass?";
current.time = System.currentTimeMillis();
}
if (failure.getException() instanceof AssertionError) {
current.error = "Failure, " + failure.getMessage();
} else {
current.error = "A " + failure.getException().getClass().getName() + " has been caught, " + failure.getMessage();
}
current.trace = failure.getTrace();
for (StackTraceElement stackTraceElement : failure.getException().getStackTrace()) {
if (stackTraceElement.getClassName().equals(className)) {
current.sourceInfos = "In " + Play.classes.getApplicationClass(className).javaFile.relativePath() + ", line " + stackTraceElement.getLineNumber();
current.sourceCode = Play.classes.getApplicationClass(className).javaSource.split("\n")[stackTraceElement.getLineNumber() - 1];
current.sourceFile = Play.classes.getApplicationClass(className).javaFile.relativePath();
current.sourceLine = stackTraceElement.getLineNumber();
}
}
current.passed = false;
results.passed = false;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "testFailure" | "@Override
public void testFailure(Failure failure) throws Exception {
if (current == null) {
// The test probably failed before it could start, ie in @BeforeClass
current = new TestResult();
results.add(current); // must add it here since testFinished() never was called.
current.name = "Before any test started, maybe in @BeforeClass?";
current.time = System.currentTimeMillis();
}
if (failure.getException() instanceof AssertionError) {
current.error = "Failure, " + failure.getMessage();
} else {
current.error = "A " + failure.getException().getClass().getName() + " has been caught, " + failure.getMessage();
<MASK>current.trace = failure.getTrace();</MASK>
}
for (StackTraceElement stackTraceElement : failure.getException().getStackTrace()) {
if (stackTraceElement.getClassName().equals(className)) {
current.sourceInfos = "In " + Play.classes.getApplicationClass(className).javaFile.relativePath() + ", line " + stackTraceElement.getLineNumber();
current.sourceCode = Play.classes.getApplicationClass(className).javaSource.split("\n")[stackTraceElement.getLineNumber() - 1];
current.sourceFile = Play.classes.getApplicationClass(className).javaFile.relativePath();
current.sourceLine = stackTraceElement.getLineNumber();
}
}
current.passed = false;
results.passed = false;
}" |
Inversion-Mutation | megadiff | "public final SrmLsResponse getSrmLsResponse()
throws SRMException ,java.sql.SQLException {
SrmLsResponse response = new SrmLsResponse();
response.setReturnStatus(getTReturnStatus());
if (!response.getReturnStatus().getStatusCode().isProcessing()) {
ArrayOfTMetaDataPathDetail details =
new ArrayOfTMetaDataPathDetail();
details.setPathDetailArray(getPathDetailArray());
response.setDetails(details);
} else {
response.setDetails(null);
response.setRequestToken(getTRequestToken());
}
return response;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getSrmLsResponse" | "public final SrmLsResponse getSrmLsResponse()
throws SRMException ,java.sql.SQLException {
SrmLsResponse response = new SrmLsResponse();
response.setReturnStatus(getTReturnStatus());
<MASK>response.setRequestToken(getTRequestToken());</MASK>
if (!response.getReturnStatus().getStatusCode().isProcessing()) {
ArrayOfTMetaDataPathDetail details =
new ArrayOfTMetaDataPathDetail();
details.setPathDetailArray(getPathDetailArray());
response.setDetails(details);
} else {
response.setDetails(null);
}
return response;
}" |
Inversion-Mutation | megadiff | "private void recalculateRowStatusBitSetsOnDataUpdate() {
setOldBitSetAndRowMap();
if ( isSearchTermSet() ) {
doSearchAndRecalculate(false);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "recalculateRowStatusBitSetsOnDataUpdate" | "private void recalculateRowStatusBitSetsOnDataUpdate() {
if ( isSearchTermSet() ) {
<MASK>setOldBitSetAndRowMap();</MASK>
doSearchAndRecalculate(false);
}
}" |
Inversion-Mutation | megadiff | "public SWTBotToolbarCheckboxButton toggle() {
log.debug(MessageFormat.format("Clicking on {0}", this)); //$NON-NLS-1$
assertEnabled();
internalToggle();
notify(SWT.MouseEnter);
notify(SWT.MouseMove);
notify(SWT.Activate);
notify(SWT.MouseDown);
notify(SWT.MouseUp);
notify(SWT.Selection);
notify(SWT.MouseHover);
notify(SWT.MouseMove);
notify(SWT.MouseExit);
notify(SWT.Deactivate);
notify(SWT.FocusOut);
log.debug(MessageFormat.format("Clicked on {0}", this)); //$NON-NLS-1$
return this;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "toggle" | "public SWTBotToolbarCheckboxButton toggle() {
log.debug(MessageFormat.format("Clicking on {0}", this)); //$NON-NLS-1$
assertEnabled();
notify(SWT.MouseEnter);
notify(SWT.MouseMove);
notify(SWT.Activate);
notify(SWT.MouseDown);
notify(SWT.MouseUp);
notify(SWT.Selection);
notify(SWT.MouseHover);
notify(SWT.MouseMove);
notify(SWT.MouseExit);
notify(SWT.Deactivate);
notify(SWT.FocusOut);
<MASK>internalToggle();</MASK>
log.debug(MessageFormat.format("Clicked on {0}", this)); //$NON-NLS-1$
return this;
}" |
Inversion-Mutation | megadiff | "public void loadAllTextures ( Context context, TextureManager pTextureManager ) {
int curr_atlas = 0; // Счётчик атласов
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); // Установили default-путь к текстурам
try {
XmlPullParser parser = context.getResources().getXml( R.xml.atlas ); // Инициализировали парсер xml
while (parser.getEventType() != XmlPullParser.END_DOCUMENT ) {
//============================ Парсер =========================================//
//==== Случай START_TAG - атлас ====//
if ( ( parser.getEventType() == XmlPullParser.START_TAG )
&& ( parser.getName().equals("Atlas") )
&& ( parser.getDepth() == 2 ) ) { // Глубина вложенности - 2
//=== Обработка ===//
int atlas_height = 1;
int atlas_width = 1;
TextureOptions textureOptions = TextureOptions.DEFAULT;
for (int i = 0; i < parser.getAttributeCount(); i++ ) {
if( parser.getAttributeName(i).equals("width") )
atlas_width = Integer.parseInt(parser.getAttributeValue(i));
if( parser.getAttributeName(i).equals("height") ) // Вытаскиваем параметры атласа
atlas_height = Integer.parseInt( parser.getAttributeValue(i) );
if( parser.getAttributeName(i).equals("type") )
textureOptions = stringToTextureOptions(parser.getAttributeValue(i));
}
atlasList.add( new BuildableBitmapTextureAtlas( pTextureManager
, atlas_width
, atlas_height
, textureOptions ) ); // Создаём новый атлас
// XXX: ДОБАВИТЬ TEXTURE FORMAT!
//=================//
}
//==================================//
//===== Случай END_TAG - атлас =====//
if ( ( parser.getEventType() == XmlPullParser.END_TAG )
&& ( parser.getName().equals("Atlas") )
&& ( parser.getDepth() == 2 ) ) {
//=== Обработка ===//
try {
atlasList.get(curr_atlas).build( // Генерируем новый атлас с текущим номером curr_atlas
new BlackPawnTextureAtlasBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(0,1,1));
// 1 - source padding; 1 - source space
}
catch (ITextureAtlasBuilder.TextureAtlasBuilderException e) {
// XXX: Обработка исключения
}
atlasList.get(curr_atlas).load(); // Загрузка атласа в память
curr_atlas++;
//=================//
}
//==================================//
//=== Случай START_TAG - текстура ===//
if ( ( parser.getEventType() == XmlPullParser.START_TAG )
&& ( parser.getName().equals("texture") )
&& ( parser.getDepth() == 3 ) ) { // Глубина вложенности - 3
String path = "";
String tname = "";
for ( int i = 0; i < parser.getAttributeCount(); i++ ) { // Вытаскиваем параметры текстуры
if ( parser.getAttributeName(i).equals("name") ) tname = parser.getAttributeValue(i);
if ( parser.getAttributeName(i).equals("path") ) path = parser.getAttributeValue(i);
}
// Создаём новый TextureRegion и записываем его в loadedTextures
ITextureRegion textReg =
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
atlasList.get(curr_atlas)
,context
,path );
loadedTextures.add( new Texture(tname, textReg) );
}
//==================================//
parser.next();
//=============================================================================//
}
}
catch ( Throwable t ) {
// XXX: Обработка исключения
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "loadAllTextures" | "public void loadAllTextures ( Context context, TextureManager pTextureManager ) {
int curr_atlas = 0; // Счётчик атласов
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); // Установили default-путь к текстурам
try {
XmlPullParser parser = context.getResources().getXml( R.xml.atlas ); // Инициализировали парсер xml
while (parser.getEventType() != XmlPullParser.END_DOCUMENT ) {
//============================ Парсер =========================================//
//==== Случай START_TAG - атлас ====//
if ( ( parser.getEventType() == XmlPullParser.START_TAG )
&& ( parser.getName().equals("Atlas") )
&& ( parser.getDepth() == 2 ) ) { // Глубина вложенности - 2
//=== Обработка ===//
int atlas_height = 1;
int atlas_width = 1;
TextureOptions textureOptions = TextureOptions.DEFAULT;
for (int i = 0; i < parser.getAttributeCount(); i++ ) {
if( parser.getAttributeName(i).equals("width") )
atlas_width = Integer.parseInt(parser.getAttributeValue(i));
if( parser.getAttributeName(i).equals("height") ) // Вытаскиваем параметры атласа
atlas_height = Integer.parseInt( parser.getAttributeValue(i) );
if( parser.getAttributeName(i).equals("type") )
textureOptions = stringToTextureOptions(parser.getAttributeValue(i));
}
atlasList.add( new BuildableBitmapTextureAtlas( pTextureManager
, atlas_width
, atlas_height
, textureOptions ) ); // Создаём новый атлас
// XXX: ДОБАВИТЬ TEXTURE FORMAT!
<MASK>curr_atlas++;</MASK>
//=================//
}
//==================================//
//===== Случай END_TAG - атлас =====//
if ( ( parser.getEventType() == XmlPullParser.END_TAG )
&& ( parser.getName().equals("Atlas") )
&& ( parser.getDepth() == 2 ) ) {
//=== Обработка ===//
try {
atlasList.get(curr_atlas).build( // Генерируем новый атлас с текущим номером curr_atlas
new BlackPawnTextureAtlasBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(0,1,1));
// 1 - source padding; 1 - source space
}
catch (ITextureAtlasBuilder.TextureAtlasBuilderException e) {
// XXX: Обработка исключения
}
atlasList.get(curr_atlas).load(); // Загрузка атласа в память
//=================//
}
//==================================//
//=== Случай START_TAG - текстура ===//
if ( ( parser.getEventType() == XmlPullParser.START_TAG )
&& ( parser.getName().equals("texture") )
&& ( parser.getDepth() == 3 ) ) { // Глубина вложенности - 3
String path = "";
String tname = "";
for ( int i = 0; i < parser.getAttributeCount(); i++ ) { // Вытаскиваем параметры текстуры
if ( parser.getAttributeName(i).equals("name") ) tname = parser.getAttributeValue(i);
if ( parser.getAttributeName(i).equals("path") ) path = parser.getAttributeValue(i);
}
// Создаём новый TextureRegion и записываем его в loadedTextures
ITextureRegion textReg =
BitmapTextureAtlasTextureRegionFactory.createFromAsset(
atlasList.get(curr_atlas)
,context
,path );
loadedTextures.add( new Texture(tname, textReg) );
}
//==================================//
parser.next();
//=============================================================================//
}
}
catch ( Throwable t ) {
// XXX: Обработка исключения
}
}" |
Inversion-Mutation | megadiff | "public static void addNatureToProjectWithValidationSupport(IProject project, String builderId, String natureId) throws CoreException {
EclipseResourceUtil.addNatureToProject(project, natureId);
IProjectDescription desc = project.getDescription();
ICommand[] existing = desc.getBuildSpec();
boolean updated = false;
int javaBuilderIndex = -1;
ICommand javaBuilder = null;
int wstValidationBuilderIndex = -1;
ICommand wstValidationBuilder = null;
int builderIndex = -1;
ICommand builder = null;
for (int i = 0; i < existing.length; i++) {
if(JAVA_BUILDER_ID.equals(existing[i].getBuilderName())) {
javaBuilderIndex = i;
javaBuilder = existing[i];
} else if(ValidationPlugin.VALIDATION_BUILDER_ID.equals(existing[i].getBuilderName())) {
wstValidationBuilderIndex = i;
wstValidationBuilder = existing[i];
} else if(builderId.equals(existing[i].getBuilderName())) {
builderIndex = i;
builder = existing[i];
}
}
if(javaBuilderIndex==-1) {
getDefault().logError("Can't enable " + builderId + " support on the project " + project.getName() + " without Java builder."); //$NON-NLS-1$ //$NON-NLS-2$//$NON-NLS-3$
return;
}
if(wstValidationBuilderIndex!=-1 && wstValidationBuilderIndex<javaBuilderIndex) {
existing[javaBuilderIndex] = wstValidationBuilder;
existing[wstValidationBuilderIndex] = javaBuilder;
int oldWstIndex = wstValidationBuilderIndex;
wstValidationBuilderIndex = javaBuilderIndex;
javaBuilderIndex = oldWstIndex;
updated = true;
}
if(builderIndex==-1) {
if(updated) {
desc.setBuildSpec(existing);
project.setDescription(desc, null);
updated = false;
}
desc = project.getDescription();
existing = desc.getBuildSpec();
builderIndex = existing.length-1;
builder = getBuilder(project, builderId);
}
if(wstValidationBuilderIndex==-1) {
existing = appendBuilder(project, existing, ValidationPlugin.VALIDATION_BUILDER_ID);
wstValidationBuilderIndex = existing.length-1;
wstValidationBuilder = existing[wstValidationBuilderIndex];
updated = true;
}
if(wstValidationBuilderIndex<builderIndex) {
existing[wstValidationBuilderIndex] = builder;
existing[builderIndex] = wstValidationBuilder;
int oldWstIndex = wstValidationBuilderIndex;
wstValidationBuilderIndex = builderIndex;
builderIndex = oldWstIndex;
updated = true;
}
if(builderIndex<javaBuilderIndex) {
existing[javaBuilderIndex] = builder;
existing[builderIndex] = javaBuilder;
int oldJavaIndex = javaBuilderIndex;
javaBuilderIndex = builderIndex;
builderIndex = oldJavaIndex;
updated = true;
}
if(updated) {
desc.setBuildSpec(existing);
project.setDescription(desc, null);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addNatureToProjectWithValidationSupport" | "public static void addNatureToProjectWithValidationSupport(IProject project, String builderId, String natureId) throws CoreException {
IProjectDescription desc = project.getDescription();
ICommand[] existing = desc.getBuildSpec();
boolean updated = false;
int javaBuilderIndex = -1;
ICommand javaBuilder = null;
int wstValidationBuilderIndex = -1;
ICommand wstValidationBuilder = null;
int builderIndex = -1;
ICommand builder = null;
for (int i = 0; i < existing.length; i++) {
if(JAVA_BUILDER_ID.equals(existing[i].getBuilderName())) {
javaBuilderIndex = i;
javaBuilder = existing[i];
} else if(ValidationPlugin.VALIDATION_BUILDER_ID.equals(existing[i].getBuilderName())) {
wstValidationBuilderIndex = i;
wstValidationBuilder = existing[i];
} else if(builderId.equals(existing[i].getBuilderName())) {
builderIndex = i;
builder = existing[i];
}
}
if(javaBuilderIndex==-1) {
getDefault().logError("Can't enable " + builderId + " support on the project " + project.getName() + " without Java builder."); //$NON-NLS-1$ //$NON-NLS-2$//$NON-NLS-3$
return;
}
if(wstValidationBuilderIndex!=-1 && wstValidationBuilderIndex<javaBuilderIndex) {
existing[javaBuilderIndex] = wstValidationBuilder;
existing[wstValidationBuilderIndex] = javaBuilder;
int oldWstIndex = wstValidationBuilderIndex;
wstValidationBuilderIndex = javaBuilderIndex;
javaBuilderIndex = oldWstIndex;
updated = true;
}
if(builderIndex==-1) {
if(updated) {
desc.setBuildSpec(existing);
project.setDescription(desc, null);
updated = false;
}
<MASK>EclipseResourceUtil.addNatureToProject(project, natureId);</MASK>
desc = project.getDescription();
existing = desc.getBuildSpec();
builderIndex = existing.length-1;
builder = getBuilder(project, builderId);
}
if(wstValidationBuilderIndex==-1) {
existing = appendBuilder(project, existing, ValidationPlugin.VALIDATION_BUILDER_ID);
wstValidationBuilderIndex = existing.length-1;
wstValidationBuilder = existing[wstValidationBuilderIndex];
updated = true;
}
if(wstValidationBuilderIndex<builderIndex) {
existing[wstValidationBuilderIndex] = builder;
existing[builderIndex] = wstValidationBuilder;
int oldWstIndex = wstValidationBuilderIndex;
wstValidationBuilderIndex = builderIndex;
builderIndex = oldWstIndex;
updated = true;
}
if(builderIndex<javaBuilderIndex) {
existing[javaBuilderIndex] = builder;
existing[builderIndex] = javaBuilder;
int oldJavaIndex = javaBuilderIndex;
javaBuilderIndex = builderIndex;
builderIndex = oldJavaIndex;
updated = true;
}
if(updated) {
desc.setBuildSpec(existing);
project.setDescription(desc, null);
}
}" |
Inversion-Mutation | megadiff | "@Override
public void map(WritableComparable docID, Text docContents, Context context)
throws IOException, InterruptedException {
Matcher matcher = WORD_PATTERN.matcher(docContents.toString());
Func func = funcFromNum(funcNum);
// YOUR CODE HERE
// make a copy of the Matcher for parsing, record indices of targets to list
Matcher copy = WORD_PATTERN.matcher(docContents.toString());
List<Double> targets = new ArrayList<Double>();
double count = 0;
while(copy.find()){
String w = copy.group().toLowerCase();
if(w.equals(targetGram))
targets.add(new Double(count));
count++;
}
if(targets.isEmpty()){
while(matcher.find())
context.write(new Text(matcher.group().toLowerCase()), new DoublePair(1.0, func.f(Double.POSITIVE_INFINITY)));
}
else{
count = 0;
while(matcher.find()){
String word = matcher.group().toLowerCase();
// if word is not target word
if(!word.equals(targetGram)){
context.write(new Text(word), new DoublePair(1.0, func.f(closestDist(targets, count))));
System.out.println(word + " " + func.f(closestDist(targets, count)));
count++;
}
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "map" | "@Override
public void map(WritableComparable docID, Text docContents, Context context)
throws IOException, InterruptedException {
Matcher matcher = WORD_PATTERN.matcher(docContents.toString());
Func func = funcFromNum(funcNum);
// YOUR CODE HERE
// make a copy of the Matcher for parsing, record indices of targets to list
Matcher copy = WORD_PATTERN.matcher(docContents.toString());
List<Double> targets = new ArrayList<Double>();
double count = 0;
while(copy.find()){
String w = copy.group().toLowerCase();
if(w.equals(targetGram))
targets.add(new Double(count));
<MASK>count++;</MASK>
}
if(targets.isEmpty()){
while(matcher.find())
context.write(new Text(matcher.group().toLowerCase()), new DoublePair(1.0, func.f(Double.POSITIVE_INFINITY)));
}
else{
count = 0;
while(matcher.find()){
String word = matcher.group().toLowerCase();
// if word is not target word
if(!word.equals(targetGram)){
context.write(new Text(word), new DoublePair(1.0, func.f(closestDist(targets, count))));
<MASK>count++;</MASK>
System.out.println(word + " " + func.f(closestDist(targets, count)));
}
}
}
}" |
Inversion-Mutation | megadiff | "public Node appendChild(Node newChild) throws DOMException
{
Child child = (Child) newChild;
DocumentImpl doc = m_doc;
child.m_parent = this;
m_childCount++;
if(0 == child.m_uid)
{
child.m_uid = ++m_doc.m_docOrderCount;
}
child.m_level = (short) (m_level + 1);
if (null == m_first)
{
m_first = child;
}
else
{
child.m_prev = m_last;
m_last.m_next = child;
}
m_last = child;
// getDocumentImpl().getLevelIndexer().insertNode(child);
if (Node.ELEMENT_NODE == child.getNodeType())
{
SourceTreeHandler sh = doc.getSourceTreeHandler();
if ((null != sh) && sh.m_shouldCheckWhitespace)
{
TransformerImpl transformer = sh.getTransformerImpl();
if (null != transformer)
{
StylesheetRoot stylesheet = transformer.getStylesheet();
try
{
ElementImpl elem = (ElementImpl) child;
WhiteSpaceInfo info =
stylesheet.getWhiteSpaceInfo(transformer.getXPathContext(),
elem);
boolean shouldStrip;
if (null == info)
{
shouldStrip = sh.getShouldStripWhitespace();
}
else
{
shouldStrip = info.getShouldStripSpace();
}
sh.setShouldStripWhitespace(shouldStrip);
}
catch (TransformerException se)
{
// TODO: Diagnostics
}
}
}
}
return newChild;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "appendChild" | "public Node appendChild(Node newChild) throws DOMException
{
Child child = (Child) newChild;
DocumentImpl doc = m_doc;
child.m_parent = this;
m_childCount++;
if(0 == child.m_uid)
{
child.m_uid = ++m_doc.m_docOrderCount;
}
child.m_level = (short) (m_level + 1);
if (null == m_first)
{
m_first = child;
}
else
{
<MASK>m_last.m_next = child;</MASK>
child.m_prev = m_last;
}
m_last = child;
// getDocumentImpl().getLevelIndexer().insertNode(child);
if (Node.ELEMENT_NODE == child.getNodeType())
{
SourceTreeHandler sh = doc.getSourceTreeHandler();
if ((null != sh) && sh.m_shouldCheckWhitespace)
{
TransformerImpl transformer = sh.getTransformerImpl();
if (null != transformer)
{
StylesheetRoot stylesheet = transformer.getStylesheet();
try
{
ElementImpl elem = (ElementImpl) child;
WhiteSpaceInfo info =
stylesheet.getWhiteSpaceInfo(transformer.getXPathContext(),
elem);
boolean shouldStrip;
if (null == info)
{
shouldStrip = sh.getShouldStripWhitespace();
}
else
{
shouldStrip = info.getShouldStripSpace();
}
sh.setShouldStripWhitespace(shouldStrip);
}
catch (TransformerException se)
{
// TODO: Diagnostics
}
}
}
}
return newChild;
}" |
Inversion-Mutation | megadiff | "private ConfigData getConfigData() {
DataLoader loader = createDataLoader();
ConfigData result;
if (loader != null)
result = loader.getConfigData();
else
result = generateConfigData();
addProductFileConfigBundles(result); // these are the bundles specified in the <configurations> tag in the product file
addProductFileBundles(result); // these are the bundles specified in the <plugins/> tag
if (product.getProductId() != null)
result.setProperty("eclipse.product", product.getProductId()); //$NON-NLS-1$
if (product.getApplication() != null)
result.setProperty("eclipse.application", product.getApplication()); //$NON-NLS-1$
String location = getSplashLocation();
if (location != null)
result.setProperty(OSGI_SPLASH_PATH, SPLASH_PREFIX + location);
return result;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getConfigData" | "private ConfigData getConfigData() {
DataLoader loader = createDataLoader();
ConfigData result;
if (loader != null)
result = loader.getConfigData();
else
result = generateConfigData();
<MASK>addProductFileBundles(result); // these are the bundles specified in the <plugins/> tag</MASK>
addProductFileConfigBundles(result); // these are the bundles specified in the <configurations> tag in the product file
if (product.getProductId() != null)
result.setProperty("eclipse.product", product.getProductId()); //$NON-NLS-1$
if (product.getApplication() != null)
result.setProperty("eclipse.application", product.getApplication()); //$NON-NLS-1$
String location = getSplashLocation();
if (location != null)
result.setProperty(OSGI_SPLASH_PATH, SPLASH_PREFIX + location);
return result;
}" |
Inversion-Mutation | megadiff | "@Test
public void rootTest4() {
l.setValues(Levels.FATAL);
r.setLevel(l);
r.addAppenderRef("A9");
r.isRootCategory(true);
r.generateProperties(p);
expectedKey = PropertiesParser.PREFIX + "." + PropertiesParser.ROOT_CATEGORY;
testExpected("FATAL, A9");
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "rootTest4" | "@Test
public void rootTest4() {
l.setValues(Levels.FATAL);
r.setLevel(l);
r.addAppenderRef("A9");
<MASK>r.generateProperties(p);</MASK>
r.isRootCategory(true);
expectedKey = PropertiesParser.PREFIX + "." + PropertiesParser.ROOT_CATEGORY;
testExpected("FATAL, A9");
}" |
Inversion-Mutation | megadiff | "@Override
public Graph transform(Graph graph) {
Random rand = new Random();
for (int r = 0; r < this.realities; r++) {
ChordIdentifierSpace idSpace = new ChordIdentifierSpace(this.bits);
ChordIdentifier[] ids = new ChordIdentifier[graph.getNodes().length];
if (this.uniform) {
BigInteger stepSize = idSpace.getModulus().divide(
new BigInteger("" + graph.getNodes().length));
for (int i = 0; i < ids.length; i++) {
ids[i] = new ChordIdentifier(idSpace,
stepSize.multiply(new BigInteger("" + i)));
}
} else {
HashSet<String> idSet = new HashSet<String>();
for (int i = 0; i < ids.length; i++) {
ChordIdentifier id = (ChordIdentifier) idSpace.randomID(rand);
while (idSet.contains(id.toString())) {
id = (ChordIdentifier) idSpace.randomID(rand);
}
ids[i] = id;
idSet.add(id.toString());
}
}
Arrays.sort(ids);
ChordPartition[] partitions = new ChordPartition[ids.length];
partitions[0] = new ChordPartition(ids[ids.length - 1], ids[0]);
for (int i = 1; i < partitions.length; i++) {
partitions[i] = new ChordPartition(ids[i - 1], ids[i]);
}
// Util.randomize(partitions, rand);
idSpace.setPartitions(partitions);
graph.addProperty(graph.getNextKey("ID_SPACE"), idSpace);
}
return graph;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "transform" | "@Override
public Graph transform(Graph graph) {
Random rand = new Random();
<MASK>ChordIdentifierSpace idSpace = new ChordIdentifierSpace(this.bits);</MASK>
for (int r = 0; r < this.realities; r++) {
ChordIdentifier[] ids = new ChordIdentifier[graph.getNodes().length];
if (this.uniform) {
BigInteger stepSize = idSpace.getModulus().divide(
new BigInteger("" + graph.getNodes().length));
for (int i = 0; i < ids.length; i++) {
ids[i] = new ChordIdentifier(idSpace,
stepSize.multiply(new BigInteger("" + i)));
}
} else {
HashSet<String> idSet = new HashSet<String>();
for (int i = 0; i < ids.length; i++) {
ChordIdentifier id = (ChordIdentifier) idSpace.randomID(rand);
while (idSet.contains(id.toString())) {
id = (ChordIdentifier) idSpace.randomID(rand);
}
ids[i] = id;
idSet.add(id.toString());
}
}
Arrays.sort(ids);
ChordPartition[] partitions = new ChordPartition[ids.length];
partitions[0] = new ChordPartition(ids[ids.length - 1], ids[0]);
for (int i = 1; i < partitions.length; i++) {
partitions[i] = new ChordPartition(ids[i - 1], ids[i]);
}
// Util.randomize(partitions, rand);
idSpace.setPartitions(partitions);
graph.addProperty(graph.getNextKey("ID_SPACE"), idSpace);
}
return graph;
}" |
Inversion-Mutation | megadiff | "private static void initializeSystemClass() {
props = new Properties();
propProviders = new Hashtable();
initProperties(props);
midpProps = new Properties();
initCldcMidpProperties(midpProps);
// dynamic properties initialization (should be moved to more
// appropriate place when we have dynamic package loading implemented)
String[] mainClasses = PackageManager.listComponents();
for (int i = 0; i < mainClasses.length; i++) {
try {
Class.forName(mainClasses[i]);
} catch (ClassNotFoundException e) {
// ignore silently
}
}
sun.misc.Version.init();
FileInputStream fdIn = new FileInputStream(FileDescriptor.in);
FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err);
setIn0(new BufferedInputStream(fdIn));
setOut0(new PrintStream(new BufferedOutputStream(fdOut, 128), true));
setErr0(new PrintStream(new BufferedOutputStream(fdErr, 128), true));
// Load the zip library now in order to keep java.util.zip.ZipFile
// from trying to use itself to load this library later.
// CVM statically loads zip
//loadLibrary("zip");
// Currently File.deleteOnExit is built on JVM_Exit, which is a
// separate mechanism from shutdown hooks. Unfortunately in order to
// work properly JVM_Exit implicitly requires that Java signal
// handlers be set up for HUP, TERM, and INT (where available). If
// File.deleteOnExit were implemented in terms of shutdown hooks this
// call to Terminator.setup() could be removed.
Terminator.setup();
// Set the maximum amount of direct memory. This value is controlled
// by the vm option -XX:MaxDirectMemorySize=<size>. This method acts
// as an initializer only if it is called before sun.misc.VM.booted().
// Subsystems that are invoked during initialization can invoke
// sun.misc.VM.isBooted() in order to avoid doing things that should
// wait until the application class loader has been set up.
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "initializeSystemClass" | "private static void initializeSystemClass() {
props = new Properties();
initProperties(props);
midpProps = new Properties();
initCldcMidpProperties(midpProps);
// dynamic properties initialization (should be moved to more
// appropriate place when we have dynamic package loading implemented)
<MASK>propProviders = new Hashtable();</MASK>
String[] mainClasses = PackageManager.listComponents();
for (int i = 0; i < mainClasses.length; i++) {
try {
Class.forName(mainClasses[i]);
} catch (ClassNotFoundException e) {
// ignore silently
}
}
sun.misc.Version.init();
FileInputStream fdIn = new FileInputStream(FileDescriptor.in);
FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err);
setIn0(new BufferedInputStream(fdIn));
setOut0(new PrintStream(new BufferedOutputStream(fdOut, 128), true));
setErr0(new PrintStream(new BufferedOutputStream(fdErr, 128), true));
// Load the zip library now in order to keep java.util.zip.ZipFile
// from trying to use itself to load this library later.
// CVM statically loads zip
//loadLibrary("zip");
// Currently File.deleteOnExit is built on JVM_Exit, which is a
// separate mechanism from shutdown hooks. Unfortunately in order to
// work properly JVM_Exit implicitly requires that Java signal
// handlers be set up for HUP, TERM, and INT (where available). If
// File.deleteOnExit were implemented in terms of shutdown hooks this
// call to Terminator.setup() could be removed.
Terminator.setup();
// Set the maximum amount of direct memory. This value is controlled
// by the vm option -XX:MaxDirectMemorySize=<size>. This method acts
// as an initializer only if it is called before sun.misc.VM.booted().
// Subsystems that are invoked during initialization can invoke
// sun.misc.VM.isBooted() in order to avoid doing things that should
// wait until the application class loader has been set up.
}" |
Inversion-Mutation | megadiff | "@Test
public void testGetNextExecutionAfter() {
Calendar c = null;
Date expectedFireDate = null;
// minute
expectedFireDate = rollUp(Calendar.getInstance(), Calendar.MINUTE, minutes);
assertEquals(expectedFireDate, minuteTrigger.getNextExecutionAfter(now));
// hour
c = Calendar.getInstance();
c.set(Calendar.MINUTE, 0);
expectedFireDate = rollUp(c, Calendar.HOUR_OF_DAY, hours);
assertEquals(expectedFireDate, hourTrigger.getNextExecutionAfter(now));
// day of month
c = Calendar.getInstance();
c.set(Calendar.MINUTE, 0);
c.set(Calendar.HOUR_OF_DAY, 0);
expectedFireDate = rollUp(c, Calendar.DAY_OF_MONTH, daysOfMonth);
assertEquals(expectedFireDate, dayOfMonthTrigger.getNextExecutionAfter(now));
// month
c = Calendar.getInstance();
c.set(Calendar.MINUTE, 0);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.DAY_OF_MONTH, 1);
expectedFireDate = rollUp(c, Calendar.MONTH, months);
assertEquals(expectedFireDate, monthTrigger.getNextExecutionAfter(now));
// day of week
c = Calendar.getInstance();
c.set(Calendar.MINUTE, 0);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.DAY_OF_MONTH, 1);
expectedFireDate = rollUp(c, Calendar.MONTH, new int[] { 1 });
expectedFireDate = rollUp(c, Calendar.DAY_OF_WEEK, daysOfWeek);
assertEquals(expectedFireDate, dayOfWeekTrigger.getNextExecutionAfter(now));
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "testGetNextExecutionAfter" | "@Test
public void testGetNextExecutionAfter() {
Calendar c = null;
Date expectedFireDate = null;
// minute
expectedFireDate = rollUp(Calendar.getInstance(), Calendar.MINUTE, minutes);
assertEquals(expectedFireDate, minuteTrigger.getNextExecutionAfter(now));
// hour
c = Calendar.getInstance();
c.set(Calendar.MINUTE, 0);
expectedFireDate = rollUp(c, Calendar.HOUR_OF_DAY, hours);
assertEquals(expectedFireDate, hourTrigger.getNextExecutionAfter(now));
// day of month
c = Calendar.getInstance();
c.set(Calendar.MINUTE, 0);
c.set(Calendar.HOUR_OF_DAY, 0);
expectedFireDate = rollUp(c, Calendar.DAY_OF_MONTH, daysOfMonth);
assertEquals(expectedFireDate, dayOfMonthTrigger.getNextExecutionAfter(now));
// month
c = Calendar.getInstance();
c.set(Calendar.MINUTE, 0);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.DAY_OF_MONTH, 1);
expectedFireDate = rollUp(c, Calendar.MONTH, months);
assertEquals(expectedFireDate, monthTrigger.getNextExecutionAfter(now));
// day of week
c = Calendar.getInstance();
c.set(Calendar.MINUTE, 0);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.DAY_OF_MONTH, 1);
<MASK>expectedFireDate = rollUp(c, Calendar.DAY_OF_WEEK, daysOfWeek);</MASK>
expectedFireDate = rollUp(c, Calendar.MONTH, new int[] { 1 });
assertEquals(expectedFireDate, dayOfWeekTrigger.getNextExecutionAfter(now));
}" |
Inversion-Mutation | megadiff | "JavaBookModel(Book book) {
super(book);
myImageMap = new ZLImageMap();
myInternalHyperlinks = new CachedCharStorage(32768, Paths.cacheDirectory(), "links");
BookTextModel = new ZLTextWritablePlainModel(null, book.getLanguage(), 1024, 65536, Paths.cacheDirectory(), "cache", myImageMap);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "JavaBookModel" | "JavaBookModel(Book book) {
super(book);
<MASK>BookTextModel = new ZLTextWritablePlainModel(null, book.getLanguage(), 1024, 65536, Paths.cacheDirectory(), "cache", myImageMap);</MASK>
myImageMap = new ZLImageMap();
myInternalHyperlinks = new CachedCharStorage(32768, Paths.cacheDirectory(), "links");
}" |
Inversion-Mutation | megadiff | "public void saveUserAddons(ISdkLog log) {
FileOutputStream fos = null;
try {
String folder = AndroidLocation.getFolder();
File f = new File(folder, SRC_FILENAME);
fos = new FileOutputStream(f);
Properties props = new Properties();
int count = 0;
for (SdkSource s : getSources(SdkSourceCategory.USER_ADDONS)) {
props.setProperty(String.format("%s%02d", KEY_SRC, count), s.getUrl()); //$NON-NLS-1$
count++;
}
props.setProperty(KEY_COUNT, Integer.toString(count));
props.store( fos, "## User Sources for Android tool"); //$NON-NLS-1$
} catch (AndroidLocationException e) {
log.error(e, null);
} catch (IOException e) {
log.error(e, null);
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
}
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "saveUserAddons" | "public void saveUserAddons(ISdkLog log) {
FileOutputStream fos = null;
try {
String folder = AndroidLocation.getFolder();
File f = new File(folder, SRC_FILENAME);
fos = new FileOutputStream(f);
Properties props = new Properties();
int count = 0;
for (SdkSource s : getSources(SdkSourceCategory.USER_ADDONS)) {
<MASK>count++;</MASK>
props.setProperty(String.format("%s%02d", KEY_SRC, count), s.getUrl()); //$NON-NLS-1$
}
props.setProperty(KEY_COUNT, Integer.toString(count));
props.store( fos, "## User Sources for Android tool"); //$NON-NLS-1$
} catch (AndroidLocationException e) {
log.error(e, null);
} catch (IOException e) {
log.error(e, null);
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
}
}
}
}" |
Inversion-Mutation | megadiff | "@Override
protected void onCreate(Bundle savedInstanceState) {
Themes.applyTheme(this);
super.onCreate(savedInstanceState);
registerExternalStorageListener();
View mainView = getLayoutInflater().inflate(R.layout.card_editor, null);
setContentView(mainView);
Themes.setWallpaper(mainView);
mFieldsLayoutContainer = (LinearLayout) findViewById(R.id.CardEditorEditFieldsLayout);
Themes.setTextViewStyle(mFieldsLayoutContainer);
setTitle(R.string.cardeditor_title);
mSave = (Button) findViewById(R.id.CardEditorSaveButton);
mCancel = (Button) findViewById(R.id.CardEditorCancelButton);
mSwapButton = (Button) findViewById(R.id.CardEditorSwapButton);
mModelButtons = (LinearLayout) findViewById(R.id.CardEditorSelectModelLayout);
mModelButton = (Button) findViewById(R.id.CardEditorModelButton);
mCardModelButton = (Button) findViewById(R.id.CardEditorCardModelButton);
mTags = (Button) findViewById(R.id.CardEditorTagButton);
mNewSelectedCardModels = new LinkedHashMap<Long, CardModel>();
cardModelIds = new ArrayList<Long>();
Intent intent = getIntent();
String action = intent.getAction();
if (action != null && action.equals(INTENT_CREATE_FLASHCARD)) {
prepareForIntentAddition();
Bundle extras = intent.getExtras();
mSourceLanguage = extras.getString("SOURCE_LANGUAGE");
mTargetLanguage = extras.getString("TARGET_LANGUAGE");
mSourceText = extras.getString("SOURCE_TEXT");
mTargetText = extras.getString("TARGET_TEXT");
mAddFact = true;
} else if (action != null
&& action.equals(INTENT_CREATE_FLASHCARD_SEND)) {
prepareForIntentAddition();
Bundle extras = intent.getExtras();
mSourceText = extras.getString(Intent.EXTRA_SUBJECT);
mTargetText = extras.getString(Intent.EXTRA_TEXT);
mAddFact = true;
} else {
switch (intent.getIntExtra(CARD_EDITOR_ACTION, ADD_CARD)) {
case EDIT_REVIEWER_CARD:
mEditorFact = Reviewer.getEditorCard().getFact();
break;
case EDIT_BROWSER_CARD:
mEditorFact = CardBrowser.getEditorCard().getFact();
break;
case ADD_CARD:
mAddFact = true;
mDeck = AnkiDroidApp.deck();
loadContents();
modelChanged();
mSave.setEnabled(false);
break;
}
}
if (mAddFact) {
mModelButtons.setVisibility(View.VISIBLE);
mModelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DIALOG_MODEL_SELECT);
}
});
mCardModelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DIALOG_CARD_MODEL_SELECT);
}
});
mSave.setText(getResources().getString(R.string.add));
mCancel.setText(getResources().getString(R.string.close));
} else {
mFactTags = mEditorFact.getTags();
}
mTags.setText(getResources().getString(R.string.CardEditorTags, mFactTags));
mModified = false;
SharedPreferences preferences = PrefSettings
.getSharedPrefs(getBaseContext());
mPrefFixArabic = preferences.getBoolean("fixArabicText", false);
// if Arabic reshaping is enabled, disable the Save button to avoid
// saving the reshaped string to the deck
if (mPrefFixArabic && !mAddFact) {
mSave.setEnabled(false);
}
mTags.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog(DIALOG_TAGS);
}
});
allTags = null;
mSelectedTags = new HashSet<String>();
mSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mAddFact) {
boolean empty = true;
for (FieldEditText current : mEditFields) {
current.updateField();
if (current.getText().length() != 0) {
empty = false;
}
}
if (!empty) {
mEditorFact.setTags(mFactTags);
DeckTask.launchDeckTask(DeckTask.TASK_TYPE_ADD_FACT,
mSaveFactHandler, new DeckTask.TaskData(mDeck,
mEditorFact, mSelectedCardModels));
setResult(RESULT_OK);
} else {
setResult(RESULT_CANCELED);
}
} else {
Iterator<FieldEditText> iter = mEditFields.iterator();
while (iter.hasNext()) {
FieldEditText current = iter.next();
mModified |= current.updateField();
}
if (!mEditorFact.getTags().equals(mFactTags)) {
mEditorFact.setTags(mFactTags);
mModified = true;
}
// Only send result to save if something was actually
// changed
if (mModified) {
setResult(RESULT_OK);
} else {
setResult(RESULT_CANCELED);
}
closeCardEditor();
}
}
});
mCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setResult(RESULT_CANCELED);
closeCardEditor();
}
});
if (!mAddFact) {
populateEditFields();
}
}" | 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) {
Themes.applyTheme(this);
super.onCreate(savedInstanceState);
registerExternalStorageListener();
View mainView = getLayoutInflater().inflate(R.layout.card_editor, null);
setContentView(mainView);
Themes.setWallpaper(mainView);
mFieldsLayoutContainer = (LinearLayout) findViewById(R.id.CardEditorEditFieldsLayout);
Themes.setTextViewStyle(mFieldsLayoutContainer);
setTitle(R.string.cardeditor_title);
mSave = (Button) findViewById(R.id.CardEditorSaveButton);
mCancel = (Button) findViewById(R.id.CardEditorCancelButton);
mSwapButton = (Button) findViewById(R.id.CardEditorSwapButton);
mModelButtons = (LinearLayout) findViewById(R.id.CardEditorSelectModelLayout);
mModelButton = (Button) findViewById(R.id.CardEditorModelButton);
mCardModelButton = (Button) findViewById(R.id.CardEditorCardModelButton);
mTags = (Button) findViewById(R.id.CardEditorTagButton);
<MASK>mTags.setText(getResources().getString(R.string.CardEditorTags, mFactTags));</MASK>
mNewSelectedCardModels = new LinkedHashMap<Long, CardModel>();
cardModelIds = new ArrayList<Long>();
Intent intent = getIntent();
String action = intent.getAction();
if (action != null && action.equals(INTENT_CREATE_FLASHCARD)) {
prepareForIntentAddition();
Bundle extras = intent.getExtras();
mSourceLanguage = extras.getString("SOURCE_LANGUAGE");
mTargetLanguage = extras.getString("TARGET_LANGUAGE");
mSourceText = extras.getString("SOURCE_TEXT");
mTargetText = extras.getString("TARGET_TEXT");
mAddFact = true;
} else if (action != null
&& action.equals(INTENT_CREATE_FLASHCARD_SEND)) {
prepareForIntentAddition();
Bundle extras = intent.getExtras();
mSourceText = extras.getString(Intent.EXTRA_SUBJECT);
mTargetText = extras.getString(Intent.EXTRA_TEXT);
mAddFact = true;
} else {
switch (intent.getIntExtra(CARD_EDITOR_ACTION, ADD_CARD)) {
case EDIT_REVIEWER_CARD:
mEditorFact = Reviewer.getEditorCard().getFact();
break;
case EDIT_BROWSER_CARD:
mEditorFact = CardBrowser.getEditorCard().getFact();
break;
case ADD_CARD:
mAddFact = true;
mDeck = AnkiDroidApp.deck();
loadContents();
modelChanged();
mSave.setEnabled(false);
break;
}
}
if (mAddFact) {
mModelButtons.setVisibility(View.VISIBLE);
mModelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DIALOG_MODEL_SELECT);
}
});
mCardModelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DIALOG_CARD_MODEL_SELECT);
}
});
mSave.setText(getResources().getString(R.string.add));
mCancel.setText(getResources().getString(R.string.close));
} else {
mFactTags = mEditorFact.getTags();
}
mModified = false;
SharedPreferences preferences = PrefSettings
.getSharedPrefs(getBaseContext());
mPrefFixArabic = preferences.getBoolean("fixArabicText", false);
// if Arabic reshaping is enabled, disable the Save button to avoid
// saving the reshaped string to the deck
if (mPrefFixArabic && !mAddFact) {
mSave.setEnabled(false);
}
mTags.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog(DIALOG_TAGS);
}
});
allTags = null;
mSelectedTags = new HashSet<String>();
mSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mAddFact) {
boolean empty = true;
for (FieldEditText current : mEditFields) {
current.updateField();
if (current.getText().length() != 0) {
empty = false;
}
}
if (!empty) {
mEditorFact.setTags(mFactTags);
DeckTask.launchDeckTask(DeckTask.TASK_TYPE_ADD_FACT,
mSaveFactHandler, new DeckTask.TaskData(mDeck,
mEditorFact, mSelectedCardModels));
setResult(RESULT_OK);
} else {
setResult(RESULT_CANCELED);
}
} else {
Iterator<FieldEditText> iter = mEditFields.iterator();
while (iter.hasNext()) {
FieldEditText current = iter.next();
mModified |= current.updateField();
}
if (!mEditorFact.getTags().equals(mFactTags)) {
mEditorFact.setTags(mFactTags);
mModified = true;
}
// Only send result to save if something was actually
// changed
if (mModified) {
setResult(RESULT_OK);
} else {
setResult(RESULT_CANCELED);
}
closeCardEditor();
}
}
});
mCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setResult(RESULT_CANCELED);
closeCardEditor();
}
});
if (!mAddFact) {
populateEditFields();
}
}" |
Inversion-Mutation | megadiff | "protected void tryListenersForEntity (Entity entity, Event event, PropagationState propState) {
if (logger.isLoggable(Level.INFO)) {
logger.info("tryListenersForEntity, entity = " + entity + ", event = " + event);
}
EventListenerCollection listeners = (EventListenerCollection) entity.getComponent(EventListenerCollection.class);
if (listeners == null || listeners.size() <= 0) {
logger.info("Entity has no listeners");
// propagatesToParent is true, so OR makes no change to its accumulator
// propagatesToUnder is false, so OR makes its accumulator is false
propState.toUnder = false;
} else {
Iterator<EventListener> it = listeners.iterator();
while (it.hasNext()) {
EventListener listener = it.next();
if (listener.isEnabled()) {
if (logger.isLoggable(Level.INFO)) {
logger.info("Calling consume for listener " + listener);
}
Event distribEvent = createEventForEntity(event, entity);
if (listener.consumesEvent(distribEvent)) {
if (logger.isLoggable(Level.INFO)) {
logger.info("CONSUMED event: " + event);
logger.info("Consuming entity " + entity);
logger.info("Consuming listener " + listener);
}
listener.postEvent(distribEvent);
propState.toParent |= listener.propagatesToParent(distribEvent);
}
// TODO: someday: decommit for now
//propState.toUnder |= listener.propagatesToUnder(distribEvent);
// logger.finer("Listener prop state, toParent = " + propState.toParent +
// ", toUnder = " + propState.toUnder);
}
}
}
if (logger.isLoggable(Level.FINE))
logger.fine("Cumulative prop state, toParent = " + propState.toParent + ", toUnder = " + propState.toUnder);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "tryListenersForEntity" | "protected void tryListenersForEntity (Entity entity, Event event, PropagationState propState) {
if (logger.isLoggable(Level.INFO)) {
logger.info("tryListenersForEntity, entity = " + entity + ", event = " + event);
}
EventListenerCollection listeners = (EventListenerCollection) entity.getComponent(EventListenerCollection.class);
if (listeners == null || listeners.size() <= 0) {
logger.info("Entity has no listeners");
// propagatesToParent is true, so OR makes no change to its accumulator
// propagatesToUnder is false, so OR makes its accumulator is false
propState.toUnder = false;
} else {
Iterator<EventListener> it = listeners.iterator();
while (it.hasNext()) {
EventListener listener = it.next();
if (listener.isEnabled()) {
if (logger.isLoggable(Level.INFO)) {
logger.info("Calling consume for listener " + listener);
}
Event distribEvent = createEventForEntity(event, entity);
if (listener.consumesEvent(distribEvent)) {
if (logger.isLoggable(Level.INFO)) {
logger.info("CONSUMED event: " + event);
logger.info("Consuming entity " + entity);
logger.info("Consuming listener " + listener);
}
listener.postEvent(distribEvent);
}
<MASK>propState.toParent |= listener.propagatesToParent(distribEvent);</MASK>
// TODO: someday: decommit for now
//propState.toUnder |= listener.propagatesToUnder(distribEvent);
// logger.finer("Listener prop state, toParent = " + propState.toParent +
// ", toUnder = " + propState.toUnder);
}
}
}
if (logger.isLoggable(Level.FINE))
logger.fine("Cumulative prop state, toParent = " + propState.toParent + ", toUnder = " + propState.toUnder);
}" |
Inversion-Mutation | megadiff | "public void step() {
String chiptext = "";
for(int i = 0; i < Field.C_COUNT; i++) {
for(int j = 0; j < chips[i]; j++) {
chiptext += Field.names[i];
}
}
if(chiptext.length() == 0) {
time = -1;
Field.getSingleton().kills += 1;
}
chiplabel.setText(chiptext);
label.setTextColor(Color.RED);
time -= 1;
label.setText(Integer.toString(time));
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "step" | "public void step() {
<MASK>label.setText(Integer.toString(time));</MASK>
String chiptext = "";
for(int i = 0; i < Field.C_COUNT; i++) {
for(int j = 0; j < chips[i]; j++) {
chiptext += Field.names[i];
}
}
if(chiptext.length() == 0) {
time = -1;
Field.getSingleton().kills += 1;
}
chiplabel.setText(chiptext);
label.setTextColor(Color.RED);
time -= 1;
}" |
Inversion-Mutation | megadiff | "@SuppressWarnings("deprecation")
public MenuManager getSubMenuManager(final List<AbstractTaskContainer> selectedElements) {
final TaskListManager tasklistManager = TasksUiPlugin.getTaskListManager();
final MenuManager subMenuManager = new MenuManager(LABEL_REMINDER);
subMenuManager.setVisible(selectedElements.size() > 0 && selectedElements.get(0) instanceof AbstractTask);// !(selectedElements.get(0) instanceof AbstractTaskContainer || selectedElements.get(0) instanceof AbstractRepositoryQuery));
AbstractTaskContainer singleSelection = null;
if (selectedElements.size() == 1) {
AbstractTaskContainer selectedElement = selectedElements.get(0);
if (selectedElement instanceof AbstractTask) {
singleSelection = selectedElement;
}
}
final AbstractTask singleTaskSelection = tasklistManager.getTaskForElement(singleSelection, false);
final List<AbstractTaskContainer> taskListElementsToSchedule = new ArrayList<AbstractTaskContainer>();
for (AbstractTaskContainer selectedElement : selectedElements) {
if (selectedElement instanceof AbstractTask) {
taskListElementsToSchedule.add(selectedElement);
}
}
Action action = new Action() {
@Override
public void run() {
Calendar reminderCalendar = GregorianCalendar.getInstance();
TasksUiPlugin.getTaskListManager().setScheduledEndOfDay(reminderCalendar);
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = tasklistManager.getTaskForElement(element, true);
TasksUiPlugin.getTaskListManager().setScheduledFor(task, reminderCalendar.getTime());
}
}
};
action.setText(LABEL_TODAY);
action.setImageDescriptor(TasksUiImages.SCHEDULE_DAY);
action.setEnabled(canSchedule(singleSelection, taskListElementsToSchedule));
subMenuManager.add(action);
if (singleTaskSelection != null && (TasksUiPlugin.getTaskListManager().isScheduledForToday(singleTaskSelection)
|| singleTaskSelection.isPastReminder())) {
action.setChecked(true);
}
// subMenuManager.add(new Separator());
final int today = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
for (int i = today + 1; i <= today + 7; i++) {
final int day = i;
action = new Action() {
@Override
public void run() {
Calendar reminderCalendar = TaskActivityUtil.getCalendar();
int dueIn = day - today;
TasksUiPlugin.getTaskListManager().setSecheduledIn(reminderCalendar, dueIn);
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = tasklistManager.getTaskForElement(element, true);
TasksUiPlugin.getTaskListManager().setScheduledFor(task, reminderCalendar.getTime());
}
}
};
getDayLabel(i, action);
if (singleTaskSelection != null && singleTaskSelection.getScheduledForDate() != null
&& !singleTaskSelection.internalIsFloatingScheduledDate()) {
Calendar now = Calendar.getInstance();
now.add(Calendar.DAY_OF_MONTH, i - today);
now.getTime();
Calendar then = Calendar.getInstance();
then.setTime(singleTaskSelection.getScheduledForDate());
if(now.get(Calendar.DAY_OF_MONTH) == then.get(Calendar.DAY_OF_MONTH)) {
action.setChecked(true);
}
}
action.setEnabled(canSchedule(singleSelection, taskListElementsToSchedule));
subMenuManager.add(action);
}
subMenuManager.add(new Separator());
action = new Action() {
@Override
public void run() {
Calendar reminderCalendar = TaskActivityUtil.getCalendar();
TaskActivityUtil.snapStartOfWorkWeek(reminderCalendar);
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = tasklistManager.getTaskForElement(element, true);
if(task != null) {
TasksUiPlugin.getTaskActivityManager().setScheduledFor(task, reminderCalendar.getTime(), true);
}
}
}
};
action.setText(LABEL_THIS_WEEK);
action.setImageDescriptor(TasksUiImages.SCHEDULE_WEEK);
action.setEnabled(canSchedule(singleSelection, taskListElementsToSchedule));
subMenuManager.add(action);
if (singleTaskSelection != null && singleTaskSelection.internalIsFloatingScheduledDate() && TasksUiPlugin.getTaskListManager().isScheduledForThisWeek(singleTaskSelection)) {
action.setChecked(true);
}
action = new Action() {
@Override
public void run() {
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = tasklistManager.getTaskForElement(element, true);
Calendar startNextWeek = Calendar.getInstance();
TasksUiPlugin.getTaskListManager().setScheduledNextWeek(startNextWeek);
TasksUiPlugin.getTaskActivityManager().setScheduledFor(task, startNextWeek.getTime(), true);
}
}
};
action.setText(LABEL_NEXT_WEEK);
action.setEnabled(canSchedule(singleSelection, taskListElementsToSchedule));
if (singleTaskSelection != null && singleTaskSelection.internalIsFloatingScheduledDate()
&& TasksUiPlugin.getTaskListManager().isScheduledAfterThisWeek(singleTaskSelection)
&& !TasksUiPlugin.getTaskListManager().isScheduledForLater(singleTaskSelection)) {
action.setChecked(true);
}
subMenuManager.add(action);
// 2 weeks
action = new Action() {
@Override
public void run() {
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = tasklistManager.getTaskForElement(element, true);
if(task != null) {
Calendar twoWeeks = TaskActivityUtil.getCalendar();
TasksUiPlugin.getTaskListManager().setScheduledNextWeek(twoWeeks);
twoWeeks.add(Calendar.DAY_OF_MONTH, 7);
TasksUiPlugin.getTaskActivityManager().setScheduledFor(task, twoWeeks.getTime(), true);
}
}
}
};
action.setText(LABEL_TWO_WEEKS);
action.setEnabled(canSchedule(singleSelection, taskListElementsToSchedule));
if (singleTaskSelection != null && singleTaskSelection.getScheduledForDate() != null && singleTaskSelection.internalIsFloatingScheduledDate()) {
Calendar time = TaskActivityUtil.getCalendar();
time.setTime(singleTaskSelection.getScheduledForDate());
Calendar start = TaskActivityUtil.getCalendar();
start.setTime(TasksUiPlugin.getTaskActivityManager().getActivityFuture().getStart().getTime());
Calendar end = TaskActivityUtil.getCalendar();
end.setTime(TasksUiPlugin.getTaskActivityManager().getActivityFuture().getStart().getTime());
TaskActivityUtil.snapEndOfWeek(end);
if (TaskActivityUtil.isBetween(time, start, end)) {
action.setChecked(true);
}
}
subMenuManager.add(action);
if (singleTaskSelection != null && singleTaskSelection.getScheduledForDate() != null) {
Calendar time = TaskActivityUtil.getCalendar();
time.setTime(singleTaskSelection.getScheduledForDate());
Calendar start = TaskActivityUtil.getCalendar();
start.setTime(TasksUiPlugin.getTaskActivityManager().getActivityFuture().getStart().getTime());
start.add(Calendar.WEEK_OF_MONTH, 1);
if (time.compareTo(start) >= 0) {
// future
action = new Action() {
@Override
public void run() {
// ignore
}
};
action.setChecked(true);
action.setText(LABEL_FUTURE);
subMenuManager.add(action);
}
}
subMenuManager.add(new Separator());
action = new Action() {
@Override
public void run() {
Calendar theCalendar = GregorianCalendar.getInstance();
if (singleTaskSelection != null && singleTaskSelection.getScheduledForDate() != null) {
theCalendar.setTime(singleTaskSelection.getScheduledForDate());
}
DateSelectionDialog reminderDialog = new DateSelectionDialog(PlatformUI.getWorkbench()
.getActiveWorkbenchWindow()
.getShell(), theCalendar, DatePicker.TITLE_DIALOG, false);
int result = reminderDialog.open();
if (result == Window.OK) {
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = null;
if (element instanceof AbstractTask) {
task = (AbstractTask) element;
}
TasksUiPlugin.getTaskListManager().setScheduledFor(task, reminderDialog.getDate());
}
}
}
};
action.setText(LABEL_CALENDAR);
// action.setImageDescriptor(TasksUiImages.CALENDAR);
action.setImageDescriptor(TasksUiImages.SCHEDULE_DAY);
action.setEnabled(canSchedule(singleSelection, taskListElementsToSchedule));
subMenuManager.add(action);
action = new Action() {
@Override
public void run() {
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = tasklistManager.getTaskForElement(element, true);
TasksUiPlugin.getTaskActivityManager().setScheduledFor(task, null, false);
}
}
};
action.setText(LABEL_NOT_SCHEDULED);
// action.setImageDescriptor(TasksUiImages.REMOVE);
if (singleTaskSelection != null) {
if (singleTaskSelection.getScheduledForDate() == null) {
action.setChecked(true);
}
}
subMenuManager.add(action);
return subMenuManager;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getSubMenuManager" | "@SuppressWarnings("deprecation")
public MenuManager getSubMenuManager(final List<AbstractTaskContainer> selectedElements) {
final TaskListManager tasklistManager = TasksUiPlugin.getTaskListManager();
final MenuManager subMenuManager = new MenuManager(LABEL_REMINDER);
subMenuManager.setVisible(selectedElements.size() > 0 && selectedElements.get(0) instanceof AbstractTask);// !(selectedElements.get(0) instanceof AbstractTaskContainer || selectedElements.get(0) instanceof AbstractRepositoryQuery));
AbstractTaskContainer singleSelection = null;
if (selectedElements.size() == 1) {
AbstractTaskContainer selectedElement = selectedElements.get(0);
if (selectedElement instanceof AbstractTask) {
singleSelection = selectedElement;
}
}
final AbstractTask singleTaskSelection = tasklistManager.getTaskForElement(singleSelection, false);
final List<AbstractTaskContainer> taskListElementsToSchedule = new ArrayList<AbstractTaskContainer>();
for (AbstractTaskContainer selectedElement : selectedElements) {
if (selectedElement instanceof AbstractTask) {
taskListElementsToSchedule.add(selectedElement);
}
}
Action action = new Action() {
@Override
public void run() {
Calendar reminderCalendar = GregorianCalendar.getInstance();
TasksUiPlugin.getTaskListManager().setScheduledEndOfDay(reminderCalendar);
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = tasklistManager.getTaskForElement(element, true);
TasksUiPlugin.getTaskListManager().setScheduledFor(task, reminderCalendar.getTime());
}
}
};
action.setText(LABEL_TODAY);
action.setImageDescriptor(TasksUiImages.SCHEDULE_DAY);
action.setEnabled(canSchedule(singleSelection, taskListElementsToSchedule));
subMenuManager.add(action);
if (singleTaskSelection != null && (TasksUiPlugin.getTaskListManager().isScheduledForToday(singleTaskSelection)
|| singleTaskSelection.isPastReminder())) {
action.setChecked(true);
}
// subMenuManager.add(new Separator());
final int today = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
for (int i = today + 1; i <= today + 7; i++) {
final int day = i;
action = new Action() {
@Override
public void run() {
Calendar reminderCalendar = TaskActivityUtil.getCalendar();
int dueIn = day - today;
TasksUiPlugin.getTaskListManager().setSecheduledIn(reminderCalendar, dueIn);
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = tasklistManager.getTaskForElement(element, true);
TasksUiPlugin.getTaskListManager().setScheduledFor(task, reminderCalendar.getTime());
}
}
};
getDayLabel(i, action);
if (singleTaskSelection != null && singleTaskSelection.getScheduledForDate() != null
&& !singleTaskSelection.internalIsFloatingScheduledDate()) {
Calendar now = Calendar.getInstance();
now.add(Calendar.DAY_OF_MONTH, i - today);
now.getTime();
Calendar then = Calendar.getInstance();
then.setTime(singleTaskSelection.getScheduledForDate());
if(now.get(Calendar.DAY_OF_MONTH) == then.get(Calendar.DAY_OF_MONTH)) {
action.setChecked(true);
}
}
action.setEnabled(canSchedule(singleSelection, taskListElementsToSchedule));
subMenuManager.add(action);
}
subMenuManager.add(new Separator());
action = new Action() {
@Override
public void run() {
Calendar reminderCalendar = TaskActivityUtil.getCalendar();
TaskActivityUtil.snapStartOfWorkWeek(reminderCalendar);
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = tasklistManager.getTaskForElement(element, true);
if(task != null) {
TasksUiPlugin.getTaskActivityManager().setScheduledFor(task, reminderCalendar.getTime(), true);
}
}
}
};
action.setText(LABEL_THIS_WEEK);
action.setEnabled(canSchedule(singleSelection, taskListElementsToSchedule));
subMenuManager.add(action);
if (singleTaskSelection != null && singleTaskSelection.internalIsFloatingScheduledDate() && TasksUiPlugin.getTaskListManager().isScheduledForThisWeek(singleTaskSelection)) {
action.setChecked(true);
}
action = new Action() {
@Override
public void run() {
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = tasklistManager.getTaskForElement(element, true);
Calendar startNextWeek = Calendar.getInstance();
TasksUiPlugin.getTaskListManager().setScheduledNextWeek(startNextWeek);
TasksUiPlugin.getTaskActivityManager().setScheduledFor(task, startNextWeek.getTime(), true);
}
}
};
action.setText(LABEL_NEXT_WEEK);
<MASK>action.setImageDescriptor(TasksUiImages.SCHEDULE_WEEK);</MASK>
action.setEnabled(canSchedule(singleSelection, taskListElementsToSchedule));
if (singleTaskSelection != null && singleTaskSelection.internalIsFloatingScheduledDate()
&& TasksUiPlugin.getTaskListManager().isScheduledAfterThisWeek(singleTaskSelection)
&& !TasksUiPlugin.getTaskListManager().isScheduledForLater(singleTaskSelection)) {
action.setChecked(true);
}
subMenuManager.add(action);
// 2 weeks
action = new Action() {
@Override
public void run() {
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = tasklistManager.getTaskForElement(element, true);
if(task != null) {
Calendar twoWeeks = TaskActivityUtil.getCalendar();
TasksUiPlugin.getTaskListManager().setScheduledNextWeek(twoWeeks);
twoWeeks.add(Calendar.DAY_OF_MONTH, 7);
TasksUiPlugin.getTaskActivityManager().setScheduledFor(task, twoWeeks.getTime(), true);
}
}
}
};
action.setText(LABEL_TWO_WEEKS);
action.setEnabled(canSchedule(singleSelection, taskListElementsToSchedule));
if (singleTaskSelection != null && singleTaskSelection.getScheduledForDate() != null && singleTaskSelection.internalIsFloatingScheduledDate()) {
Calendar time = TaskActivityUtil.getCalendar();
time.setTime(singleTaskSelection.getScheduledForDate());
Calendar start = TaskActivityUtil.getCalendar();
start.setTime(TasksUiPlugin.getTaskActivityManager().getActivityFuture().getStart().getTime());
Calendar end = TaskActivityUtil.getCalendar();
end.setTime(TasksUiPlugin.getTaskActivityManager().getActivityFuture().getStart().getTime());
TaskActivityUtil.snapEndOfWeek(end);
if (TaskActivityUtil.isBetween(time, start, end)) {
action.setChecked(true);
}
}
subMenuManager.add(action);
if (singleTaskSelection != null && singleTaskSelection.getScheduledForDate() != null) {
Calendar time = TaskActivityUtil.getCalendar();
time.setTime(singleTaskSelection.getScheduledForDate());
Calendar start = TaskActivityUtil.getCalendar();
start.setTime(TasksUiPlugin.getTaskActivityManager().getActivityFuture().getStart().getTime());
start.add(Calendar.WEEK_OF_MONTH, 1);
if (time.compareTo(start) >= 0) {
// future
action = new Action() {
@Override
public void run() {
// ignore
}
};
action.setChecked(true);
action.setText(LABEL_FUTURE);
subMenuManager.add(action);
}
}
subMenuManager.add(new Separator());
action = new Action() {
@Override
public void run() {
Calendar theCalendar = GregorianCalendar.getInstance();
if (singleTaskSelection != null && singleTaskSelection.getScheduledForDate() != null) {
theCalendar.setTime(singleTaskSelection.getScheduledForDate());
}
DateSelectionDialog reminderDialog = new DateSelectionDialog(PlatformUI.getWorkbench()
.getActiveWorkbenchWindow()
.getShell(), theCalendar, DatePicker.TITLE_DIALOG, false);
int result = reminderDialog.open();
if (result == Window.OK) {
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = null;
if (element instanceof AbstractTask) {
task = (AbstractTask) element;
}
TasksUiPlugin.getTaskListManager().setScheduledFor(task, reminderDialog.getDate());
}
}
}
};
action.setText(LABEL_CALENDAR);
// action.setImageDescriptor(TasksUiImages.CALENDAR);
action.setImageDescriptor(TasksUiImages.SCHEDULE_DAY);
action.setEnabled(canSchedule(singleSelection, taskListElementsToSchedule));
subMenuManager.add(action);
action = new Action() {
@Override
public void run() {
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = tasklistManager.getTaskForElement(element, true);
TasksUiPlugin.getTaskActivityManager().setScheduledFor(task, null, false);
}
}
};
action.setText(LABEL_NOT_SCHEDULED);
// action.setImageDescriptor(TasksUiImages.REMOVE);
if (singleTaskSelection != null) {
if (singleTaskSelection.getScheduledForDate() == null) {
action.setChecked(true);
}
}
subMenuManager.add(action);
return subMenuManager;
}" |
Inversion-Mutation | megadiff | "public void addSpectator(Player player, String type) {
if (type.equals("death")) {
Messaging.tell(player, Message.WELCOME_SPECTATOR_DEATH);
} else {
SafeTeleporter.tp(player, Waypoint.SPECTATOR);
Messaging.tell(player, Message.WELCOME_SPECTATOR);
}
if (!PlayerData.storageContains(player)) {
PlayerData.store(player);
}
SimpleUtil.reset(player);
player.setAllowFlight(true);
for (String n : usersTeam.keySet()) {
if (Bukkit.getPlayerExact(n) != null) {
Bukkit.getPlayerExact(n).hidePlayer(player);
}
}
spectators.add(player.getName());
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addSpectator" | "public void addSpectator(Player player, String type) {
if (type.equals("death")) {
Messaging.tell(player, Message.WELCOME_SPECTATOR_DEATH);
} else {
SafeTeleporter.tp(player, Waypoint.SPECTATOR);
Messaging.tell(player, Message.WELCOME_SPECTATOR);
}
if (!PlayerData.storageContains(player)) {
PlayerData.store(player);
<MASK>SimpleUtil.reset(player);</MASK>
}
player.setAllowFlight(true);
for (String n : usersTeam.keySet()) {
if (Bukkit.getPlayerExact(n) != null) {
Bukkit.getPlayerExact(n).hidePlayer(player);
}
}
spectators.add(player.getName());
}" |
Inversion-Mutation | megadiff | "protected void writeLogFile(Element logElement)
throws CruiseControlException {
BufferedWriter logWriter = null;
try {
XMLLogHelper helper = new XMLLogHelper(logElement);
if (helper.isBuildSuccessful())
_logFileName = new File(_logDir, "log" + _formatter.format(_now)
+ "L" + helper.getLabel() + ".xml").getAbsolutePath();
else
_logFileName = new File(_logDir, "log" + _formatter.format(_now)
+ ".xml").getAbsolutePath();
log.debug("Writing log file: " + _logFileName);
if(_logXmlEncoding == null) {
_logXmlEncoding = System.getProperty("file.encoding");
}
XMLOutputter outputter = new XMLOutputter(" ", true, _logXmlEncoding);
logWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(_logFileName), _logXmlEncoding));
outputter.output(new Document(logElement), logWriter);
logWriter = null;
} catch (IOException e) {
throw new CruiseControlException(e);
} finally {
logWriter = null;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "writeLogFile" | "protected void writeLogFile(Element logElement)
throws CruiseControlException {
BufferedWriter logWriter = null;
try {
XMLLogHelper helper = new XMLLogHelper(logElement);
if (helper.isBuildSuccessful())
_logFileName = new File(_logDir, "log" + _formatter.format(_now)
+ "L" + helper.getLabel() + ".xml").getAbsolutePath();
else
_logFileName = new File(_logDir, "log" + _formatter.format(_now)
+ ".xml").getAbsolutePath();
log.debug("Writing log file: " + _logFileName);
<MASK>XMLOutputter outputter = new XMLOutputter(" ", true, _logXmlEncoding);</MASK>
if(_logXmlEncoding == null) {
_logXmlEncoding = System.getProperty("file.encoding");
}
logWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(_logFileName), _logXmlEncoding));
outputter.output(new Document(logElement), logWriter);
logWriter = null;
} catch (IOException e) {
throw new CruiseControlException(e);
} finally {
logWriter = null;
}
}" |
Inversion-Mutation | megadiff | "@SuppressWarnings({"ConstantConditions"})
@Override
protected boolean dispatchHoverEvent(MotionEvent event) {
final int action = event.getAction();
// First check whether the view group wants to intercept the hover event.
final boolean interceptHover = onInterceptHoverEvent(event);
event.setAction(action); // restore action in case it was changed
MotionEvent eventNoHistory = event;
boolean handled = false;
// Send events to the hovered children and build a new list of hover targets until
// one is found that handles the event.
HoverTarget firstOldHoverTarget = mFirstHoverTarget;
mFirstHoverTarget = null;
if (!interceptHover && action != MotionEvent.ACTION_HOVER_EXIT) {
final float x = event.getX();
final float y = event.getY();
final int childrenCount = mChildrenCount;
if (childrenCount != 0) {
final View[] children = mChildren;
HoverTarget lastHoverTarget = null;
for (int i = childrenCount - 1; i >= 0; i--) {
final View child = children[i];
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
continue;
}
// Obtain a hover target for this child. Dequeue it from the
// old hover target list if the child was previously hovered.
HoverTarget hoverTarget = firstOldHoverTarget;
final boolean wasHovered;
for (HoverTarget predecessor = null; ;) {
if (hoverTarget == null) {
hoverTarget = HoverTarget.obtain(child);
wasHovered = false;
break;
}
if (hoverTarget.child == child) {
if (predecessor != null) {
predecessor.next = hoverTarget.next;
} else {
firstOldHoverTarget = hoverTarget.next;
}
hoverTarget.next = null;
wasHovered = true;
break;
}
predecessor = hoverTarget;
hoverTarget = hoverTarget.next;
}
// Enqueue the hover target onto the new hover target list.
if (lastHoverTarget != null) {
lastHoverTarget.next = hoverTarget;
} else {
mFirstHoverTarget = hoverTarget;
}
lastHoverTarget = hoverTarget;
// Dispatch the event to the child.
if (action == MotionEvent.ACTION_HOVER_ENTER) {
if (!wasHovered) {
// Send the enter as is.
handled |= dispatchTransformedGenericPointerEvent(
event, child); // enter
}
} else if (action == MotionEvent.ACTION_HOVER_MOVE) {
if (!wasHovered) {
// Synthesize an enter from a move.
eventNoHistory = obtainMotionEventNoHistoryOrSelf(eventNoHistory);
eventNoHistory.setAction(MotionEvent.ACTION_HOVER_ENTER);
handled |= dispatchTransformedGenericPointerEvent(
eventNoHistory, child); // enter
eventNoHistory.setAction(action);
handled |= dispatchTransformedGenericPointerEvent(
eventNoHistory, child); // move
} else {
// Send the move as is.
handled |= dispatchTransformedGenericPointerEvent(event, child);
}
}
if (handled) {
break;
}
}
}
}
// Send exit events to all previously hovered children that are no longer hovered.
while (firstOldHoverTarget != null) {
final View child = firstOldHoverTarget.child;
// Exit the old hovered child.
if (action == MotionEvent.ACTION_HOVER_EXIT) {
// Send the exit as is.
handled |= dispatchTransformedGenericPointerEvent(
event, child); // exit
} else {
// Synthesize an exit from a move or enter.
// Ignore the result because hover focus has moved to a different view.
if (action == MotionEvent.ACTION_HOVER_MOVE) {
dispatchTransformedGenericPointerEvent(
event, child); // move
}
eventNoHistory = obtainMotionEventNoHistoryOrSelf(eventNoHistory);
eventNoHistory.setAction(MotionEvent.ACTION_HOVER_EXIT);
dispatchTransformedGenericPointerEvent(
eventNoHistory, child); // exit
eventNoHistory.setAction(action);
}
final HoverTarget nextOldHoverTarget = firstOldHoverTarget.next;
firstOldHoverTarget.recycle();
firstOldHoverTarget = nextOldHoverTarget;
}
// Send events to the view group itself if no children have handled it.
boolean newHoveredSelf = !handled;
if (newHoveredSelf == mHoveredSelf) {
if (newHoveredSelf) {
// Send event to the view group as before.
handled |= super.dispatchHoverEvent(event);
}
} else {
if (mHoveredSelf) {
// Exit the view group.
if (action == MotionEvent.ACTION_HOVER_EXIT) {
// Send the exit as is.
handled |= super.dispatchHoverEvent(event); // exit
} else {
// Synthesize an exit from a move or enter.
// Ignore the result because hover focus is moving to a different view.
if (action == MotionEvent.ACTION_HOVER_MOVE) {
super.dispatchHoverEvent(event); // move
}
eventNoHistory = obtainMotionEventNoHistoryOrSelf(eventNoHistory);
eventNoHistory.setAction(MotionEvent.ACTION_HOVER_EXIT);
super.dispatchHoverEvent(eventNoHistory); // exit
eventNoHistory.setAction(action);
}
mHoveredSelf = false;
}
if (newHoveredSelf) {
// Enter the view group.
if (action == MotionEvent.ACTION_HOVER_ENTER) {
// Send the enter as is.
handled |= super.dispatchHoverEvent(event); // enter
mHoveredSelf = true;
} else if (action == MotionEvent.ACTION_HOVER_MOVE) {
// Synthesize an enter from a move.
eventNoHistory = obtainMotionEventNoHistoryOrSelf(eventNoHistory);
eventNoHistory.setAction(MotionEvent.ACTION_HOVER_ENTER);
handled |= super.dispatchHoverEvent(eventNoHistory); // enter
eventNoHistory.setAction(action);
handled |= super.dispatchHoverEvent(eventNoHistory); // move
mHoveredSelf = true;
}
}
}
// Recycle the copy of the event that we made.
if (eventNoHistory != event) {
eventNoHistory.recycle();
}
// Done.
return handled;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "dispatchHoverEvent" | "@SuppressWarnings({"ConstantConditions"})
@Override
protected boolean dispatchHoverEvent(MotionEvent event) {
final int action = event.getAction();
// First check whether the view group wants to intercept the hover event.
final boolean interceptHover = onInterceptHoverEvent(event);
event.setAction(action); // restore action in case it was changed
MotionEvent eventNoHistory = event;
boolean handled = false;
// Send events to the hovered children and build a new list of hover targets until
// one is found that handles the event.
HoverTarget firstOldHoverTarget = mFirstHoverTarget;
mFirstHoverTarget = null;
if (!interceptHover && action != MotionEvent.ACTION_HOVER_EXIT) {
final float x = event.getX();
final float y = event.getY();
final int childrenCount = mChildrenCount;
if (childrenCount != 0) {
final View[] children = mChildren;
HoverTarget lastHoverTarget = null;
for (int i = childrenCount - 1; i >= 0; i--) {
final View child = children[i];
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
continue;
}
// Obtain a hover target for this child. Dequeue it from the
// old hover target list if the child was previously hovered.
HoverTarget hoverTarget = firstOldHoverTarget;
final boolean wasHovered;
for (HoverTarget predecessor = null; ;) {
if (hoverTarget == null) {
hoverTarget = HoverTarget.obtain(child);
wasHovered = false;
break;
}
if (hoverTarget.child == child) {
if (predecessor != null) {
predecessor.next = hoverTarget.next;
} else {
firstOldHoverTarget = hoverTarget.next;
}
hoverTarget.next = null;
wasHovered = true;
break;
}
predecessor = hoverTarget;
hoverTarget = hoverTarget.next;
}
// Enqueue the hover target onto the new hover target list.
if (lastHoverTarget != null) {
lastHoverTarget.next = hoverTarget;
} else {
<MASK>lastHoverTarget = hoverTarget;</MASK>
mFirstHoverTarget = hoverTarget;
}
// Dispatch the event to the child.
if (action == MotionEvent.ACTION_HOVER_ENTER) {
if (!wasHovered) {
// Send the enter as is.
handled |= dispatchTransformedGenericPointerEvent(
event, child); // enter
}
} else if (action == MotionEvent.ACTION_HOVER_MOVE) {
if (!wasHovered) {
// Synthesize an enter from a move.
eventNoHistory = obtainMotionEventNoHistoryOrSelf(eventNoHistory);
eventNoHistory.setAction(MotionEvent.ACTION_HOVER_ENTER);
handled |= dispatchTransformedGenericPointerEvent(
eventNoHistory, child); // enter
eventNoHistory.setAction(action);
handled |= dispatchTransformedGenericPointerEvent(
eventNoHistory, child); // move
} else {
// Send the move as is.
handled |= dispatchTransformedGenericPointerEvent(event, child);
}
}
if (handled) {
break;
}
}
}
}
// Send exit events to all previously hovered children that are no longer hovered.
while (firstOldHoverTarget != null) {
final View child = firstOldHoverTarget.child;
// Exit the old hovered child.
if (action == MotionEvent.ACTION_HOVER_EXIT) {
// Send the exit as is.
handled |= dispatchTransformedGenericPointerEvent(
event, child); // exit
} else {
// Synthesize an exit from a move or enter.
// Ignore the result because hover focus has moved to a different view.
if (action == MotionEvent.ACTION_HOVER_MOVE) {
dispatchTransformedGenericPointerEvent(
event, child); // move
}
eventNoHistory = obtainMotionEventNoHistoryOrSelf(eventNoHistory);
eventNoHistory.setAction(MotionEvent.ACTION_HOVER_EXIT);
dispatchTransformedGenericPointerEvent(
eventNoHistory, child); // exit
eventNoHistory.setAction(action);
}
final HoverTarget nextOldHoverTarget = firstOldHoverTarget.next;
firstOldHoverTarget.recycle();
firstOldHoverTarget = nextOldHoverTarget;
}
// Send events to the view group itself if no children have handled it.
boolean newHoveredSelf = !handled;
if (newHoveredSelf == mHoveredSelf) {
if (newHoveredSelf) {
// Send event to the view group as before.
handled |= super.dispatchHoverEvent(event);
}
} else {
if (mHoveredSelf) {
// Exit the view group.
if (action == MotionEvent.ACTION_HOVER_EXIT) {
// Send the exit as is.
handled |= super.dispatchHoverEvent(event); // exit
} else {
// Synthesize an exit from a move or enter.
// Ignore the result because hover focus is moving to a different view.
if (action == MotionEvent.ACTION_HOVER_MOVE) {
super.dispatchHoverEvent(event); // move
}
eventNoHistory = obtainMotionEventNoHistoryOrSelf(eventNoHistory);
eventNoHistory.setAction(MotionEvent.ACTION_HOVER_EXIT);
super.dispatchHoverEvent(eventNoHistory); // exit
eventNoHistory.setAction(action);
}
mHoveredSelf = false;
}
if (newHoveredSelf) {
// Enter the view group.
if (action == MotionEvent.ACTION_HOVER_ENTER) {
// Send the enter as is.
handled |= super.dispatchHoverEvent(event); // enter
mHoveredSelf = true;
} else if (action == MotionEvent.ACTION_HOVER_MOVE) {
// Synthesize an enter from a move.
eventNoHistory = obtainMotionEventNoHistoryOrSelf(eventNoHistory);
eventNoHistory.setAction(MotionEvent.ACTION_HOVER_ENTER);
handled |= super.dispatchHoverEvent(eventNoHistory); // enter
eventNoHistory.setAction(action);
handled |= super.dispatchHoverEvent(eventNoHistory); // move
mHoveredSelf = true;
}
}
}
// Recycle the copy of the event that we made.
if (eventNoHistory != event) {
eventNoHistory.recycle();
}
// Done.
return handled;
}" |
Inversion-Mutation | megadiff | "protected final void addInstance(Singleton instance)
throws IllegalStateException,
IllegalArgumentException,
InitializationException {
// TODO: Check that state equals INITIALIZING
// Check preconditions
MandatoryArgumentChecker.check("instance", instance);
_instances.add(instance);
boolean succeeded = false;
String className = instance.getClass().getName();
LOG.debug("Initializing instance of class \"" + className + "\".");
try {
// TODO: Use one instance of PropertiesPropertyReader
instance.init(new PropertiesPropertyReader(_initSettings));
succeeded = true;
} finally {
if (succeeded) {
LOG.info("Initialized instance of class \"" + className + "\".");
} else {
String message = "Failed to initialize instance of \"" + className + "\".";
LOG.error(message);
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addInstance" | "protected final void addInstance(Singleton instance)
throws IllegalStateException,
IllegalArgumentException,
InitializationException {
// TODO: Check that state equals INITIALIZING
// Check preconditions
MandatoryArgumentChecker.check("instance", instance);
_instances.add(instance);
boolean succeeded = false;
LOG.debug("Initializing instance of class \"" + className + "\".");
try {
// TODO: Use one instance of PropertiesPropertyReader
instance.init(new PropertiesPropertyReader(_initSettings));
succeeded = true;
} finally {
<MASK>String className = instance.getClass().getName();</MASK>
if (succeeded) {
LOG.info("Initialized instance of class \"" + className + "\".");
} else {
String message = "Failed to initialize instance of \"" + className + "\".";
LOG.error(message);
}
}
}" |
Inversion-Mutation | megadiff | "protected void sendRequest(MethodCall methodCall, Future future)
throws java.io.IOException, RenegotiateSessionException {
// Determines the body that is at the root of the subsystem from which the
// call was sent.
// It is always true that the body that issued the request (and not the body
// that is the target of the call) and this BodyProxy are in the same
// address space because being a local representative for something remote
// is what the proxy is all about. This is why we know that the table that
// can be accessed by using a static methode has this information.
ExceptionHandler.addRequest(methodCall, (FutureProxy) future);
sendRequest(methodCall, future,
LocalBodyStore.getInstance().getCurrentThreadBody());
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "sendRequest" | "protected void sendRequest(MethodCall methodCall, Future future)
throws java.io.IOException, RenegotiateSessionException {
// Determines the body that is at the root of the subsystem from which the
// call was sent.
// It is always true that the body that issued the request (and not the body
// that is the target of the call) and this BodyProxy are in the same
// address space because being a local representative for something remote
// is what the proxy is all about. This is why we know that the table that
// can be accessed by using a static methode has this information.
sendRequest(methodCall, future,
LocalBodyStore.getInstance().getCurrentThreadBody());
<MASK>ExceptionHandler.addRequest(methodCall, (FutureProxy) future);</MASK>
}" |
Inversion-Mutation | megadiff | "public void handlRequest(HttpServletRequest request,
HttpServletResponse response) {
printRequest(request);
String method = request.getParameter(ServiceConstant.METHOD);
CommonService obj = null;
try {
obj = CommonService.createServiceObjectByMethod(method);
} catch (InstantiationException e1) {
log
.severe("<handlRequest> but exception while create service object for method("
+ method + "), exception=" + e1.toString());
e1.printStackTrace();
} catch (IllegalAccessException e1) {
log
.severe("<handlRequest> but exception while create service object for method("
+ method + "), exception=" + e1.toString());
e1.printStackTrace();
}
try {
if (obj == null) {
sendResponseByErrorCode(response,
ErrorCode.ERROR_PARA_METHOD_NOT_FOUND);
return;
}
obj.setCassandraClient(cassandraClient);
obj.setRequest(request);
if (!obj.validateSecurity(request)) {
sendResponseByErrorCode(response,
ErrorCode.ERROR_INVALID_SECURITY);
return;
}
// parse request parameters
if (!obj.setDataFromRequest(request)) {
sendResponseByErrorCode(response, obj.resultCode);
return;
}
// print parameters
obj.printData();
// handle request
obj.handleData();
} catch (HectorException e) {
obj.resultCode = ErrorCode.ERROR_CASSANDRA;
log.severe("catch DB exception=" + e.toString());
e.printStackTrace();
} catch (JSONException e) {
obj.resultCode = ErrorCode.ERROR_JSON;
log.severe("catch JSON exception=" + e.toString());
e.printStackTrace();
} catch (Exception e) {
obj.resultCode = ErrorCode.ERROR_SYSTEM;
log.severe("catch general exception=" + e.toString());
e.printStackTrace();
} finally {
}
String responseData = obj.getResponseString();
// send back response
sendResponse(response, responseData);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handlRequest" | "public void handlRequest(HttpServletRequest request,
HttpServletResponse response) {
printRequest(request);
String method = request.getParameter(ServiceConstant.METHOD);
CommonService obj = null;
try {
obj = CommonService.createServiceObjectByMethod(method);
} catch (InstantiationException e1) {
log
.severe("<handlRequest> but exception while create service object for method("
+ method + "), exception=" + e1.toString());
e1.printStackTrace();
} catch (IllegalAccessException e1) {
log
.severe("<handlRequest> but exception while create service object for method("
+ method + "), exception=" + e1.toString());
e1.printStackTrace();
}
try {
if (obj == null) {
sendResponseByErrorCode(response,
ErrorCode.ERROR_PARA_METHOD_NOT_FOUND);
return;
}
obj.setCassandraClient(cassandraClient);
obj.setRequest(request);
if (!obj.validateSecurity(request)) {
sendResponseByErrorCode(response,
ErrorCode.ERROR_INVALID_SECURITY);
return;
}
// parse request parameters
<MASK>sendResponseByErrorCode(response, obj.resultCode);</MASK>
if (!obj.setDataFromRequest(request)) {
return;
}
// print parameters
obj.printData();
// handle request
obj.handleData();
} catch (HectorException e) {
obj.resultCode = ErrorCode.ERROR_CASSANDRA;
log.severe("catch DB exception=" + e.toString());
e.printStackTrace();
} catch (JSONException e) {
obj.resultCode = ErrorCode.ERROR_JSON;
log.severe("catch JSON exception=" + e.toString());
e.printStackTrace();
} catch (Exception e) {
obj.resultCode = ErrorCode.ERROR_SYSTEM;
log.severe("catch general exception=" + e.toString());
e.printStackTrace();
} finally {
}
String responseData = obj.getResponseString();
// send back response
sendResponse(response, responseData);
}" |
Inversion-Mutation | megadiff | "private DAVStatus sendRequest(String method, String path, Map header, InputStream requestBody) throws SVNException {
Map readHeader = new HashMap();
if (myUserCredentialsProvider != null) {
myUserCredentialsProvider.reset();
}
ISVNCredentials credentials = myLastUsedCredentials;
while (true) {
DAVStatus status = null;
try {
connect();
if (credentials != null) {
String auth = credentials.getName() + ":" + credentials.getPassword();
auth = Base64.byteArrayToBase64(auth.getBytes());
header.put("Authorization", "Basic " + auth);
}
sendHeader(method, path, header, requestBody);
logOutputStream();
readHeader.clear();
status = readHeader(readHeader);
} catch (IOException e) {
logOutputStream();
close();
acknowledgeSSLContext(false);
throw new SVNException(e);
}
acknowledgeSSLContext(true);
if (status != null
&& (status.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED || status.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN)) {
myLastUsedCredentials = null;
try {
skipRequestBody(readHeader);
} catch (IOException e1) {}
close();
String realm = getAuthRealm((String) readHeader.get("WWW-Authenticate"));
if (myUserCredentialsProvider == null) {
throw new SVNAuthenticationException("No credentials defined");
}
// get credentials and continue
if (credentials != null) {
myUserCredentialsProvider.notAccepted(credentials, "forbidden");
}
credentials = SVNUtil.nextCredentials(myUserCredentialsProvider, mySVNRepositoryLocation ,realm);
if (credentials == null) {
// no more to try.
throw new SVNAuthenticationException("Authentication failed");
}
// reset stream!
if (requestBody instanceof ByteArrayInputStream) {
((ByteArrayInputStream) requestBody).reset();
} else if (requestBody != null) {
throw new SVNAuthenticationException("Authentication failed");
}
} else if (status != null) {
if (credentials != null && myUserCredentialsProvider != null) {
myUserCredentialsProvider.accepted(credentials);
}
// remember creds
myLastUsedCredentials = credentials;
status.setResponseHeader(readHeader);
return status;
} else {
close();
throw new SVNException("can't connect");
}
if (credentials == null) {
close();
throw new SVNCancelException();
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "sendRequest" | "private DAVStatus sendRequest(String method, String path, Map header, InputStream requestBody) throws SVNException {
Map readHeader = new HashMap();
if (myUserCredentialsProvider != null) {
myUserCredentialsProvider.reset();
}
ISVNCredentials credentials = myLastUsedCredentials;
while (true) {
DAVStatus status = null;
try {
connect();
if (credentials != null) {
String auth = credentials.getName() + ":" + credentials.getPassword();
auth = Base64.byteArrayToBase64(auth.getBytes());
header.put("Authorization", "Basic " + auth);
}
sendHeader(method, path, header, requestBody);
readHeader.clear();
status = readHeader(readHeader);
<MASK>logOutputStream();</MASK>
} catch (IOException e) {
<MASK>logOutputStream();</MASK>
close();
acknowledgeSSLContext(false);
throw new SVNException(e);
}
acknowledgeSSLContext(true);
if (status != null
&& (status.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED || status.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN)) {
myLastUsedCredentials = null;
try {
skipRequestBody(readHeader);
} catch (IOException e1) {}
close();
String realm = getAuthRealm((String) readHeader.get("WWW-Authenticate"));
if (myUserCredentialsProvider == null) {
throw new SVNAuthenticationException("No credentials defined");
}
// get credentials and continue
if (credentials != null) {
myUserCredentialsProvider.notAccepted(credentials, "forbidden");
}
credentials = SVNUtil.nextCredentials(myUserCredentialsProvider, mySVNRepositoryLocation ,realm);
if (credentials == null) {
// no more to try.
throw new SVNAuthenticationException("Authentication failed");
}
// reset stream!
if (requestBody instanceof ByteArrayInputStream) {
((ByteArrayInputStream) requestBody).reset();
} else if (requestBody != null) {
throw new SVNAuthenticationException("Authentication failed");
}
} else if (status != null) {
if (credentials != null && myUserCredentialsProvider != null) {
myUserCredentialsProvider.accepted(credentials);
}
// remember creds
myLastUsedCredentials = credentials;
status.setResponseHeader(readHeader);
return status;
} else {
close();
throw new SVNException("can't connect");
}
if (credentials == null) {
close();
throw new SVNCancelException();
}
}
}" |
Inversion-Mutation | megadiff | "private void emphasis(TableDDDetails details) {
deEmphasis();
UIObject.setStyleName(getElement(), CLASSNAME + "-drag", true);
// iterate old and new emphasized row
for (Widget w : scrollBody.renderedRows) {
VScrollTableRow row = (VScrollTableRow) w;
if (details != null && details.overkey == row.rowKey) {
if (row != null) {
String stylename = ROWSTYLEBASE
+ details.dropLocation.toString().toLowerCase();
VScrollTableRow.setStyleName(row.getElement(),
stylename, true);
}
lastEmphasized = details;
return;
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "emphasis" | "private void emphasis(TableDDDetails details) {
deEmphasis();
// iterate old and new emphasized row
for (Widget w : scrollBody.renderedRows) {
VScrollTableRow row = (VScrollTableRow) w;
if (details != null && details.overkey == row.rowKey) {
if (row != null) {
String stylename = ROWSTYLEBASE
+ details.dropLocation.toString().toLowerCase();
VScrollTableRow.setStyleName(row.getElement(),
stylename, true);
}
lastEmphasized = details;
return;
}
}
<MASK>UIObject.setStyleName(getElement(), CLASSNAME + "-drag", true);</MASK>
}" |
Inversion-Mutation | megadiff | "protected void noteDocumentIngest(String outputConnectionName,
String docKey, String documentVersion,
String outputVersion, String authorityNameString,
long ingestTime, String documentURI, String documentURIHash)
throws ManifoldCFException
{
HashMap map = new HashMap();
while (true)
{
// The table can have at most one row per URI, for non-null URIs. It can also have at most one row per document identifier.
// However, for null URI's, multiple rows are allowed. Null URIs have a special meaning, which is that
// the document was not actually ingested.
// To make sure the constraints are enforced, we cannot simply look for the row and insert one if not found. This is because
// postgresql does not cause a lock to be created on rows that don't yet exist, so multiple transactions of the kind described
// can lead to multiple rows with the same key. Instead, we *could* lock the whole table down, but that would interfere with
// parallelism. The lowest-impact approach is to make sure an index constraint is in place, and first attempt to do an INSERT.
// That attempt will fail if a record already exists. Then, an update can be attempted.
//
// In the situation where the INSERT fails, the current transaction is aborted and a new transaction must be performed.
// This means that it is impossible to structure things so that the UPDATE is guaranteed to succeed. So, on the event of an
// INSERT failure, the UPDATE is tried, but if that fails too, then the INSERT is tried again. This should also handle the
// case where a DELETE in another transaction removes the database row before it can be UPDATEd.
//
// If the UPDATE does not appear to modify any rows, this is also a signal that the INSERT must be retried.
//
// Try the update first. Typically this succeeds except in the case where a doc is indexed for the first time.
map.clear();
map.put(lastVersionField,documentVersion);
map.put(lastOutputVersionField,outputVersion);
map.put(lastIngestField,new Long(ingestTime));
if (documentURI != null)
{
map.put(docURIField,documentURI);
map.put(uriHashField,documentURIHash);
}
if (authorityNameString != null)
map.put(authorityNameField,authorityNameString);
else
map.put(authorityNameField,"");
// Transaction abort due to deadlock should be retried here.
while (true)
{
long sleepAmt = 0L;
beginTransaction();
try
{
// Look for existing row.
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(docKeyField,docKey),
new UnitaryClause(outputConnNameField,outputConnectionName)});
IResultSet set = performQuery("SELECT "+idField+","+changeCountField+" FROM "+getTableName()+" WHERE "+
query+" FOR UPDATE",list,null,null);
IResultRow row = null;
if (set.getRowCount() > 0)
row = set.getRow(0);
if (row != null)
{
// Update the record
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(idField,row.getValue(idField))});
long changeCount = ((Long)row.getValue(changeCountField)).longValue();
changeCount++;
map.put(changeCountField,new Long(changeCount));
performUpdate(map,"WHERE "+query,list,null);
// Update successful!
performCommit();
return;
}
// Update failed to find a matching record, so try the insert
break;
}
catch (ManifoldCFException e)
{
signalRollback();
if (e.getErrorCode() == e.DATABASE_TRANSACTION_ABORT)
{
if (Logging.perf.isDebugEnabled())
Logging.perf.debug("Aborted transaction noting ingestion: "+e.getMessage());
sleepAmt = getSleepAmt();
continue;
}
throw e;
}
catch (Error e)
{
signalRollback();
throw e;
}
finally
{
endTransaction();
sleepFor(sleepAmt);
}
}
// Set up for insert
map.clear();
map.put(lastVersionField,documentVersion);
map.put(lastOutputVersionField,outputVersion);
map.put(lastIngestField,new Long(ingestTime));
if (documentURI != null)
{
map.put(docURIField,documentURI);
map.put(uriHashField,documentURIHash);
}
if (authorityNameString != null)
map.put(authorityNameField,authorityNameString);
else
map.put(authorityNameField,"");
Long id = new Long(IDFactory.make(threadContext));
map.put(idField,id);
map.put(outputConnNameField,outputConnectionName);
map.put(docKeyField,docKey);
map.put(changeCountField,new Long(1));
map.put(firstIngestField,map.get(lastIngestField));
beginTransaction();
try
{
performInsert(map,null);
noteModifications(1,0,0);
performCommit();
return;
}
catch (ManifoldCFException e)
{
signalRollback();
// If this is simply a constraint violation, we just want to fall through and try the update!
if (e.getErrorCode() != ManifoldCFException.DATABASE_TRANSACTION_ABORT)
throw e;
// Otherwise, exit transaction and fall through to 'update' attempt
}
catch (Error e)
{
signalRollback();
throw e;
}
finally
{
endTransaction();
}
// Insert must have failed. Attempt an update.
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "noteDocumentIngest" | "protected void noteDocumentIngest(String outputConnectionName,
String docKey, String documentVersion,
String outputVersion, String authorityNameString,
long ingestTime, String documentURI, String documentURIHash)
throws ManifoldCFException
{
HashMap map = new HashMap();
while (true)
{
// The table can have at most one row per URI, for non-null URIs. It can also have at most one row per document identifier.
// However, for null URI's, multiple rows are allowed. Null URIs have a special meaning, which is that
// the document was not actually ingested.
// To make sure the constraints are enforced, we cannot simply look for the row and insert one if not found. This is because
// postgresql does not cause a lock to be created on rows that don't yet exist, so multiple transactions of the kind described
// can lead to multiple rows with the same key. Instead, we *could* lock the whole table down, but that would interfere with
// parallelism. The lowest-impact approach is to make sure an index constraint is in place, and first attempt to do an INSERT.
// That attempt will fail if a record already exists. Then, an update can be attempted.
//
// In the situation where the INSERT fails, the current transaction is aborted and a new transaction must be performed.
// This means that it is impossible to structure things so that the UPDATE is guaranteed to succeed. So, on the event of an
// INSERT failure, the UPDATE is tried, but if that fails too, then the INSERT is tried again. This should also handle the
// case where a DELETE in another transaction removes the database row before it can be UPDATEd.
//
// If the UPDATE does not appear to modify any rows, this is also a signal that the INSERT must be retried.
//
// Try the update first. Typically this succeeds except in the case where a doc is indexed for the first time.
map.clear();
map.put(lastVersionField,documentVersion);
map.put(lastOutputVersionField,outputVersion);
map.put(lastIngestField,new Long(ingestTime));
if (documentURI != null)
{
map.put(docURIField,documentURI);
map.put(uriHashField,documentURIHash);
}
if (authorityNameString != null)
map.put(authorityNameField,authorityNameString);
else
map.put(authorityNameField,"");
// Transaction abort due to deadlock should be retried here.
while (true)
{
long sleepAmt = 0L;
beginTransaction();
try
{
// Look for existing row.
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(docKeyField,docKey),
new UnitaryClause(outputConnNameField,outputConnectionName)});
IResultSet set = performQuery("SELECT "+idField+","+changeCountField+" FROM "+getTableName()+" WHERE "+
query+" FOR UPDATE",list,null,null);
IResultRow row = null;
if (set.getRowCount() > 0)
row = set.getRow(0);
if (row != null)
{
// Update the record
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(idField,row.getValue(idField))});
long changeCount = ((Long)row.getValue(changeCountField)).longValue();
changeCount++;
map.put(changeCountField,new Long(changeCount));
performUpdate(map,"WHERE "+query,list,null);
// Update successful!
<MASK>performCommit();</MASK>
return;
}
// Update failed to find a matching record, so try the insert
<MASK>performCommit();</MASK>
break;
}
catch (ManifoldCFException e)
{
signalRollback();
if (e.getErrorCode() == e.DATABASE_TRANSACTION_ABORT)
{
if (Logging.perf.isDebugEnabled())
Logging.perf.debug("Aborted transaction noting ingestion: "+e.getMessage());
sleepAmt = getSleepAmt();
continue;
}
throw e;
}
catch (Error e)
{
signalRollback();
throw e;
}
finally
{
endTransaction();
sleepFor(sleepAmt);
}
}
// Set up for insert
map.clear();
map.put(lastVersionField,documentVersion);
map.put(lastOutputVersionField,outputVersion);
map.put(lastIngestField,new Long(ingestTime));
if (documentURI != null)
{
map.put(docURIField,documentURI);
map.put(uriHashField,documentURIHash);
}
if (authorityNameString != null)
map.put(authorityNameField,authorityNameString);
else
map.put(authorityNameField,"");
Long id = new Long(IDFactory.make(threadContext));
map.put(idField,id);
map.put(outputConnNameField,outputConnectionName);
map.put(docKeyField,docKey);
map.put(changeCountField,new Long(1));
map.put(firstIngestField,map.get(lastIngestField));
beginTransaction();
try
{
performInsert(map,null);
noteModifications(1,0,0);
return;
}
catch (ManifoldCFException e)
{
signalRollback();
// If this is simply a constraint violation, we just want to fall through and try the update!
if (e.getErrorCode() != ManifoldCFException.DATABASE_TRANSACTION_ABORT)
throw e;
// Otherwise, exit transaction and fall through to 'update' attempt
}
catch (Error e)
{
signalRollback();
throw e;
}
finally
{
endTransaction();
}
// Insert must have failed. Attempt an update.
}
}" |
Inversion-Mutation | megadiff | "public Object start(IApplicationContext appContext) {
try {
appContext.applicationRunning();
initializeProxySupport();
advisor = createInstallContext();
//fetch description of what to install
InstallDescription description = null;
try {
description = computeInstallDescription();
startRequiredBundles(description);
//perform long running install operation
InstallUpdateProductOperation operation = new InstallUpdateProductOperation(InstallerActivator.getDefault().getContext(), description);
IStatus result = advisor.performInstall(operation);
if (!result.isOK()) {
LogHelper.log(result);
advisor.setResult(result);
return IApplication.EXIT_OK;
}
//just exit after a successful update
if (!operation.isFirstInstall())
return IApplication.EXIT_OK;
if (canAutoStart(description))
launchProduct(description);
else {
//notify user that the product was installed
//TODO present the user an option to immediately start the product
advisor.setResult(result);
}
} catch (OperationCanceledException e) {
advisor.setResult(Status.CANCEL_STATUS);
} catch (Exception e) {
IStatus error = getStatus(e);
advisor.setResult(error);
LogHelper.log(error);
}
return IApplication.EXIT_OK;
} finally {
advisor.stop();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "start" | "public Object start(IApplicationContext appContext) {
try {
appContext.applicationRunning();
advisor = createInstallContext();
//fetch description of what to install
InstallDescription description = null;
try {
description = computeInstallDescription();
startRequiredBundles(description);
<MASK>initializeProxySupport();</MASK>
//perform long running install operation
InstallUpdateProductOperation operation = new InstallUpdateProductOperation(InstallerActivator.getDefault().getContext(), description);
IStatus result = advisor.performInstall(operation);
if (!result.isOK()) {
LogHelper.log(result);
advisor.setResult(result);
return IApplication.EXIT_OK;
}
//just exit after a successful update
if (!operation.isFirstInstall())
return IApplication.EXIT_OK;
if (canAutoStart(description))
launchProduct(description);
else {
//notify user that the product was installed
//TODO present the user an option to immediately start the product
advisor.setResult(result);
}
} catch (OperationCanceledException e) {
advisor.setResult(Status.CANCEL_STATUS);
} catch (Exception e) {
IStatus error = getStatus(e);
advisor.setResult(error);
LogHelper.log(error);
}
return IApplication.EXIT_OK;
} finally {
advisor.stop();
}
}" |
Inversion-Mutation | megadiff | "private void setViewStates(int mode) {
// Extra canModify check just in case
if (mode == Utils.MODIFY_UNINITIALIZED || !EditEventHelper.canModifyEvent(mModel)) {
setWhenString();
for (View v : mViewOnlyList) {
v.setVisibility(View.VISIBLE);
}
for (View v : mEditOnlyList) {
v.setVisibility(View.GONE);
}
for (View v : mEditViewList) {
v.setEnabled(false);
v.setBackgroundDrawable(null);
}
mCalendarSelectorGroup.setVisibility(View.GONE);
mCalendarStaticGroup.setVisibility(View.VISIBLE);
mRepeatsSpinner.setEnabled(false);
mRepeatsSpinner.setBackgroundDrawable(null);
if (EditEventHelper.canAddReminders(mModel)) {
mRemindersGroup.setVisibility(View.VISIBLE);
} else {
mRemindersGroup.setVisibility(View.GONE);
}
if (TextUtils.isEmpty(mLocationTextView.getText())) {
mLocationGroup.setVisibility(View.GONE);
}
if (TextUtils.isEmpty(mDescriptionTextView.getText())) {
mDescriptionGroup.setVisibility(View.GONE);
}
} else {
for (View v : mViewOnlyList) {
v.setVisibility(View.GONE);
}
for (View v : mEditOnlyList) {
v.setVisibility(View.VISIBLE);
}
for (View v : mEditViewList) {
v.setEnabled(true);
if (v.getTag() != null) {
v.setBackgroundDrawable((Drawable) v.getTag());
v.setPadding(mOriginalPadding[0], mOriginalPadding[1], mOriginalPadding[2],
mOriginalPadding[3]);
}
}
if (mModel.mUri == null) {
mCalendarSelectorGroup.setVisibility(View.VISIBLE);
mCalendarStaticGroup.setVisibility(View.GONE);
} else {
mCalendarSelectorGroup.setVisibility(View.GONE);
mCalendarStaticGroup.setVisibility(View.VISIBLE);
}
mRepeatsSpinner.setBackgroundDrawable((Drawable) mRepeatsSpinner.getTag());
mRepeatsSpinner.setPadding(mOriginalSpinnerPadding[0], mOriginalSpinnerPadding[1],
mOriginalSpinnerPadding[2], mOriginalSpinnerPadding[3]);
if (mModel.mOriginalSyncId == null) {
mRepeatsSpinner.setEnabled(true);
} else {
mRepeatsSpinner.setEnabled(false);
}
mRemindersGroup.setVisibility(View.VISIBLE);
mLocationGroup.setVisibility(View.VISIBLE);
mDescriptionGroup.setVisibility(View.VISIBLE);
}
setAllDayViewsVisibility(mAllDayCheckBox.isChecked());
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setViewStates" | "private void setViewStates(int mode) {
// Extra canModify check just in case
if (mode == Utils.MODIFY_UNINITIALIZED || !EditEventHelper.canModifyEvent(mModel)) {
setWhenString();
for (View v : mViewOnlyList) {
v.setVisibility(View.VISIBLE);
}
for (View v : mEditOnlyList) {
v.setVisibility(View.GONE);
}
for (View v : mEditViewList) {
v.setEnabled(false);
v.setBackgroundDrawable(null);
}
mCalendarSelectorGroup.setVisibility(View.GONE);
mCalendarStaticGroup.setVisibility(View.VISIBLE);
mRepeatsSpinner.setEnabled(false);
mRepeatsSpinner.setBackgroundDrawable(null);
<MASK>setAllDayViewsVisibility(mAllDayCheckBox.isChecked());</MASK>
if (EditEventHelper.canAddReminders(mModel)) {
mRemindersGroup.setVisibility(View.VISIBLE);
} else {
mRemindersGroup.setVisibility(View.GONE);
}
if (TextUtils.isEmpty(mLocationTextView.getText())) {
mLocationGroup.setVisibility(View.GONE);
}
if (TextUtils.isEmpty(mDescriptionTextView.getText())) {
mDescriptionGroup.setVisibility(View.GONE);
}
} else {
for (View v : mViewOnlyList) {
v.setVisibility(View.GONE);
}
for (View v : mEditOnlyList) {
v.setVisibility(View.VISIBLE);
}
for (View v : mEditViewList) {
v.setEnabled(true);
if (v.getTag() != null) {
v.setBackgroundDrawable((Drawable) v.getTag());
v.setPadding(mOriginalPadding[0], mOriginalPadding[1], mOriginalPadding[2],
mOriginalPadding[3]);
}
}
if (mModel.mUri == null) {
mCalendarSelectorGroup.setVisibility(View.VISIBLE);
mCalendarStaticGroup.setVisibility(View.GONE);
} else {
mCalendarSelectorGroup.setVisibility(View.GONE);
mCalendarStaticGroup.setVisibility(View.VISIBLE);
}
mRepeatsSpinner.setBackgroundDrawable((Drawable) mRepeatsSpinner.getTag());
mRepeatsSpinner.setPadding(mOriginalSpinnerPadding[0], mOriginalSpinnerPadding[1],
mOriginalSpinnerPadding[2], mOriginalSpinnerPadding[3]);
if (mModel.mOriginalSyncId == null) {
mRepeatsSpinner.setEnabled(true);
} else {
mRepeatsSpinner.setEnabled(false);
}
mRemindersGroup.setVisibility(View.VISIBLE);
mLocationGroup.setVisibility(View.VISIBLE);
mDescriptionGroup.setVisibility(View.VISIBLE);
}
}" |
Inversion-Mutation | megadiff | "public static List<Element> handlePropertyName(String[] propertyNames,
ServiceContext context, boolean freq, int maxRecords, String cswServiceSpecificConstraint, LuceneConfig luceneConfig) throws Exception {
List<Element> domainValuesList = new ArrayList<Element>();
if(Log.isDebugEnabled(Geonet.CSW))
Log.debug(Geonet.CSW,"Handling property names '"+Arrays.toString(propertyNames)+"' with max records of "+maxRecords);
for (int i=0; i < propertyNames.length; i++) {
// Initialize list of values element.
Element listOfValues = null;
// Generate DomainValues element
Element domainValues = new Element("DomainValues", Csw.NAMESPACE_CSW);
// FIXME what should be the type ???
domainValues.setAttribute("type", "csw:Record");
String property = propertyNames[i].trim();
// Set propertyName in any case.
Element pn = new Element("PropertyName", Csw.NAMESPACE_CSW);
domainValues.addContent(pn.setText(property));
GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
SearchManager sm = gc.getBean(SearchManager.class);
IndexAndTaxonomy indexAndTaxonomy= sm.getNewIndexReader(null);
try {
GeonetworkMultiReader reader = indexAndTaxonomy.indexReader;
BooleanQuery groupsQuery = (BooleanQuery) CatalogSearcher.getGroupsQuery(context);
BooleanQuery query = null;
// Apply CSW service specific constraint
if (StringUtils.isNotEmpty(cswServiceSpecificConstraint)) {
Query constraintQuery = CatalogSearcher.getCswServiceSpecificConstraintQuery(cswServiceSpecificConstraint, luceneConfig);
query = new BooleanQuery();
BooleanClause.Occur occur = LuceneUtils
.convertRequiredAndProhibitedToOccur(true, false);
query.add(groupsQuery, occur);
query.add(constraintQuery, occur);
} else {
query = groupsQuery;
}
List<Pair<String, Boolean>> sortFields = Collections.singletonList(Pair.read(Geonet.SearchResult.SortBy.RELEVANCE, true));
Sort sort = LuceneSearcher.makeSort(sortFields, context.getLanguage(), false);
CachingWrapperFilter filter = null;
Pair<TopDocs,Element> searchResults = LuceneSearcher.doSearchAndMakeSummary(
maxRecords, 0, maxRecords, context.getLanguage(),
null, reader,
query, filter, sort, null, false, false,
false, false // Scoring is useless for GetDomain operation
);
TopDocs hits = searchResults.one();
try {
// Get mapped lucene field in CSW configuration
String indexField = CatalogConfiguration.getFieldMapping().get(
property.toLowerCase());
if (indexField != null)
property = indexField;
// check if params asked is in the index using getFieldNames ?
@SuppressWarnings("resource")
FieldInfos fi = new SlowCompositeReaderWrapper(reader).getFieldInfos();
if (fi.fieldInfo(property) == null)
continue;
boolean isRange = false;
if (CatalogConfiguration.getGetRecordsRangeFields().contains(
property))
isRange = true;
if (isRange)
listOfValues = new Element("RangeOfValues", Csw.NAMESPACE_CSW);
else
listOfValues = new Element("ListOfValues", Csw.NAMESPACE_CSW);
Set<String> fields = new HashSet<String>();
fields.add(property);
fields.add("_isTemplate");
// parse each document in the index
String[] fieldValues;
SortedSet<String> sortedValues = new TreeSet<String>();
ObjectKeyIntOpenHashMap duplicateValues = new ObjectKeyIntOpenHashMap();
for (int j = 0; j < hits.scoreDocs.length; j++) {
DocumentStoredFieldVisitor selector = new DocumentStoredFieldVisitor(fields);
reader.document(hits.scoreDocs[j].doc, selector);
Document doc = selector.getDocument();
// Skip templates and subTemplates
String[] isTemplate = doc.getValues("_isTemplate");
if (isTemplate[0] != null && !isTemplate[0].equals("n"))
continue;
// Get doc values for specified property
fieldValues = doc.getValues(property);
if (fieldValues == null)
continue;
addtoSortedSet(sortedValues, fieldValues, duplicateValues);
}
SummaryComparator valuesComparator = new SummaryComparator(SortOption.FREQUENCY, Type.STRING, context.getLanguage(), null);
TreeSet<SummaryComparator.SummaryElement> sortedValuesFrequency = new TreeSet<SummaryComparator.SummaryElement>(valuesComparator);
ObjectKeyIntMapIterator entries = duplicateValues.entries();
while(entries.hasNext()) {
entries.next();
sortedValuesFrequency.add(new SummaryComparator.SummaryElement(entries));
}
if (freq)
return createValuesByFrequency(sortedValuesFrequency);
else
listOfValues.addContent(createValuesElement(sortedValues, isRange));
} finally {
// any children means that the catalog was unable to determine
// anything about the specified parameter
if (listOfValues!= null && listOfValues.getChildren().size() != 0)
domainValues.addContent(listOfValues);
// Add current DomainValues to the list
domainValuesList.add(domainValues);
}
} finally {
sm.releaseIndexReader(indexAndTaxonomy);
}
}
return domainValuesList;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handlePropertyName" | "public static List<Element> handlePropertyName(String[] propertyNames,
ServiceContext context, boolean freq, int maxRecords, String cswServiceSpecificConstraint, LuceneConfig luceneConfig) throws Exception {
List<Element> domainValuesList = new ArrayList<Element>();
if(Log.isDebugEnabled(Geonet.CSW))
Log.debug(Geonet.CSW,"Handling property names '"+Arrays.toString(propertyNames)+"' with max records of "+maxRecords);
for (int i=0; i < propertyNames.length; i++) {
// Initialize list of values element.
Element listOfValues = null;
// Generate DomainValues element
Element domainValues = new Element("DomainValues", Csw.NAMESPACE_CSW);
// FIXME what should be the type ???
domainValues.setAttribute("type", "csw:Record");
String property = propertyNames[i].trim();
// Set propertyName in any case.
Element pn = new Element("PropertyName", Csw.NAMESPACE_CSW);
domainValues.addContent(pn.setText(property));
GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
SearchManager sm = gc.getBean(SearchManager.class);
IndexAndTaxonomy indexAndTaxonomy= sm.getNewIndexReader(null);
try {
GeonetworkMultiReader reader = indexAndTaxonomy.indexReader;
BooleanQuery groupsQuery = (BooleanQuery) CatalogSearcher.getGroupsQuery(context);
BooleanQuery query = null;
// Apply CSW service specific constraint
if (StringUtils.isNotEmpty(cswServiceSpecificConstraint)) {
Query constraintQuery = CatalogSearcher.getCswServiceSpecificConstraintQuery(cswServiceSpecificConstraint, luceneConfig);
query = new BooleanQuery();
BooleanClause.Occur occur = LuceneUtils
.convertRequiredAndProhibitedToOccur(true, false);
query.add(groupsQuery, occur);
query.add(constraintQuery, occur);
} else {
query = groupsQuery;
}
List<Pair<String, Boolean>> sortFields = Collections.singletonList(Pair.read(Geonet.SearchResult.SortBy.RELEVANCE, true));
Sort sort = LuceneSearcher.makeSort(sortFields, context.getLanguage(), false);
CachingWrapperFilter filter = null;
Pair<TopDocs,Element> searchResults = LuceneSearcher.doSearchAndMakeSummary(
maxRecords, 0, maxRecords, context.getLanguage(),
null, reader,
query, filter, sort, null, false, false,
false, false // Scoring is useless for GetDomain operation
);
TopDocs hits = searchResults.one();
try {
// Get mapped lucene field in CSW configuration
String indexField = CatalogConfiguration.getFieldMapping().get(
property.toLowerCase());
if (indexField != null)
property = indexField;
// check if params asked is in the index using getFieldNames ?
@SuppressWarnings("resource")
FieldInfos fi = new SlowCompositeReaderWrapper(reader).getFieldInfos();
if (fi.fieldInfo(property) == null)
continue;
boolean isRange = false;
if (CatalogConfiguration.getGetRecordsRangeFields().contains(
property))
isRange = true;
if (isRange)
listOfValues = new Element("RangeOfValues", Csw.NAMESPACE_CSW);
else
listOfValues = new Element("ListOfValues", Csw.NAMESPACE_CSW);
Set<String> fields = new HashSet<String>();
fields.add(property);
fields.add("_isTemplate");
// parse each document in the index
String[] fieldValues;
SortedSet<String> sortedValues = new TreeSet<String>();
ObjectKeyIntOpenHashMap duplicateValues = new ObjectKeyIntOpenHashMap();
for (int j = 0; j < hits.scoreDocs.length; j++) {
DocumentStoredFieldVisitor selector = new DocumentStoredFieldVisitor(fields);
reader.document(hits.scoreDocs[j].doc, selector);
Document doc = selector.getDocument();
// Skip templates and subTemplates
String[] isTemplate = doc.getValues("_isTemplate");
if (isTemplate[0] != null && !isTemplate[0].equals("n"))
continue;
// Get doc values for specified property
fieldValues = doc.getValues(property);
if (fieldValues == null)
continue;
addtoSortedSet(sortedValues, fieldValues, duplicateValues);
}
SummaryComparator valuesComparator = new SummaryComparator(SortOption.FREQUENCY, Type.STRING, context.getLanguage(), null);
TreeSet<SummaryComparator.SummaryElement> sortedValuesFrequency = new TreeSet<SummaryComparator.SummaryElement>(valuesComparator);
ObjectKeyIntMapIterator entries = duplicateValues.entries();
while(entries.hasNext()) {
<MASK>sortedValuesFrequency.add(new SummaryComparator.SummaryElement(entries));</MASK>
entries.next();
}
if (freq)
return createValuesByFrequency(sortedValuesFrequency);
else
listOfValues.addContent(createValuesElement(sortedValues, isRange));
} finally {
// any children means that the catalog was unable to determine
// anything about the specified parameter
if (listOfValues!= null && listOfValues.getChildren().size() != 0)
domainValues.addContent(listOfValues);
// Add current DomainValues to the list
domainValuesList.add(domainValues);
}
} finally {
sm.releaseIndexReader(indexAndTaxonomy);
}
}
return domainValuesList;
}" |
Inversion-Mutation | megadiff | "private int readMessages(ClientSession session, ClientConsumer consumer, SimpleString queue) throws MessagingException
{
session.start();
int msgs = 0;
ClientMessage msg = null;
do
{
msg = consumer.receive(1000);
if (msg != null)
{
msg.processed();
if (++msgs % 10000 == 0)
{
System.out.println("received " + msgs);
session.commit();
}
}
}
while (msg != null);
session.commit();
return msgs;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "readMessages" | "private int readMessages(ClientSession session, ClientConsumer consumer, SimpleString queue) throws MessagingException
{
session.start();
int msgs = 0;
ClientMessage msg = null;
do
{
msg = consumer.receive(1000);
<MASK>msg.processed();</MASK>
if (msg != null)
{
if (++msgs % 10000 == 0)
{
System.out.println("received " + msgs);
session.commit();
}
}
}
while (msg != null);
session.commit();
return msgs;
}" |
Inversion-Mutation | megadiff | "public synchronized void setCurrentFolder(AbstractFile folder, AbstractFile children[]) {
AbstractFile current; // Current folder.
FileSet markedFiles; // Buffer for all previously marked file.
AbstractFile selectedFile; // Buffer for the previously selected file.
// Stop quick search in case it was being used before folder change
quickSearch.cancel();
current = getCurrentFolder();
currentFolder = folder;
// If we're refreshing the current folder, save the current selection and marked files
// in order to restore them properly.
markedFiles = null;
selectedFile = null;
if(current != null && folder.equals(current)) {
markedFiles = tableModel.getMarkedFiles();
selectedFile = getSelectedFile();
}
// If we're navigating to the current folder's parent, we must select
// the current folder.
else if(tableModel.hasParentFolder() && folder.equals(tableModel.getParentFolder()))
selectedFile = current;
// Changes the current folder in the swing thread to make sure that repaints cannot
// happen in the middle of the operation - this is used to prevent flickers, baddly
// refreshed frames and such unpleasant graphical artifacts.
SwingUtilities.invokeLater(new FolderChangeThread(folder, children, markedFiles, selectedFile));
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setCurrentFolder" | "public synchronized void setCurrentFolder(AbstractFile folder, AbstractFile children[]) {
AbstractFile current; // Current folder.
FileSet markedFiles; // Buffer for all previously marked file.
AbstractFile selectedFile; // Buffer for the previously selected file.
// Stop quick search in case it was being used before folder change
quickSearch.cancel();
<MASK>currentFolder = folder;</MASK>
current = getCurrentFolder();
// If we're refreshing the current folder, save the current selection and marked files
// in order to restore them properly.
markedFiles = null;
selectedFile = null;
if(current != null && folder.equals(current)) {
markedFiles = tableModel.getMarkedFiles();
selectedFile = getSelectedFile();
}
// If we're navigating to the current folder's parent, we must select
// the current folder.
else if(tableModel.hasParentFolder() && folder.equals(tableModel.getParentFolder()))
selectedFile = current;
// Changes the current folder in the swing thread to make sure that repaints cannot
// happen in the middle of the operation - this is used to prevent flickers, baddly
// refreshed frames and such unpleasant graphical artifacts.
SwingUtilities.invokeLater(new FolderChangeThread(folder, children, markedFiles, selectedFile));
}" |
Inversion-Mutation | megadiff | "public boolean install() {
boolean result = super.install();
if (result) {
result &= super.addSupportedMetrics(
this.getDescription(),
"SKEL",
MetricType.Type.SOURCE_CODE);
}
return result;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "install" | "public boolean install() {
boolean result = super.install();
if (result) {
result &= super.addSupportedMetrics(
<MASK>"SKEL",</MASK>
this.getDescription(),
MetricType.Type.SOURCE_CODE);
}
return result;
}" |
Inversion-Mutation | megadiff | "public static Resolution invokeEventHandler(ExecutionContext ctx) throws Exception {
final Configuration config = StripesFilter.getConfiguration();
final Method handler = ctx.getHandler();
final ActionBean bean = ctx.getActionBean();
// Finally execute the handler method!
ctx.setLifecycleStage(LifecycleStage.EventHandling);
ctx.setInterceptors(config.getInterceptors(LifecycleStage.EventHandling));
return ctx.wrap( new Interceptor() {
public Resolution intercept(ExecutionContext ctx) throws Exception {
Object returnValue = handler.invoke(bean);
fillInValidationErrors(ctx);
if (returnValue != null && returnValue instanceof Resolution) {
ctx.setResolutionFromHandler(true);
return (Resolution) returnValue;
}
else if (returnValue != null) {
log.warn("Expected handler method ", handler.getName(), " on class ",
bean.getClass().getSimpleName(), " to return a Resolution. Instead it ",
"returned: ", returnValue);
}
return null;
}
});
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "invokeEventHandler" | "public static Resolution invokeEventHandler(ExecutionContext ctx) throws Exception {
final Configuration config = StripesFilter.getConfiguration();
final Method handler = ctx.getHandler();
final ActionBean bean = ctx.getActionBean();
// Finally execute the handler method!
ctx.setLifecycleStage(LifecycleStage.EventHandling);
ctx.setInterceptors(config.getInterceptors(LifecycleStage.EventHandling));
return ctx.wrap( new Interceptor() {
public Resolution intercept(ExecutionContext ctx) throws Exception {
Object returnValue = handler.invoke(bean);
if (returnValue != null && returnValue instanceof Resolution) {
ctx.setResolutionFromHandler(true);
return (Resolution) returnValue;
}
else if (returnValue != null) {
log.warn("Expected handler method ", handler.getName(), " on class ",
bean.getClass().getSimpleName(), " to return a Resolution. Instead it ",
"returned: ", returnValue);
}
<MASK>fillInValidationErrors(ctx);</MASK>
return null;
}
});
}" |
Inversion-Mutation | megadiff | "public Resolution intercept(ExecutionContext ctx) throws Exception {
Object returnValue = handler.invoke(bean);
fillInValidationErrors(ctx);
if (returnValue != null && returnValue instanceof Resolution) {
ctx.setResolutionFromHandler(true);
return (Resolution) returnValue;
}
else if (returnValue != null) {
log.warn("Expected handler method ", handler.getName(), " on class ",
bean.getClass().getSimpleName(), " to return a Resolution. Instead it ",
"returned: ", returnValue);
}
return null;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "intercept" | "public Resolution intercept(ExecutionContext ctx) throws Exception {
Object returnValue = handler.invoke(bean);
if (returnValue != null && returnValue instanceof Resolution) {
ctx.setResolutionFromHandler(true);
return (Resolution) returnValue;
}
else if (returnValue != null) {
log.warn("Expected handler method ", handler.getName(), " on class ",
bean.getClass().getSimpleName(), " to return a Resolution. Instead it ",
"returned: ", returnValue);
}
<MASK>fillInValidationErrors(ctx);</MASK>
return null;
}" |
Inversion-Mutation | megadiff | "public void dispose()
{
if ( !disposed )
{
if ( contentProvider != null )
{
contentProvider.dispose();
contentProvider = null;
}
if ( labelProvider != null )
{
labelProvider.dispose();
labelProvider = null;
}
if ( contextMenuManager != null )
{
contextMenuManager.dispose();
contextMenuManager = null;
}
disposed = true;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "dispose" | "public void dispose()
{
if ( !disposed )
{
if ( contentProvider != null )
{
contentProvider.dispose();
contentProvider = null;
}
if ( labelProvider != null )
{
labelProvider.dispose();
labelProvider = null;
}
if ( contextMenuManager != null )
{
<MASK>contextMenuManager = null;</MASK>
contextMenuManager.dispose();
}
disposed = true;
}
}" |
Inversion-Mutation | megadiff | "public void initProcess(List<String> command, String workingDirectory) throws Throwable {
String[] argv = command.toArray(new String[command.size()]);
String executable = argv[0];
markAsLoginShellIfDefault(argv);
ptyProcess = new PTYProcess(executable, argv, workingDirectory);
writerExecutor = ThreadUtilities.newSingleThreadExecutor(makeThreadName("Writer"));
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "initProcess" | "public void initProcess(List<String> command, String workingDirectory) throws Throwable {
String[] argv = command.toArray(new String[command.size()]);
String executable = argv[0];
markAsLoginShellIfDefault(argv);
<MASK>writerExecutor = ThreadUtilities.newSingleThreadExecutor(makeThreadName("Writer"));</MASK>
ptyProcess = new PTYProcess(executable, argv, workingDirectory);
}" |
Inversion-Mutation | megadiff | "public File saveBuild(Jar jar) throws Exception {
try {
String bsn = jar.getName();
File f = getOutputFile(bsn);
String msg = "";
if (!f.exists() || f.lastModified() < jar.lastModified()) {
reportNewer(f.lastModified(), jar);
f.delete();
if (!f.getParentFile().isDirectory())
f.getParentFile().mkdirs();
jar.write(f);
getWorkspace().changedFile(f);
} else {
msg = "(not modified since " + new Date(f.lastModified()) + ")";
}
trace(jar.getName() + " (" + f.getName() + ") " + jar.getResources().size() + " " + msg);
return f;
} finally {
jar.close();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "saveBuild" | "public File saveBuild(Jar jar) throws Exception {
try {
String bsn = jar.getName();
File f = getOutputFile(bsn);
String msg = "";
if (!f.exists() || f.lastModified() < jar.lastModified()) {
reportNewer(f.lastModified(), jar);
f.delete();
<MASK>jar.write(f);</MASK>
if (!f.getParentFile().isDirectory())
f.getParentFile().mkdirs();
getWorkspace().changedFile(f);
} else {
msg = "(not modified since " + new Date(f.lastModified()) + ")";
}
trace(jar.getName() + " (" + f.getName() + ") " + jar.getResources().size() + " " + msg);
return f;
} finally {
jar.close();
}
}" |
Inversion-Mutation | megadiff | "public Component getTableCellRendererComponent(
final JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int col) {
value = formatField(value);
TableColumn tableColumn = table.getColumnModel().getColumn(col);
JLabel label = (JLabel)super.getTableCellRendererComponent(table, value,
isSelected, hasFocus, row, col);
//chainsawcolumns uses one-based indexing
int colIndex = tableColumn.getModelIndex() + 1;
EventContainer container = (EventContainer) table.getModel();
ExtendedLoggingEvent loggingEvent = container.getRow(row);
//no event, use default renderer
if (loggingEvent == null) {
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
}
Map matches = loggingEvent.getSearchMatches();
JComponent component;
switch (colIndex) {
case ChainsawColumns.INDEX_THROWABLE_COL_NAME:
if (value instanceof String[] && ((String[])value).length > 0){
Style tabStyle = singleLineTextPane.getLogicalStyle();
StyleConstants.setTabSet(tabStyle, tabs);
//set the 1st tab at position 3
singleLineTextPane.setLogicalStyle(tabStyle);
//exception string is split into an array..just highlight the first line completely if anything in the exception matches if we have a match for the exception field
Set exceptionMatches = (Set)matches.get(LoggingEventFieldResolver.EXCEPTION_FIELD);
if (exceptionMatches != null && exceptionMatches.size() > 0) {
singleLineTextPane.setText(((String[])value)[0]);
boldAll((StyledDocument) singleLineTextPane.getDocument());
} else {
singleLineTextPane.setText(((String[])value)[0]);
}
} else {
singleLineTextPane.setText("");
}
component = generalPanel;
break;
case ChainsawColumns.INDEX_LOGGER_COL_NAME:
String logger = value.toString();
int startPos = -1;
for (int i = 0; i < loggerPrecision; i++) {
startPos = logger.indexOf(".", startPos + 1);
if (startPos < 0) {
break;
}
}
singleLineTextPane.setText(logger.substring(startPos + 1));
setHighlightAttributesInternal(matches.get(LoggingEventFieldResolver.LOGGER_FIELD), (StyledDocument) singleLineTextPane.getDocument());
component = generalPanel;
break;
case ChainsawColumns.INDEX_ID_COL_NAME:
singleLineTextPane.setText(value.toString());
setHighlightAttributesInternal(matches.get(LoggingEventFieldResolver.PROP_FIELD + "LOG4JID"), (StyledDocument) singleLineTextPane.getDocument());
component = generalPanel;
break;
case ChainsawColumns.INDEX_CLASS_COL_NAME:
singleLineTextPane.setText(value.toString());
setHighlightAttributesInternal(matches.get(LoggingEventFieldResolver.CLASS_FIELD), (StyledDocument) singleLineTextPane.getDocument());
component = generalPanel;
break;
case ChainsawColumns.INDEX_FILE_COL_NAME:
singleLineTextPane.setText(value.toString());
setHighlightAttributesInternal(matches.get(LoggingEventFieldResolver.FILE_FIELD), (StyledDocument) singleLineTextPane.getDocument());
component = generalPanel;
break;
case ChainsawColumns.INDEX_LINE_COL_NAME:
singleLineTextPane.setText(value.toString());
setHighlightAttributesInternal(matches.get(LoggingEventFieldResolver.LINE_FIELD), (StyledDocument) singleLineTextPane.getDocument());
component = generalPanel;
break;
case ChainsawColumns.INDEX_NDC_COL_NAME:
singleLineTextPane.setText(value.toString());
setHighlightAttributesInternal(matches.get(LoggingEventFieldResolver.NDC_FIELD), (StyledDocument) singleLineTextPane.getDocument());
component = generalPanel;
break;
case ChainsawColumns.INDEX_THREAD_COL_NAME:
singleLineTextPane.setText(value.toString());
setHighlightAttributesInternal(matches.get(LoggingEventFieldResolver.THREAD_FIELD), (StyledDocument) singleLineTextPane.getDocument());
component = generalPanel;
break;
case ChainsawColumns.INDEX_TIMESTAMP_COL_NAME:
//timestamp matches contain the millis..not the display text..just highlight if we have a match for the timestamp field
Set timestampMatches = (Set)matches.get(LoggingEventFieldResolver.TIMESTAMP_FIELD);
if (timestampMatches != null && timestampMatches.size() > 0) {
singleLineTextPane.setText(value.toString());
boldAll((StyledDocument) singleLineTextPane.getDocument());
} else {
singleLineTextPane.setText(value.toString());
}
component = generalPanel;
break;
case ChainsawColumns.INDEX_METHOD_COL_NAME:
singleLineTextPane.setText(value.toString());
setHighlightAttributesInternal(matches.get(LoggingEventFieldResolver.METHOD_FIELD), (StyledDocument) singleLineTextPane.getDocument());
component = generalPanel;
break;
case ChainsawColumns.INDEX_LOG4J_MARKER_COL_NAME:
case ChainsawColumns.INDEX_MESSAGE_COL_NAME:
String thisString = value.toString().trim();
multiLineTextPane.setText(thisString);
int width = tableColumn.getWidth();
if (colIndex == ChainsawColumns.INDEX_LOG4J_MARKER_COL_NAME) {
//property keys are set as all uppercase
setHighlightAttributesInternal(matches.get(LoggingEventFieldResolver.PROP_FIELD + ChainsawConstants.LOG4J_MARKER_COL_NAME_LOWERCASE.toUpperCase()), (StyledDocument) multiLineTextPane.getDocument());
} else {
setHighlightAttributesInternal(matches.get(LoggingEventFieldResolver.MSG_FIELD), (StyledDocument) multiLineTextPane.getDocument());
}
int tableRowHeight = table.getRowHeight(row);
multiLinePanel.removeAll();
multiLinePanel.add(multiLineTextPane);
if (wrap) {
Map paramMap = new HashMap();
paramMap.put(TextAttribute.FONT, multiLineTextPane.getFont());
int calculatedHeight = calculateHeight(thisString, width, paramMap);
//set preferred size to default height
multiLineTextPane.setSize(new Dimension(width, calculatedHeight));
int multiLinePanelPrefHeight = multiLinePanel.getPreferredSize().height;
if(tableRowHeight < multiLinePanelPrefHeight) {
table.setRowHeight(row, Math.max(ChainsawConstants.DEFAULT_ROW_HEIGHT, multiLinePanelPrefHeight));
}
}
component = multiLinePanel;
break;
case ChainsawColumns.INDEX_LEVEL_COL_NAME:
if (levelUseIcons) {
levelTextPane.setText("");
levelTextPane.insertIcon((Icon) iconMap.get(value.toString()));
if (!toolTipsVisible) {
levelTextPane.setToolTipText(value.toString());
}
} else {
levelTextPane.setText(value.toString());
setHighlightAttributesInternal(matches.get(LoggingEventFieldResolver.LEVEL_FIELD), (StyledDocument) levelTextPane.getDocument());
if (!toolTipsVisible) {
levelTextPane.setToolTipText(null);
}
}
if (toolTipsVisible) {
levelTextPane.setToolTipText(label.getToolTipText());
}
levelTextPane.setForeground(label.getForeground());
levelTextPane.setBackground(label.getBackground());
component = levelPanel;
break;
//remaining entries are properties
default:
Set propertySet = loggingEvent.getPropertyKeySet();
String headerName = tableColumn.getHeaderValue().toString().toLowerCase();
String thisProp = null;
//find the property in the property set...case-sensitive
for (Iterator iter = propertySet.iterator();iter.hasNext();) {
String entry = iter.next().toString();
if (entry.toLowerCase().equals(headerName)) {
thisProp = entry;
break;
}
}
if (thisProp != null) {
String propKey = LoggingEventFieldResolver.PROP_FIELD + thisProp.toUpperCase();
Set propKeyMatches = (Set)matches.get(propKey);
singleLineTextPane.setText(loggingEvent.getProperty(thisProp));
setHighlightAttributesInternal(propKeyMatches, (StyledDocument) singleLineTextPane.getDocument());
} else {
singleLineTextPane.setText("");
}
component = generalPanel;
break;
}
Color background;
Color foreground;
Rule loggerRule = colorizer.getLoggerRule();
//use logger colors in table instead of event colors if event passes logger rule
if (loggerRule != null && loggerRule.evaluate(loggingEvent, null)) {
background = applicationPreferenceModel.getSearchBackgroundColor();
foreground = applicationPreferenceModel.getSearchForegroundColor();
} else {
background = loggingEvent.isSearchMatch()?applicationPreferenceModel.getSearchBackgroundColor():loggingEvent.getBackground();
foreground = loggingEvent.isSearchMatch()?applicationPreferenceModel.getSearchForegroundColor():loggingEvent.getForeground();
}
/**
* Colourize background based on row striping if the event still has default foreground and background color
*/
if (background.equals(ChainsawConstants.COLOR_DEFAULT_BACKGROUND) && foreground.equals(ChainsawConstants.COLOR_DEFAULT_FOREGROUND)) {
if ((row % 2) != 0) {
background = applicationPreferenceModel.getAlternatingColorBackgroundColor();
foreground = applicationPreferenceModel.getAlternatingColorForegroundColor();
}
}
component.setBackground(background);
component.setForeground(foreground);
//update the background & foreground of the jtextpane using styles
if (multiLineTextPane != null)
{
StyledDocument styledDocument = multiLineTextPane.getStyledDocument();
MutableAttributeSet attributes = multiLineTextPane.getInputAttributes();
StyleConstants.setForeground(attributes, foreground);
styledDocument.setCharacterAttributes(0, styledDocument.getLength() + 1, attributes, false);
multiLineTextPane.setBackground(background);
}
levelTextPane.setBackground(background);
levelTextPane.setForeground(foreground);
singleLineTextPane.setBackground(background);
singleLineTextPane.setForeground(foreground);
if (isSelected) {
if (col == 0) {
component.setBorder(LEFT_BORDER);
} else if (col == table.getColumnCount() - 1) {
component.setBorder(RIGHT_BORDER);
} else {
component.setBorder(MIDDLE_BORDER);
}
} else {
if (col == 0) {
component.setBorder(LEFT_EMPTY_BORDER);
} else if (col == table.getColumnCount() - 1) {
component.setBorder(RIGHT_EMPTY_BORDER);
} else {
component.setBorder(MIDDLE_EMPTY_BORDER);
}
}
return component;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getTableCellRendererComponent" | "public Component getTableCellRendererComponent(
final JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int col) {
value = formatField(value);
TableColumn tableColumn = table.getColumnModel().getColumn(col);
JLabel label = (JLabel)super.getTableCellRendererComponent(table, value,
isSelected, hasFocus, row, col);
//chainsawcolumns uses one-based indexing
int colIndex = tableColumn.getModelIndex() + 1;
EventContainer container = (EventContainer) table.getModel();
ExtendedLoggingEvent loggingEvent = container.getRow(row);
//no event, use default renderer
if (loggingEvent == null) {
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
}
Map matches = loggingEvent.getSearchMatches();
JComponent component;
switch (colIndex) {
case ChainsawColumns.INDEX_THROWABLE_COL_NAME:
if (value instanceof String[] && ((String[])value).length > 0){
Style tabStyle = singleLineTextPane.getLogicalStyle();
StyleConstants.setTabSet(tabStyle, tabs);
//set the 1st tab at position 3
singleLineTextPane.setLogicalStyle(tabStyle);
//exception string is split into an array..just highlight the first line completely if anything in the exception matches if we have a match for the exception field
Set exceptionMatches = (Set)matches.get(LoggingEventFieldResolver.EXCEPTION_FIELD);
if (exceptionMatches != null && exceptionMatches.size() > 0) {
singleLineTextPane.setText(((String[])value)[0]);
boldAll((StyledDocument) singleLineTextPane.getDocument());
} else {
singleLineTextPane.setText(((String[])value)[0]);
}
} else {
singleLineTextPane.setText("");
}
component = generalPanel;
break;
case ChainsawColumns.INDEX_LOGGER_COL_NAME:
String logger = value.toString();
int startPos = -1;
for (int i = 0; i < loggerPrecision; i++) {
startPos = logger.indexOf(".", startPos + 1);
if (startPos < 0) {
break;
}
}
singleLineTextPane.setText(logger.substring(startPos + 1));
setHighlightAttributesInternal(matches.get(LoggingEventFieldResolver.LOGGER_FIELD), (StyledDocument) singleLineTextPane.getDocument());
component = generalPanel;
break;
case ChainsawColumns.INDEX_ID_COL_NAME:
singleLineTextPane.setText(value.toString());
setHighlightAttributesInternal(matches.get(LoggingEventFieldResolver.PROP_FIELD + "LOG4JID"), (StyledDocument) singleLineTextPane.getDocument());
component = generalPanel;
break;
case ChainsawColumns.INDEX_CLASS_COL_NAME:
singleLineTextPane.setText(value.toString());
setHighlightAttributesInternal(matches.get(LoggingEventFieldResolver.CLASS_FIELD), (StyledDocument) singleLineTextPane.getDocument());
component = generalPanel;
break;
case ChainsawColumns.INDEX_FILE_COL_NAME:
singleLineTextPane.setText(value.toString());
setHighlightAttributesInternal(matches.get(LoggingEventFieldResolver.FILE_FIELD), (StyledDocument) singleLineTextPane.getDocument());
component = generalPanel;
break;
case ChainsawColumns.INDEX_LINE_COL_NAME:
singleLineTextPane.setText(value.toString());
setHighlightAttributesInternal(matches.get(LoggingEventFieldResolver.LINE_FIELD), (StyledDocument) singleLineTextPane.getDocument());
component = generalPanel;
break;
case ChainsawColumns.INDEX_NDC_COL_NAME:
singleLineTextPane.setText(value.toString());
setHighlightAttributesInternal(matches.get(LoggingEventFieldResolver.NDC_FIELD), (StyledDocument) singleLineTextPane.getDocument());
component = generalPanel;
break;
case ChainsawColumns.INDEX_THREAD_COL_NAME:
singleLineTextPane.setText(value.toString());
setHighlightAttributesInternal(matches.get(LoggingEventFieldResolver.THREAD_FIELD), (StyledDocument) singleLineTextPane.getDocument());
component = generalPanel;
break;
case ChainsawColumns.INDEX_TIMESTAMP_COL_NAME:
//timestamp matches contain the millis..not the display text..just highlight if we have a match for the timestamp field
Set timestampMatches = (Set)matches.get(LoggingEventFieldResolver.TIMESTAMP_FIELD);
if (timestampMatches != null && timestampMatches.size() > 0) {
singleLineTextPane.setText(value.toString());
boldAll((StyledDocument) singleLineTextPane.getDocument());
} else {
singleLineTextPane.setText(value.toString());
}
component = generalPanel;
break;
case ChainsawColumns.INDEX_METHOD_COL_NAME:
singleLineTextPane.setText(value.toString());
setHighlightAttributesInternal(matches.get(LoggingEventFieldResolver.METHOD_FIELD), (StyledDocument) singleLineTextPane.getDocument());
component = generalPanel;
break;
case ChainsawColumns.INDEX_LOG4J_MARKER_COL_NAME:
case ChainsawColumns.INDEX_MESSAGE_COL_NAME:
String thisString = value.toString().trim();
multiLineTextPane.setText(thisString);
int width = tableColumn.getWidth();
if (colIndex == ChainsawColumns.INDEX_LOG4J_MARKER_COL_NAME) {
//property keys are set as all uppercase
setHighlightAttributesInternal(matches.get(LoggingEventFieldResolver.PROP_FIELD + ChainsawConstants.LOG4J_MARKER_COL_NAME_LOWERCASE.toUpperCase()), (StyledDocument) multiLineTextPane.getDocument());
} else {
setHighlightAttributesInternal(matches.get(LoggingEventFieldResolver.MSG_FIELD), (StyledDocument) multiLineTextPane.getDocument());
}
int tableRowHeight = table.getRowHeight(row);
multiLinePanel.removeAll();
multiLinePanel.add(multiLineTextPane);
if (wrap) {
Map paramMap = new HashMap();
paramMap.put(TextAttribute.FONT, multiLineTextPane.getFont());
int calculatedHeight = calculateHeight(thisString, width, paramMap);
//set preferred size to default height
multiLineTextPane.setSize(new Dimension(width, calculatedHeight));
int multiLinePanelPrefHeight = multiLinePanel.getPreferredSize().height;
if(tableRowHeight < multiLinePanelPrefHeight) {
table.setRowHeight(row, Math.max(ChainsawConstants.DEFAULT_ROW_HEIGHT, multiLinePanelPrefHeight));
}
}
component = multiLinePanel;
break;
case ChainsawColumns.INDEX_LEVEL_COL_NAME:
if (levelUseIcons) {
<MASK>levelTextPane.insertIcon((Icon) iconMap.get(value.toString()));</MASK>
levelTextPane.setText("");
if (!toolTipsVisible) {
levelTextPane.setToolTipText(value.toString());
}
} else {
levelTextPane.setText(value.toString());
setHighlightAttributesInternal(matches.get(LoggingEventFieldResolver.LEVEL_FIELD), (StyledDocument) levelTextPane.getDocument());
if (!toolTipsVisible) {
levelTextPane.setToolTipText(null);
}
}
if (toolTipsVisible) {
levelTextPane.setToolTipText(label.getToolTipText());
}
levelTextPane.setForeground(label.getForeground());
levelTextPane.setBackground(label.getBackground());
component = levelPanel;
break;
//remaining entries are properties
default:
Set propertySet = loggingEvent.getPropertyKeySet();
String headerName = tableColumn.getHeaderValue().toString().toLowerCase();
String thisProp = null;
//find the property in the property set...case-sensitive
for (Iterator iter = propertySet.iterator();iter.hasNext();) {
String entry = iter.next().toString();
if (entry.toLowerCase().equals(headerName)) {
thisProp = entry;
break;
}
}
if (thisProp != null) {
String propKey = LoggingEventFieldResolver.PROP_FIELD + thisProp.toUpperCase();
Set propKeyMatches = (Set)matches.get(propKey);
singleLineTextPane.setText(loggingEvent.getProperty(thisProp));
setHighlightAttributesInternal(propKeyMatches, (StyledDocument) singleLineTextPane.getDocument());
} else {
singleLineTextPane.setText("");
}
component = generalPanel;
break;
}
Color background;
Color foreground;
Rule loggerRule = colorizer.getLoggerRule();
//use logger colors in table instead of event colors if event passes logger rule
if (loggerRule != null && loggerRule.evaluate(loggingEvent, null)) {
background = applicationPreferenceModel.getSearchBackgroundColor();
foreground = applicationPreferenceModel.getSearchForegroundColor();
} else {
background = loggingEvent.isSearchMatch()?applicationPreferenceModel.getSearchBackgroundColor():loggingEvent.getBackground();
foreground = loggingEvent.isSearchMatch()?applicationPreferenceModel.getSearchForegroundColor():loggingEvent.getForeground();
}
/**
* Colourize background based on row striping if the event still has default foreground and background color
*/
if (background.equals(ChainsawConstants.COLOR_DEFAULT_BACKGROUND) && foreground.equals(ChainsawConstants.COLOR_DEFAULT_FOREGROUND)) {
if ((row % 2) != 0) {
background = applicationPreferenceModel.getAlternatingColorBackgroundColor();
foreground = applicationPreferenceModel.getAlternatingColorForegroundColor();
}
}
component.setBackground(background);
component.setForeground(foreground);
//update the background & foreground of the jtextpane using styles
if (multiLineTextPane != null)
{
StyledDocument styledDocument = multiLineTextPane.getStyledDocument();
MutableAttributeSet attributes = multiLineTextPane.getInputAttributes();
StyleConstants.setForeground(attributes, foreground);
styledDocument.setCharacterAttributes(0, styledDocument.getLength() + 1, attributes, false);
multiLineTextPane.setBackground(background);
}
levelTextPane.setBackground(background);
levelTextPane.setForeground(foreground);
singleLineTextPane.setBackground(background);
singleLineTextPane.setForeground(foreground);
if (isSelected) {
if (col == 0) {
component.setBorder(LEFT_BORDER);
} else if (col == table.getColumnCount() - 1) {
component.setBorder(RIGHT_BORDER);
} else {
component.setBorder(MIDDLE_BORDER);
}
} else {
if (col == 0) {
component.setBorder(LEFT_EMPTY_BORDER);
} else if (col == table.getColumnCount() - 1) {
component.setBorder(RIGHT_EMPTY_BORDER);
} else {
component.setBorder(MIDDLE_EMPTY_BORDER);
}
}
return component;
}" |
Inversion-Mutation | megadiff | "public DefaultSingleTargetProductDialog(String operatorName, AppContext appContext, String title, String helpID) {
super(appContext, title, ID_APPLY_CLOSE, helpID);
this.operatorName = operatorName;
targetProductNameSuffix = "";
final OperatorSpi operatorSpi = GPF.getDefaultInstance().getOperatorSpiRegistry().getOperatorSpi(operatorName);
if (operatorSpi == null) {
throw new IllegalArgumentException("operatorName");
}
ioParametersPanel = new DefaultIOParametersPanel(getAppContext(), operatorSpi, getTargetProductSelector());
this.form = new JTabbedPane();
this.form.add("I/O Parameters", ioParametersPanel);
parameterSupport = new OperatorParameterSupport(operatorSpi.getOperatorClass());
OperatorMenu operatorMenu = new OperatorMenu(this.getJDialog(),
operatorSpi.getOperatorClass(),
parameterSupport,
helpID);
final ArrayList<SourceProductSelector> sourceProductSelectorList = ioParametersPanel.getSourceProductSelectorList();
PropertySet propertyContainer = parameterSupport.getPopertySet();
if (propertyContainer.getProperties().length > 0) {
if (!sourceProductSelectorList.isEmpty()) {
Property[] properties = propertyContainer.getProperties();
List<PropertyDescriptor> rdnTypeProperties = new ArrayList<PropertyDescriptor>(properties.length);
for (Property property : properties) {
PropertyDescriptor parameterDescriptor = property.getDescriptor();
if (parameterDescriptor.getAttribute(RasterDataNodeValues.ATTRIBUTE_NAME) != null) {
rdnTypeProperties.add(parameterDescriptor);
}
}
rasterDataNodeTypeProperties = rdnTypeProperties.toArray(
new PropertyDescriptor[rdnTypeProperties.size()]);
}
PropertyPane parametersPane = new PropertyPane(propertyContainer);
final JPanel parametersPanel = parametersPane.createPanel();
parametersPanel.setBorder(new EmptyBorder(4, 4, 4, 4));
this.form.add("Processing Parameters", new JScrollPane(parametersPanel));
getJDialog().setJMenuBar(operatorMenu.createDefaultMenu());
}
productChangedHandler = new ProductChangedHandler();
if (!sourceProductSelectorList.isEmpty()) {
sourceProductSelectorList.get(0).addSelectionChangeListener(productChangedHandler);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "DefaultSingleTargetProductDialog" | "public DefaultSingleTargetProductDialog(String operatorName, AppContext appContext, String title, String helpID) {
super(appContext, title, ID_APPLY_CLOSE, helpID);
this.operatorName = operatorName;
targetProductNameSuffix = "";
final OperatorSpi operatorSpi = GPF.getDefaultInstance().getOperatorSpiRegistry().getOperatorSpi(operatorName);
if (operatorSpi == null) {
throw new IllegalArgumentException("operatorName");
}
ioParametersPanel = new DefaultIOParametersPanel(getAppContext(), operatorSpi, getTargetProductSelector());
this.form = new JTabbedPane();
this.form.add("I/O Parameters", ioParametersPanel);
parameterSupport = new OperatorParameterSupport(operatorSpi.getOperatorClass());
OperatorMenu operatorMenu = new OperatorMenu(this.getJDialog(),
operatorSpi.getOperatorClass(),
parameterSupport,
helpID);
final ArrayList<SourceProductSelector> sourceProductSelectorList = ioParametersPanel.getSourceProductSelectorList();
PropertySet propertyContainer = parameterSupport.getPopertySet();
if (propertyContainer.getProperties().length > 0) {
if (!sourceProductSelectorList.isEmpty()) {
Property[] properties = propertyContainer.getProperties();
List<PropertyDescriptor> rdnTypeProperties = new ArrayList<PropertyDescriptor>(properties.length);
for (Property property : properties) {
PropertyDescriptor parameterDescriptor = property.getDescriptor();
if (parameterDescriptor.getAttribute(RasterDataNodeValues.ATTRIBUTE_NAME) != null) {
rdnTypeProperties.add(parameterDescriptor);
}
}
rasterDataNodeTypeProperties = rdnTypeProperties.toArray(
new PropertyDescriptor[rdnTypeProperties.size()]);
}
PropertyPane parametersPane = new PropertyPane(propertyContainer);
final JPanel parametersPanel = parametersPane.createPanel();
parametersPanel.setBorder(new EmptyBorder(4, 4, 4, 4));
this.form.add("Processing Parameters", new JScrollPane(parametersPanel));
getJDialog().setJMenuBar(operatorMenu.createDefaultMenu());
}
if (!sourceProductSelectorList.isEmpty()) {
<MASK>productChangedHandler = new ProductChangedHandler();</MASK>
sourceProductSelectorList.get(0).addSelectionChangeListener(productChangedHandler);
}
}" |
Inversion-Mutation | megadiff | "public void reconcile()
{
IEditorInput input = (IEditorInput) editor.getEditorInput();
if (!(input instanceof IFileEditorInput)) return;
IDocumentProvider docProvider = editor.getDocumentProvider();
if (docProvider == null) return;
IDocument doc = docProvider.getDocument(input);
if (doc == null) return;
PerlPartitioner partitioner = (PerlPartitioner) doc.getDocumentPartitioner();
if (partitioner == null) return;
markerUtil = new MarkerUtil(((IFileEditorInput) input).getFile());
markerUtil.clearAllUsedFlags(IMarker.TASK, EPIC_AUTOGENERATED);
IPreferenceStore store = PerlEditorPlugin.getDefault().getPreferenceStore();
allowWhiteSpace = store.getBoolean(ITaskTagConstants.ID_WHITESPACE);
initSearchPatterns(store);
synchronized (partitioner.getTokensLock())
{
List tokens = partitioner.getTokens();
for (Iterator i = tokens.iterator(); i.hasNext();)
{
PerlToken t = (PerlToken) i.next();
if (t.getType() == PerlTokenTypes.COMMENT) parseComment(t);
}
}
markerUtil.removeUnusedMarkers(IMarker.TASK, EPIC_AUTOGENERATED);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "reconcile" | "public void reconcile()
{
IEditorInput input = (IEditorInput) editor.getEditorInput();
if (!(input instanceof IFileEditorInput)) return;
IDocumentProvider docProvider = editor.getDocumentProvider();
if (docProvider == null) return;
IDocument doc = docProvider.getDocument(input);
if (doc == null) return;
PerlPartitioner partitioner = (PerlPartitioner) doc.getDocumentPartitioner();
if (partitioner == null) return;
markerUtil = new MarkerUtil(((IFileEditorInput) input).getFile());
markerUtil.clearAllUsedFlags(IMarker.TASK, EPIC_AUTOGENERATED);
IPreferenceStore store = PerlEditorPlugin.getDefault().getPreferenceStore();
initSearchPatterns(store);
<MASK>allowWhiteSpace = store.getBoolean(ITaskTagConstants.ID_WHITESPACE);</MASK>
synchronized (partitioner.getTokensLock())
{
List tokens = partitioner.getTokens();
for (Iterator i = tokens.iterator(); i.hasNext();)
{
PerlToken t = (PerlToken) i.next();
if (t.getType() == PerlTokenTypes.COMMENT) parseComment(t);
}
}
markerUtil.removeUnusedMarkers(IMarker.TASK, EPIC_AUTOGENERATED);
}" |
Inversion-Mutation | megadiff | "@Override
protected void realExecute() {
IData data = project.getData();
for (ShallowAssign al : assigns){
Worker worker = data.getOrCreateWorker(al.worker);
LObject object = data.getOrCreateObject(al.object);
data.addAssign(new AssignedLabel(worker, object, al.label));
}
setResult("Assigns added");
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "realExecute" | "@Override
protected void realExecute() {
IData data = project.getData();
for (ShallowAssign al : assigns){
Worker worker = data.getOrCreateWorker(al.worker);
LObject object = data.getOrCreateObject(al.object);
data.addAssign(new AssignedLabel(worker, object, al.label));
<MASK>setResult("Assigns added");</MASK>
}
}" |
Inversion-Mutation | megadiff | "protected void updateRuntimeCombo(IServerType serverType) {
if (serverType == null || !serverType.hasRuntime() || server == null) {
if (runtimeLabel != null) {
runtimeLabel.setEnabled(false);
runtimeCombo.setItems(new String[0]);
runtimeCombo.setEnabled(false);
runtimeLabel.setVisible(false);
runtimeCombo.setVisible(false);
configureRuntimes.setEnabled(false);
configureRuntimes.setVisible(false);
addRuntime.setEnabled(false);
addRuntime.setVisible(false);
}
runtimes = new IRuntime[0];
setRuntime(null);
return;
}
updateRuntimes(serverType, !SocketUtil.isLocalhost(server.getHost()));
int size = runtimes.length;
String[] items = new String[size];
for (int i = 0; i < size; i++) {
if (runtimes[i].equals(newRuntime))
items[i] = Messages.wizNewServerRuntimeCreate;
else
items[i] = runtimes[i].getName();
}
if (runtime == null)
setRuntime(getDefaultRuntime());
if (runtimeCombo != null) {
runtimeCombo.setItems(items);
if (runtimes.length > 0) {
int sel = -1;
for (int i = 0; i < size; i++) {
if (runtimes[i].equals(runtime))
sel = i;
}
if (sel < 0) {
sel = 0;
}
runtimeCombo.select(sel);
setRuntime(runtimes[0]);
}
IRuntimeType runtimeType = serverType.getRuntimeType();
boolean showRuntime = ServerUIPlugin.getRuntimes(runtimeType).length >=1;
runtimeCombo.setEnabled(showRuntime);
runtimeLabel.setEnabled(showRuntime);
configureRuntimes.setEnabled(showRuntime);
addRuntime.setEnabled(showRuntime);
runtimeLabel.setVisible(showRuntime);
runtimeCombo.setVisible(showRuntime);
configureRuntimes.setVisible(showRuntime);
addRuntime.setVisible(showRuntime);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "updateRuntimeCombo" | "protected void updateRuntimeCombo(IServerType serverType) {
if (serverType == null || !serverType.hasRuntime() || server == null) {
if (runtimeLabel != null) {
runtimeLabel.setEnabled(false);
runtimeCombo.setItems(new String[0]);
runtimeCombo.setEnabled(false);
runtimeLabel.setVisible(false);
runtimeCombo.setVisible(false);
configureRuntimes.setEnabled(false);
configureRuntimes.setVisible(false);
addRuntime.setEnabled(false);
addRuntime.setVisible(false);
}
runtimes = new IRuntime[0];
setRuntime(null);
return;
}
updateRuntimes(serverType, !SocketUtil.isLocalhost(server.getHost()));
int size = runtimes.length;
String[] items = new String[size];
for (int i = 0; i < size; i++) {
if (runtimes[i].equals(newRuntime))
items[i] = Messages.wizNewServerRuntimeCreate;
else
items[i] = runtimes[i].getName();
}
if (runtime == null)
setRuntime(getDefaultRuntime());
if (runtimeCombo != null) {
runtimeCombo.setItems(items);
if (runtimes.length > 0) {
int sel = -1;
for (int i = 0; i < size; i++) {
if (runtimes[i].equals(runtime))
sel = i;
}
if (sel < 0) {
sel = 0;
<MASK>setRuntime(runtimes[0]);</MASK>
}
runtimeCombo.select(sel);
}
IRuntimeType runtimeType = serverType.getRuntimeType();
boolean showRuntime = ServerUIPlugin.getRuntimes(runtimeType).length >=1;
runtimeCombo.setEnabled(showRuntime);
runtimeLabel.setEnabled(showRuntime);
configureRuntimes.setEnabled(showRuntime);
addRuntime.setEnabled(showRuntime);
runtimeLabel.setVisible(showRuntime);
runtimeCombo.setVisible(showRuntime);
configureRuntimes.setVisible(showRuntime);
addRuntime.setVisible(showRuntime);
}
}" |
Inversion-Mutation | megadiff | "public static void main(String[] args) {
try {
Scanner input = new Scanner(System.in); // Make a scanner
int upTo = 0; //It has to be defined outside of the try block to be visible outside it.
while(true) {
System.out.print("Input a Number: "); // Ask for how much it should check
try {
upTo = input.nextInt(); // Set the "upTo" variable
break;//Success, it didn't fail, break the loop
} catch(Exception e) {//In case it wasn't a number...
System.out.print("You didn't input a full number(integer)"); //Tell the user it's not a integer
}
}
input.close();
int current = 2; // Current
for (; current <= upTo; current++) { // the loop (had to consult the java docs for this)
if (isPrime(current)) { // if it's true, print (I might've used some array or list thing, but it seemed hard for me)
System.out.println(current); // print
}
}
} catch (Exception e) { // Catching errors if you entered a string instead of an integer
System.out.print("Error: "); // print error
e.printStackTrace(); // print stack trace (Eclipses' auto-correct function helped me discover this xD)
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "main" | "public static void main(String[] args) {
try {
Scanner input = new Scanner(System.in); // Make a scanner
while(true) {
System.out.print("Input a Number: "); // Ask for how much it should check
<MASK>int upTo = 0; //It has to be defined outside of the try block to be visible outside it.</MASK>
try {
upTo = input.nextInt(); // Set the "upTo" variable
break;//Success, it didn't fail, break the loop
} catch(Exception e) {//In case it wasn't a number...
System.out.print("You didn't input a full number(integer)"); //Tell the user it's not a integer
}
}
input.close();
int current = 2; // Current
for (; current <= upTo; current++) { // the loop (had to consult the java docs for this)
if (isPrime(current)) { // if it's true, print (I might've used some array or list thing, but it seemed hard for me)
System.out.println(current); // print
}
}
} catch (Exception e) { // Catching errors if you entered a string instead of an integer
System.out.print("Error: "); // print error
e.printStackTrace(); // print stack trace (Eclipses' auto-correct function helped me discover this xD)
}
}" |
Inversion-Mutation | megadiff | "protected void executeOn(String[] files)
throws Exception {
if (MappingTool.ACTION_IMPORT.equals(flags.action))
assertFiles(files);
ClassLoader loader =
(ClassLoader) AccessController.doPrivileged(J2DoPrivHelper
.newTemporaryClassLoaderAction(getClassLoader()));
if (flags.meta && MappingTool.ACTION_ADD.equals(flags.action))
flags.metaDataFile = Files.getFile(file, loader);
else
flags.mappingWriter = Files.getWriter(file, loader);
flags.schemaWriter = Files.getWriter(schemaFile, loader);
flags.sqlWriter = Files.getWriter(sqlFile, loader);
MultiLoaderClassResolver resolver = new MultiLoaderClassResolver();
resolver.addClassLoader(loader);
resolver.addClassLoader((ClassLoader) AccessController.doPrivileged(
J2DoPrivHelper.getClassLoaderAction(MappingTool.class)));
JDBCConfiguration conf = (JDBCConfiguration) getConfiguration();
conf.setClassResolver(resolver);
if (!MappingTool.run(conf, files, flags, loader))
throw new BuildException(_loc.get("bad-conf", "MappingToolTask")
.getMessage());
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "executeOn" | "protected void executeOn(String[] files)
throws Exception {
if (MappingTool.ACTION_IMPORT.equals(flags.action))
assertFiles(files);
ClassLoader loader =
(ClassLoader) AccessController.doPrivileged(J2DoPrivHelper
.newTemporaryClassLoaderAction(getClassLoader()));
if (flags.meta && MappingTool.ACTION_ADD.equals(flags.action))
flags.metaDataFile = Files.getFile(file, loader);
else
flags.mappingWriter = Files.getWriter(file, loader);
flags.schemaWriter = Files.getWriter(schemaFile, loader);
flags.sqlWriter = Files.getWriter(sqlFile, loader);
MultiLoaderClassResolver resolver = new MultiLoaderClassResolver();
resolver.addClassLoader((ClassLoader) AccessController.doPrivileged(
J2DoPrivHelper.getClassLoaderAction(MappingTool.class)));
<MASK>resolver.addClassLoader(loader);</MASK>
JDBCConfiguration conf = (JDBCConfiguration) getConfiguration();
conf.setClassResolver(resolver);
if (!MappingTool.run(conf, files, flags, loader))
throw new BuildException(_loc.get("bad-conf", "MappingToolTask")
.getMessage());
}" |
Inversion-Mutation | megadiff | "protected void setupEnvironment(PythonInterpreter interp,
Properties props,
PySystemState systemState) throws PyException {
processPythonLib(interp, systemState);
checkSitePackages(props);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setupEnvironment" | "protected void setupEnvironment(PythonInterpreter interp,
Properties props,
PySystemState systemState) throws PyException {
<MASK>checkSitePackages(props);</MASK>
processPythonLib(interp, systemState);
}" |
Inversion-Mutation | megadiff | "private boolean insertIntoTable(String className, Product product) {
try {
int originalCount = getRecordCount(className);
Class<?> c = product.getClass();
Field[] fields = c.getFields();
fields = sortFields(fields);
String sql = "INSERT INTO " + className + "(";
for (int i = 0; i < fields.length; i++) {
sql += fields[i].getName();
if (i < fields.length-1) {
sql += ",";
}
}
sql += ") values (";
for (int i = 0; i < fields.length; i++) {
sql += "?";
if (i < fields.length-1) {
sql += ",";
}
}
sql += ");";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setInt(1, 1);
for (int i = 0; i < fields.length; i++) { //TODO: sort fields by name, as Class.getFields returns them in no particular order.
Object obj = fields[i].get(product);
String data = "";
if (obj != null) {
data = fields[i].get(product).toString();
setPreparedStatementValues(preparedStatement, fields[i], i+1, product); //preparedStatement args start from 1
}
}
preparedStatement.addBatch();
preparedStatement.executeBatch();
if (getRecordCount(className) == originalCount+1) {
return true;
} else {
return false;
}
} catch (Exception e) {
System.err.println("Error on database insert");
e.printStackTrace();
return false;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "insertIntoTable" | "private boolean insertIntoTable(String className, Product product) {
try {
int originalCount = getRecordCount(className);
Class<?> c = product.getClass();
Field[] fields = c.getFields();
fields = sortFields(fields);
String sql = "INSERT INTO " + className + "(";
for (int i = 0; i < fields.length; i++) {
sql += fields[i].getName();
if (i < fields.length-1) {
sql += ",";
}
}
sql += ") values (";
for (int i = 0; i < fields.length; i++) {
sql += "?";
if (i < fields.length-1) {
sql += ",";
}
}
sql += ");";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setInt(1, 1);
for (int i = 0; i < fields.length; i++) { //TODO: sort fields by name, as Class.getFields returns them in no particular order.
Object obj = fields[i].get(product);
String data = "";
if (obj != null) {
data = fields[i].get(product).toString();
}
<MASK>setPreparedStatementValues(preparedStatement, fields[i], i+1, product); //preparedStatement args start from 1</MASK>
}
preparedStatement.addBatch();
preparedStatement.executeBatch();
if (getRecordCount(className) == originalCount+1) {
return true;
} else {
return false;
}
} catch (Exception e) {
System.err.println("Error on database insert");
e.printStackTrace();
return false;
}
}" |
Inversion-Mutation | megadiff | "protected boolean onItemClicked(int id) {
Intent intent;
switch (id) {
case Statics.ITEM_TIMER:
clearBackStack();
getMainActivity().showDetails(TimerListFragment.class);
break;
case Statics.ITEM_MOVIES:
clearBackStack();
getMainActivity().showDetails(MovieListFragment.class);
break;
case Statics.ITEM_SERVICES:
clearBackStack();
getMainActivity().showDetails(ServiceListFragment.class);
break;
case Statics.ITEM_INFO:
clearBackStack();
getMainActivity().showDetails(DeviceInfoFragment.class);
break;
case Statics.ITEM_CURRENT:
clearBackStack();
getMainActivity().showDetails(CurrentServiceFragment.class);
break;
case Statics.ITEM_REMOTE:
if (getMultiPaneHandler().isSlidingMenu()) {
intent = new Intent(getMainActivity(), SimpleNoTitleFragmentActivity.class);
intent.putExtra("fragmentClass", VirtualRemoteFragment.class);
startActivity(intent);
} else {
clearBackStack();
getMainActivity().showDetails(VirtualRemoteFragment.class);
}
break;
case Statics.ITEM_PREFERENCES:
intent = new Intent(getMainActivity(), DreamDroidPreferenceActivity.class);
startActivityForResult(intent, Statics.REQUEST_ANY);
break;
case Statics.ITEM_MESSAGE:
getMultiPaneHandler().showDialogFragment(SendMessageDialog.newInstance(), "sendmessage_dialog");
break;
case Statics.ITEM_EPG_SEARCH:
getMainActivity().onSearchRequested();
break;
case Statics.ITEM_SCREENSHOT:
clearBackStack();
getMainActivity().showDetails(ScreenShotFragment.class);
break;
case Statics.ITEM_TOGGLE_STANDBY:
setPowerState(PowerState.STATE_TOGGLE);
break;
case Statics.ITEM_RESTART_GUI:
setPowerState(PowerState.STATE_GUI_RESTART);
break;
case Statics.ITEM_REBOOT:
setPowerState(PowerState.STATE_SYSTEM_REBOOT);
break;
case Statics.ITEM_SHUTDOWN:
setPowerState(PowerState.STATE_SHUTDOWN);
break;
case Statics.ITEM_POWERSTATE_DIALOG:
CharSequence[] actions = { getText(R.string.standby), getText(R.string.restart_gui),
getText(R.string.reboot), getText(R.string.shutdown) };
int[] actionIds = { Statics.ITEM_TOGGLE_STANDBY, Statics.ITEM_RESTART_GUI, Statics.ITEM_REBOOT,
Statics.ITEM_SHUTDOWN };
getMultiPaneHandler().showDialogFragment(
SimpleChoiceDialog.newInstance(getString(R.string.powercontrol), actions, actionIds),
"powerstate_dialog");
break;
case Statics.ITEM_ABOUT:
getMultiPaneHandler().showDialogFragment(AboutDialog.newInstance(), "about_dialog");
break;
case Statics.ITEM_CHECK_CONN:
getMainActivity().onProfileChanged(DreamDroid.getCurrentProfile());
break;
case Statics.ITEM_SLEEPTIMER:
getSleepTimer(true);
break;
case Statics.ITEM_MEDIA_PLAYER:
showToast(getString(R.string.not_implemented));
// TODO startActivity( new Intent(getMainActivity(),
// MediaplayerNavigationActivity.class) );
break;
case Statics.ITEM_PROFILES:
clearBackStack();
getMainActivity().showDetails(ProfileListFragment.class);
break;
case Statics.ITEM_SIGNAL:
clearBackStack();
getMainActivity().showDetails(SignalFragment.class);
break;
default:
return super.onItemClicked(id);
}
return true;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onItemClicked" | "protected boolean onItemClicked(int id) {
Intent intent;
switch (id) {
case Statics.ITEM_TIMER:
<MASK>clearBackStack();</MASK>
getMainActivity().showDetails(TimerListFragment.class);
break;
case Statics.ITEM_MOVIES:
<MASK>clearBackStack();</MASK>
getMainActivity().showDetails(MovieListFragment.class);
break;
case Statics.ITEM_SERVICES:
<MASK>clearBackStack();</MASK>
getMainActivity().showDetails(ServiceListFragment.class);
break;
case Statics.ITEM_INFO:
<MASK>clearBackStack();</MASK>
getMainActivity().showDetails(DeviceInfoFragment.class);
break;
case Statics.ITEM_CURRENT:
<MASK>clearBackStack();</MASK>
getMainActivity().showDetails(CurrentServiceFragment.class);
break;
case Statics.ITEM_REMOTE:
<MASK>clearBackStack();</MASK>
if (getMultiPaneHandler().isSlidingMenu()) {
intent = new Intent(getMainActivity(), SimpleNoTitleFragmentActivity.class);
intent.putExtra("fragmentClass", VirtualRemoteFragment.class);
startActivity(intent);
} else {
getMainActivity().showDetails(VirtualRemoteFragment.class);
}
break;
case Statics.ITEM_PREFERENCES:
intent = new Intent(getMainActivity(), DreamDroidPreferenceActivity.class);
startActivityForResult(intent, Statics.REQUEST_ANY);
break;
case Statics.ITEM_MESSAGE:
getMultiPaneHandler().showDialogFragment(SendMessageDialog.newInstance(), "sendmessage_dialog");
break;
case Statics.ITEM_EPG_SEARCH:
getMainActivity().onSearchRequested();
break;
case Statics.ITEM_SCREENSHOT:
<MASK>clearBackStack();</MASK>
getMainActivity().showDetails(ScreenShotFragment.class);
break;
case Statics.ITEM_TOGGLE_STANDBY:
setPowerState(PowerState.STATE_TOGGLE);
break;
case Statics.ITEM_RESTART_GUI:
setPowerState(PowerState.STATE_GUI_RESTART);
break;
case Statics.ITEM_REBOOT:
setPowerState(PowerState.STATE_SYSTEM_REBOOT);
break;
case Statics.ITEM_SHUTDOWN:
setPowerState(PowerState.STATE_SHUTDOWN);
break;
case Statics.ITEM_POWERSTATE_DIALOG:
CharSequence[] actions = { getText(R.string.standby), getText(R.string.restart_gui),
getText(R.string.reboot), getText(R.string.shutdown) };
int[] actionIds = { Statics.ITEM_TOGGLE_STANDBY, Statics.ITEM_RESTART_GUI, Statics.ITEM_REBOOT,
Statics.ITEM_SHUTDOWN };
getMultiPaneHandler().showDialogFragment(
SimpleChoiceDialog.newInstance(getString(R.string.powercontrol), actions, actionIds),
"powerstate_dialog");
break;
case Statics.ITEM_ABOUT:
getMultiPaneHandler().showDialogFragment(AboutDialog.newInstance(), "about_dialog");
break;
case Statics.ITEM_CHECK_CONN:
getMainActivity().onProfileChanged(DreamDroid.getCurrentProfile());
break;
case Statics.ITEM_SLEEPTIMER:
getSleepTimer(true);
break;
case Statics.ITEM_MEDIA_PLAYER:
showToast(getString(R.string.not_implemented));
// TODO startActivity( new Intent(getMainActivity(),
// MediaplayerNavigationActivity.class) );
break;
case Statics.ITEM_PROFILES:
<MASK>clearBackStack();</MASK>
getMainActivity().showDetails(ProfileListFragment.class);
break;
case Statics.ITEM_SIGNAL:
<MASK>clearBackStack();</MASK>
getMainActivity().showDetails(SignalFragment.class);
break;
default:
return super.onItemClicked(id);
}
return true;
}" |
Inversion-Mutation | megadiff | "public static void maskBaseFileByDepth(String depthFile, int depthToMask, int maskDenom, boolean exportDepth) {
System.out.println("Depth file: "+depthFile);
System.out.println("Site depth to mask: "+depthToMask);
System.out.println("Divisor for physical positions to be masked: "+maskDenom);
MutableNucleotideAlignmentHDF5 mnah5= MutableNucleotideAlignmentHDF5.getInstance(depthFile);
System.out.println("Generate file to mask");
String outMasked= depthFile.substring(0, depthFile.length()-7)+"_masked_Depth"+depthToMask+"_Denom"+maskDenom+".hmp.h5";
String outKey= depthFile.substring(0, depthFile.length()-7)+"_maskKey_Depth"+depthToMask+"_Denom"+maskDenom+".hmp.h5";
ExportUtils.writeToMutableHDF5(mnah5,outMasked, null, exportDepth);
ExportUtils.writeToMutableHDF5(mnah5,outKey, null, false);
MutableNucleotideAlignmentHDF5 mna= MutableNucleotideAlignmentHDF5.getInstance(outMasked);
System.out.println("read back in maskedFile: "+outMasked);
MutableNucleotideAlignmentHDF5 key= MutableNucleotideAlignmentHDF5.getInstance(outKey);
System.out.println("read back in keyFile: "+outKey);
int cnt= 0;
System.out.println("Starting mask...");
for (int taxon = 0; taxon < mna.getSequenceCount(); taxon++) {
int taxaCnt= 0;
byte[] taxonMask= new byte[mna.getSiteCount()];
byte[] taxonKey= new byte[mna.getSiteCount()];
for (int site = 0; site < mna.getSiteCount(); site++) {
taxonKey[site]= diploidN;
taxonMask[site]= mnah5.getBase(taxon, site);
byte[] currDepth= mnah5.getDepthForAlleles(taxon, site);
int[] currMinMaj= getIndexForMinMaj(mnah5.getMajorAllele(site),mnah5.getMinorAllele(site));
if (getReadDepthForAlleles(currDepth,currMinMaj)==depthToMask) {
if ((depthToMask>3&&((getReadDepthForAlleles(currDepth,currMinMaj[0])==1)||(getReadDepthForAlleles(currDepth,currMinMaj[1])!=1)))) continue;
if (mnah5.getPositionInLocus(site)%maskDenom==0) {
taxonMask[site]= diploidN;
taxonKey[site]= mnah5.getBase(taxon, site);
taxaCnt++;
cnt++;
}
}
}
mna.setAllBases(taxon, taxonMask);
key.setAllBases(taxon, taxonKey);
System.out.println(taxaCnt+" sites masked for "+mna.getTaxaName(taxon));
}
System.out.println(cnt+" sites masked at a depth of "+depthToMask+" (site numbers that can be divided by "+maskDenom+")");
mna.clean();
key.clean();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "maskBaseFileByDepth" | "public static void maskBaseFileByDepth(String depthFile, int depthToMask, int maskDenom, boolean exportDepth) {
System.out.println("Depth file: "+depthFile);
System.out.println("Site depth to mask: "+depthToMask);
System.out.println("Divisor for physical positions to be masked: "+maskDenom);
MutableNucleotideAlignmentHDF5 mnah5= MutableNucleotideAlignmentHDF5.getInstance(depthFile);
System.out.println("Generate file to mask");
String outMasked= depthFile.substring(0, depthFile.length()-7)+"_masked_Depth"+depthToMask+"_Denom"+maskDenom+".hmp.h5";
String outKey= depthFile.substring(0, depthFile.length()-7)+"_maskKey_Depth"+depthToMask+"_Denom"+maskDenom+".hmp.h5";
ExportUtils.writeToMutableHDF5(mnah5,outMasked, null, exportDepth);
ExportUtils.writeToMutableHDF5(mnah5,outKey, null, false);
MutableNucleotideAlignmentHDF5 mna= MutableNucleotideAlignmentHDF5.getInstance(outMasked);
System.out.println("read back in maskedFile: "+outMasked);
MutableNucleotideAlignmentHDF5 key= MutableNucleotideAlignmentHDF5.getInstance(outKey);
System.out.println("read back in keyFile: "+outKey);
int cnt= 0;
<MASK>int taxaCnt= 0;</MASK>
System.out.println("Starting mask...");
for (int taxon = 0; taxon < mna.getSequenceCount(); taxon++) {
byte[] taxonMask= new byte[mna.getSiteCount()];
byte[] taxonKey= new byte[mna.getSiteCount()];
for (int site = 0; site < mna.getSiteCount(); site++) {
taxonKey[site]= diploidN;
taxonMask[site]= mnah5.getBase(taxon, site);
byte[] currDepth= mnah5.getDepthForAlleles(taxon, site);
int[] currMinMaj= getIndexForMinMaj(mnah5.getMajorAllele(site),mnah5.getMinorAllele(site));
if (getReadDepthForAlleles(currDepth,currMinMaj)==depthToMask) {
if ((depthToMask>3&&((getReadDepthForAlleles(currDepth,currMinMaj[0])==1)||(getReadDepthForAlleles(currDepth,currMinMaj[1])!=1)))) continue;
if (mnah5.getPositionInLocus(site)%maskDenom==0) {
taxonMask[site]= diploidN;
taxonKey[site]= mnah5.getBase(taxon, site);
taxaCnt++;
cnt++;
}
}
}
mna.setAllBases(taxon, taxonMask);
key.setAllBases(taxon, taxonKey);
System.out.println(taxaCnt+" sites masked for "+mna.getTaxaName(taxon));
}
System.out.println(cnt+" sites masked at a depth of "+depthToMask+" (site numbers that can be divided by "+maskDenom+")");
mna.clean();
key.clean();
}" |
Inversion-Mutation | megadiff | "@SuppressWarnings("unchecked")
public static List<CleanPlan> createCleanPlanFromJSON(Reader reader)
throws InvalidRuleException, InvalidCleanPlanException {
Preconditions.checkNotNull(reader);
JSONObject jsonObject = (JSONObject) JSONValue.parse(reader);
// a set which prevents generating new tables whenever encounters among
// multiple rules.
List<CleanPlan> result = Lists.newArrayList();
boolean isCSV = false;
List<Schema> schemas = Lists.newArrayList();
Connection conn = null;
try {
// ----------------------------------------
// parsing the source config
// ----------------------------------------
JSONObject src = (JSONObject) jsonObject.get("source");
String type = (String) src.get("type");
DBConfig dbConfig;
switch (type) {
case "csv":
isCSV = true;
dbConfig = NadeefConfiguration.getDbConfig();
break;
default:
// TODO: support different type of DB.
SQLDialect sqlDialect = SQLDialect.POSTGRES;
DBConfig.Builder builder = new DBConfig.Builder();
dbConfig =
builder.username((String) src.get("username"))
.password((String) src.get("password"))
.url((String) src.get("url")).dialect(sqlDialect)
.build();
}
// Initialize the connection pool
DBConnectionFactory.initializeSource(dbConfig);
// ----------------------------------------
// parsing the rules
// ----------------------------------------
// TODO: use token.matches("^\\s*(\\w+\\.?){0,3}\\w\\s*$") to match
// the table pattern.
JSONArray ruleArray = (JSONArray) jsonObject.get("rule");
ArrayList<Rule> rules = Lists.newArrayList();
List<String> targetTableNames;
List<String> fileNames = Lists.newArrayList();
HashSet<String> copiedTables = Sets.newHashSet();
for (int i = 0; i < ruleArray.size(); i++) {
schemas.clear();
fileNames.clear();
JSONObject ruleObj = (JSONObject) ruleArray.get(i);
if (isCSV) {
// working with CSV
List<String> fullFileNames = (List<String>) src.get("file");
for (String fullFileName : fullFileNames) {
fileNames.add(Files.getNameWithoutExtension(fullFileName));
}
if (ruleObj.containsKey("table")) {
targetTableNames = (List<String>) ruleObj.get("table");
Preconditions.checkArgument(
targetTableNames.size() <= 2,
"NADEEF only supports MAX 2 tables per rule."
);
for (String targetTableName : targetTableNames) {
if (!fileNames.contains(targetTableName)) {
throw new InvalidCleanPlanException("Unknown table name.");
}
}
} else {
// if the target table names does not exist, we use
// default naming and only the first two tables are touched.
targetTableNames = Lists.newArrayList();
for (String fileName : fileNames) {
targetTableNames.add(fileName);
if (targetTableNames.size() == 2) {
break;
}
}
}
// source is a CSV file, dump it to NADEEF database.
conn = DBConnectionFactory.getNadeefConnection();
// This hashset is to prevent that tables are dumped for multiple times.
for (int j = 0; j < targetTableNames.size(); j++) {
File file = CommonTools.getFile(fullFileNames.get(j));
// target table name already exists in the hashset.
if (!copiedTables.contains(targetTableNames.get(j))) {
String tableName = CSVDumper.dump(conn, file, targetTableNames.get(j));
copiedTables.add(targetTableNames.get(j));
targetTableNames.set(j, tableName);
schemas.add(DBMetaDataTool.getSchema(tableName));
}
}
} else {
// working with database
List<String> sourceTableNames = (List<String>) ruleObj.get("table");
for (String tableName : sourceTableNames) {
if (!DBMetaDataTool.isTableExist(tableName)) {
throw new InvalidCleanPlanException(
"The specified table " +
tableName +
" cannot be found in the source database.");
}
}
if (ruleObj.containsKey("target")) {
targetTableNames = (List<String>) ruleObj.get("target");
} else {
// when user doesn't provide target tables we create a
// copy for them
// with default table names.
targetTableNames = Lists.newArrayList();
for (String sourceTableName : sourceTableNames) {
targetTableNames.add(sourceTableName + "_copy");
}
}
Preconditions.checkArgument(
sourceTableNames.size() == targetTableNames.size() &&
sourceTableNames.size() <= 2 &&
sourceTableNames.size() >= 1,
"Invalid Rule property, rule needs to have one or two tables.");
for (int j = 0; j < sourceTableNames.size(); j++) {
if (!copiedTables.contains(targetTableNames.get(j))) {
DBMetaDataTool.copy(
sourceTableNames.get(j),
targetTableNames.get(j)
);
schemas.add(
DBMetaDataTool.getSchema(
targetTableNames.get(j)
)
);
copiedTables.add(targetTableNames.get(j));
}
}
}
type = (String) ruleObj.get("type");
Rule rule;
JSONArray value;
value = (JSONArray) ruleObj.get("value");
String ruleName = (String) ruleObj.get("name");
if (Strings.isNullOrEmpty(ruleName)) {
// generate default rule name when it is not provided by the user, and
// distinguished by the value of the rule.
ruleName = "Rule" + CommonTools.toHashCode((String)value.get(0));
}
switch (type) {
case "udf":
value = (JSONArray) ruleObj.get("value");
Class udfClass =
CommonTools.loadClass((String) value.get(0));
if (!Rule.class.isAssignableFrom(udfClass)) {
throw new InvalidRuleException(
"The specified class is not a Rule class."
);
}
rule = (Rule) udfClass.newInstance();
// call internal initialization on the rule.
rule.initialize(ruleName, targetTableNames);
rules.add(rule);
break;
default:
RuleBuilder ruleBuilder = NadeefConfiguration.tryGetRuleBuilder(type);
if (ruleBuilder != null) {
rules.addAll(
ruleBuilder.name(ruleName)
.schema(schemas)
.table(targetTableNames)
.value(value)
.build()
);
} else {
tracer.err("Unknown Rule type: " + type, null);
}
break;
}
}
for (int i = 0; i < rules.size(); i++) {
result.add(new CleanPlan(dbConfig, rules.get(i)));
}
return result;
} catch (Exception ex) {
ex.printStackTrace();
if (ex instanceof InvalidRuleException) {
throw (InvalidRuleException) ex;
}
throw new InvalidCleanPlanException(ex);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
}
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createCleanPlanFromJSON" | "@SuppressWarnings("unchecked")
public static List<CleanPlan> createCleanPlanFromJSON(Reader reader)
throws InvalidRuleException, InvalidCleanPlanException {
Preconditions.checkNotNull(reader);
JSONObject jsonObject = (JSONObject) JSONValue.parse(reader);
// a set which prevents generating new tables whenever encounters among
// multiple rules.
List<CleanPlan> result = Lists.newArrayList();
boolean isCSV = false;
List<Schema> schemas = Lists.newArrayList();
Connection conn = null;
try {
// ----------------------------------------
// parsing the source config
// ----------------------------------------
JSONObject src = (JSONObject) jsonObject.get("source");
String type = (String) src.get("type");
DBConfig dbConfig;
switch (type) {
case "csv":
isCSV = true;
dbConfig = NadeefConfiguration.getDbConfig();
break;
default:
// TODO: support different type of DB.
SQLDialect sqlDialect = SQLDialect.POSTGRES;
DBConfig.Builder builder = new DBConfig.Builder();
dbConfig =
builder.username((String) src.get("username"))
.password((String) src.get("password"))
.url((String) src.get("url")).dialect(sqlDialect)
.build();
}
// Initialize the connection pool
DBConnectionFactory.initializeSource(dbConfig);
// ----------------------------------------
// parsing the rules
// ----------------------------------------
// TODO: use token.matches("^\\s*(\\w+\\.?){0,3}\\w\\s*$") to match
// the table pattern.
JSONArray ruleArray = (JSONArray) jsonObject.get("rule");
ArrayList<Rule> rules = Lists.newArrayList();
List<String> targetTableNames;
List<String> fileNames = Lists.newArrayList();
HashSet<String> copiedTables = Sets.newHashSet();
for (int i = 0; i < ruleArray.size(); i++) {
schemas.clear();
fileNames.clear();
JSONObject ruleObj = (JSONObject) ruleArray.get(i);
if (isCSV) {
// working with CSV
List<String> fullFileNames = (List<String>) src.get("file");
for (String fullFileName : fullFileNames) {
fileNames.add(Files.getNameWithoutExtension(fullFileName));
}
if (ruleObj.containsKey("table")) {
targetTableNames = (List<String>) ruleObj.get("table");
Preconditions.checkArgument(
targetTableNames.size() <= 2,
"NADEEF only supports MAX 2 tables per rule."
);
for (String targetTableName : targetTableNames) {
if (!fileNames.contains(targetTableName)) {
throw new InvalidCleanPlanException("Unknown table name.");
}
}
} else {
// if the target table names does not exist, we use
// default naming and only the first two tables are touched.
targetTableNames = Lists.newArrayList();
for (String fileName : fileNames) {
targetTableNames.add(fileName);
if (targetTableNames.size() == 2) {
break;
}
}
}
// source is a CSV file, dump it to NADEEF database.
conn = DBConnectionFactory.getNadeefConnection();
// This hashset is to prevent that tables are dumped for multiple times.
for (int j = 0; j < targetTableNames.size(); j++) {
File file = CommonTools.getFile(fullFileNames.get(j));
// target table name already exists in the hashset.
if (!copiedTables.contains(targetTableNames.get(j))) {
String tableName = CSVDumper.dump(conn, file, targetTableNames.get(j));
targetTableNames.set(j, tableName);
schemas.add(DBMetaDataTool.getSchema(tableName));
<MASK>copiedTables.add(targetTableNames.get(j));</MASK>
}
}
} else {
// working with database
List<String> sourceTableNames = (List<String>) ruleObj.get("table");
for (String tableName : sourceTableNames) {
if (!DBMetaDataTool.isTableExist(tableName)) {
throw new InvalidCleanPlanException(
"The specified table " +
tableName +
" cannot be found in the source database.");
}
}
if (ruleObj.containsKey("target")) {
targetTableNames = (List<String>) ruleObj.get("target");
} else {
// when user doesn't provide target tables we create a
// copy for them
// with default table names.
targetTableNames = Lists.newArrayList();
for (String sourceTableName : sourceTableNames) {
targetTableNames.add(sourceTableName + "_copy");
}
}
Preconditions.checkArgument(
sourceTableNames.size() == targetTableNames.size() &&
sourceTableNames.size() <= 2 &&
sourceTableNames.size() >= 1,
"Invalid Rule property, rule needs to have one or two tables.");
for (int j = 0; j < sourceTableNames.size(); j++) {
if (!copiedTables.contains(targetTableNames.get(j))) {
DBMetaDataTool.copy(
sourceTableNames.get(j),
targetTableNames.get(j)
);
schemas.add(
DBMetaDataTool.getSchema(
targetTableNames.get(j)
)
);
<MASK>copiedTables.add(targetTableNames.get(j));</MASK>
}
}
}
type = (String) ruleObj.get("type");
Rule rule;
JSONArray value;
value = (JSONArray) ruleObj.get("value");
String ruleName = (String) ruleObj.get("name");
if (Strings.isNullOrEmpty(ruleName)) {
// generate default rule name when it is not provided by the user, and
// distinguished by the value of the rule.
ruleName = "Rule" + CommonTools.toHashCode((String)value.get(0));
}
switch (type) {
case "udf":
value = (JSONArray) ruleObj.get("value");
Class udfClass =
CommonTools.loadClass((String) value.get(0));
if (!Rule.class.isAssignableFrom(udfClass)) {
throw new InvalidRuleException(
"The specified class is not a Rule class."
);
}
rule = (Rule) udfClass.newInstance();
// call internal initialization on the rule.
rule.initialize(ruleName, targetTableNames);
rules.add(rule);
break;
default:
RuleBuilder ruleBuilder = NadeefConfiguration.tryGetRuleBuilder(type);
if (ruleBuilder != null) {
rules.addAll(
ruleBuilder.name(ruleName)
.schema(schemas)
.table(targetTableNames)
.value(value)
.build()
);
} else {
tracer.err("Unknown Rule type: " + type, null);
}
break;
}
}
for (int i = 0; i < rules.size(); i++) {
result.add(new CleanPlan(dbConfig, rules.get(i)));
}
return result;
} catch (Exception ex) {
ex.printStackTrace();
if (ex instanceof InvalidRuleException) {
throw (InvalidRuleException) ex;
}
throw new InvalidCleanPlanException(ex);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
}
}
}
}" |
Inversion-Mutation | megadiff | "@Override
public void configureHandlerExceptionResolvers(
List<HandlerExceptionResolver> exceptionResolvers) {
exceptionResolvers.add(exceptionHandlerExceptionResolver());
exceptionResolvers.add(simpleMappingExceptionResolver());
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "configureHandlerExceptionResolvers" | "@Override
public void configureHandlerExceptionResolvers(
List<HandlerExceptionResolver> exceptionResolvers) {
<MASK>exceptionResolvers.add(simpleMappingExceptionResolver());</MASK>
exceptionResolvers.add(exceptionHandlerExceptionResolver());
}" |
Inversion-Mutation | megadiff | "public void initializePlayers() {
Square redSquare = null;
Square blueSquare = null;
try {
redSquare = getGrid().getSquareAtCoordinate(getGrid().getStartingPositions().get(0));
blueSquare = getGrid().getSquareAtCoordinate(getGrid().getStartingPositions().get(1));
} catch (OutsideTheGridException e) {
// Can not occur.
}
// Add the players to the game
players[0] = new Player(redSquare,PlayerColour.RED);
players[1] = new Player(blueSquare,PlayerColour.BLUE);
// Add to the turn queue
playerQueue.add(players[1]);
playerQueue.add(players[0]);
// Red always starts.
setCurrentPlayer(players[0]);
getCurrentPlayer().startTurn();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "initializePlayers" | "public void initializePlayers() {
Square redSquare = null;
Square blueSquare = null;
try {
redSquare = getGrid().getSquareAtCoordinate(getGrid().getStartingPositions().get(0));
blueSquare = getGrid().getSquareAtCoordinate(getGrid().getStartingPositions().get(1));
} catch (OutsideTheGridException e) {
// Can not occur.
}
// Add the players to the game
players[0] = new Player(redSquare,PlayerColour.RED);
players[1] = new Player(blueSquare,PlayerColour.BLUE);
// Add to the turn queue
playerQueue.add(players[0]);
<MASK>playerQueue.add(players[1]);</MASK>
// Red always starts.
setCurrentPlayer(players[0]);
getCurrentPlayer().startTurn();
}" |
Inversion-Mutation | megadiff | "@Override
public void onCreate() {
mConnectivityManager = new EmailConnectivityManager(this, TAG);
// Start up our service thread
new Thread(this, "AttachmentDownloadService").start();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCreate" | "@Override
public void onCreate() {
// Start up our service thread
new Thread(this, "AttachmentDownloadService").start();
<MASK>mConnectivityManager = new EmailConnectivityManager(this, TAG);</MASK>
}" |
Inversion-Mutation | megadiff | "public void reserveConfirmed(Long connectionId, NsiRequestDetails requestDetails) {
ConnectionV2 connection = connectionRepo.findOne(connectionId);
connection.setReservationState(ReservationStateEnumType.RESERVE_HELD);
connectionRepo.save(connection);
log.info("Sending a reserveConfirmed on endpoint: {} for connectionId: {}", requestDetails.getReplyTo(), connection.getConnectionId());
ReservationConfirmCriteriaType criteria = new ReservationConfirmCriteriaType()
.withBandwidth(connection.getDesiredBandwidth())
.withPath(new PathType()
.withSourceSTP(toStpType(connection.getSourceStpId()))
.withDestSTP(toStpType(connection.getDestinationStpId()))
.withDirectionality(DirectionalityType.BIDIRECTIONAL))
.withSchedule(new ScheduleType()
.withEndTime(XmlUtils.toGregorianCalendar(connection.getEndTime().get()))
.withStartTime(XmlUtils.toGregorianCalendar(connection.getStartTime().get())))
.withServiceAttributes(new TypeValuePairListType())
.withVersion(0);
Holder<CommonHeaderType> headerHolder = createHeader(requestDetails, connection);
ConnectionRequesterPort port = createPort(requestDetails);
try {
port.reserveConfirmed(
connection.getConnectionId(),
connection.getGlobalReservationId(),
connection.getDescription(),
ImmutableList.of(criteria),
headerHolder);
} catch (ServiceException e) {
log.info("Sending reserve confirmed failed", e);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "reserveConfirmed" | "public void reserveConfirmed(Long connectionId, NsiRequestDetails requestDetails) {
ConnectionV2 connection = connectionRepo.findOne(connectionId);
connection.setReservationState(ReservationStateEnumType.RESERVE_HELD);
connectionRepo.save(connection);
log.info("Sending a reserveConfirmed on endpoint: {} for connectionId: {}", requestDetails.getReplyTo(), connection.getConnectionId());
ReservationConfirmCriteriaType criteria = new ReservationConfirmCriteriaType()
.withBandwidth(connection.getDesiredBandwidth())
.withPath(new PathType()
.withSourceSTP(toStpType(connection.getSourceStpId()))
.withDestSTP(toStpType(connection.getDestinationStpId()))
.withDirectionality(DirectionalityType.BIDIRECTIONAL))
.withSchedule(new ScheduleType()
.withEndTime(XmlUtils.toGregorianCalendar(connection.getEndTime().get()))
.withStartTime(XmlUtils.toGregorianCalendar(connection.getStartTime().get())))
.withServiceAttributes(new TypeValuePairListType())
.withVersion(0);
Holder<CommonHeaderType> headerHolder = createHeader(requestDetails, connection);
ConnectionRequesterPort port = createPort(requestDetails);
try {
port.reserveConfirmed(
connection.getGlobalReservationId(),
connection.getDescription(),
<MASK>connection.getConnectionId(),</MASK>
ImmutableList.of(criteria),
headerHolder);
} catch (ServiceException e) {
log.info("Sending reserve confirmed failed", e);
}
}" |
Inversion-Mutation | megadiff | "public static void main(String[] args) throws IOException {
String location;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(57005);
while(true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
location = inFromClient.readLine();
System.out.println("Received: " + location);
saveToFile(location, "locations");
// For testing purposes, perhaps this configurable
capitalizedSentence = location.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "main" | "public static void main(String[] args) throws IOException {
String location;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(57005);
while(true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
location = inFromClient.readLine();
saveToFile(location, "locations");
// For testing purposes, perhaps this configurable
<MASK>System.out.println("Received: " + location);</MASK>
capitalizedSentence = location.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}
}" |
Inversion-Mutation | megadiff | "private void loadAndBindAllApps() {
final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderThread running with no launcher (loadAndBindAllApps)");
return;
}
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final PackageManager packageManager = mContext.getPackageManager();
List<ResolveInfo> apps = null;
int N = Integer.MAX_VALUE;
int startIndex;
int i=0;
int batchSize = -1;
while (i < N && !mStopped) {
synchronized (mLock) {
if (i == 0) {
// This needs to happen inside the same lock block as when we
// prepare the first batch for bindAllApplications. Otherwise
// the package changed receiver can come in and double-add
// (or miss one?).
mAllAppsList.clear();
final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
apps = packageManager.queryIntentActivities(mainIntent, 0);
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities took "
+ (SystemClock.uptimeMillis()-qiaTime) + "ms");
}
if (apps == null) {
return;
}
N = apps.size();
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities got " + N + " apps");
}
if (N == 0) {
// There are no apps?!?
return;
}
if (mBatchSize == 0) {
batchSize = N;
} else {
batchSize = mBatchSize;
}
final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Collections.sort(apps,
new ResolveInfo.DisplayNameComparator(packageManager));
if (DEBUG_LOADERS) {
Log.d(TAG, "sort took "
+ (SystemClock.uptimeMillis()-qiaTime) + "ms");
}
}
final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
startIndex = i;
for (int j=0; i<N && j<batchSize; j++) {
// This builds the icon bitmaps.
mAllAppsList.add(new ApplicationInfo(apps.get(i), mIconCache));
i++;
}
final boolean first = i <= batchSize;
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
final ArrayList<ApplicationInfo> added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
if (callbacks != null) {
if (first) {
mBeforeFirstLoad = false;
callbacks.bindAllApplications(added);
} else {
callbacks.bindAppsAdded(added);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound " + added.size() + " apps in "
+ (SystemClock.uptimeMillis() - t) + "ms");
}
} else {
Log.i(TAG, "not binding apps: no Launcher activity");
}
}
});
if (DEBUG_LOADERS) {
Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in "
+ (SystemClock.uptimeMillis()-t2) + "ms");
}
}
if (mAllAppsLoadDelay > 0 && i < N) {
try {
if (DEBUG_LOADERS) {
Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms");
}
Thread.sleep(mAllAppsLoadDelay);
} catch (InterruptedException exc) { }
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "cached all " + N + " apps in "
+ (SystemClock.uptimeMillis()-t) + "ms"
+ (mAllAppsLoadDelay > 0 ? " (including delay)" : ""));
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "loadAndBindAllApps" | "private void loadAndBindAllApps() {
final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderThread running with no launcher (loadAndBindAllApps)");
return;
}
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final PackageManager packageManager = mContext.getPackageManager();
List<ResolveInfo> apps = null;
int N = Integer.MAX_VALUE;
int startIndex;
int i=0;
int batchSize = -1;
while (i < N && !mStopped) {
synchronized (mLock) {
if (i == 0) {
// This needs to happen inside the same lock block as when we
// prepare the first batch for bindAllApplications. Otherwise
// the package changed receiver can come in and double-add
// (or miss one?).
mAllAppsList.clear();
final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
apps = packageManager.queryIntentActivities(mainIntent, 0);
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities took "
+ (SystemClock.uptimeMillis()-qiaTime) + "ms");
}
if (apps == null) {
return;
}
N = apps.size();
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities got " + N + " apps");
}
if (N == 0) {
// There are no apps?!?
return;
}
if (mBatchSize == 0) {
batchSize = N;
} else {
batchSize = mBatchSize;
}
final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Collections.sort(apps,
new ResolveInfo.DisplayNameComparator(packageManager));
if (DEBUG_LOADERS) {
Log.d(TAG, "sort took "
+ (SystemClock.uptimeMillis()-qiaTime) + "ms");
}
}
final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
startIndex = i;
for (int j=0; i<N && j<batchSize; j++) {
// This builds the icon bitmaps.
mAllAppsList.add(new ApplicationInfo(apps.get(i), mIconCache));
i++;
}
final boolean first = i <= batchSize;
final ArrayList<ApplicationInfo> added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
<MASK>final Callbacks callbacks = tryGetCallbacks(oldCallbacks);</MASK>
if (callbacks != null) {
if (first) {
mBeforeFirstLoad = false;
callbacks.bindAllApplications(added);
} else {
callbacks.bindAppsAdded(added);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound " + added.size() + " apps in "
+ (SystemClock.uptimeMillis() - t) + "ms");
}
} else {
Log.i(TAG, "not binding apps: no Launcher activity");
}
}
});
if (DEBUG_LOADERS) {
Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in "
+ (SystemClock.uptimeMillis()-t2) + "ms");
}
}
if (mAllAppsLoadDelay > 0 && i < N) {
try {
if (DEBUG_LOADERS) {
Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms");
}
Thread.sleep(mAllAppsLoadDelay);
} catch (InterruptedException exc) { }
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "cached all " + N + " apps in "
+ (SystemClock.uptimeMillis()-t) + "ms"
+ (mAllAppsLoadDelay > 0 ? " (including delay)" : ""));
}
}" |
Inversion-Mutation | megadiff | "public TextField newTextField(String s, int max_length, int width, int style){
TextField t = new TextField(this.mc.fontRenderer, this.x, this.y, width, style);
t.setMaxStringLength(max_length);
t.setText(s);
this.x += width;
return t;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "newTextField" | "public TextField newTextField(String s, int max_length, int width, int style){
TextField t = new TextField(this.mc.fontRenderer, this.x, this.y, width, style);
<MASK>t.setText(s);</MASK>
t.setMaxStringLength(max_length);
this.x += width;
return t;
}" |
Inversion-Mutation | megadiff | "public static String getTitleFromUrl(AbstractWebLocation location, IProgressMonitor monitor) throws IOException {
monitor = Policy.monitorFor(monitor);
try {
monitor.beginTask("Retrieving " + location.getUrl(), IProgressMonitor.UNKNOWN);
HttpClient client = new HttpClient();
WebUtil.configureHttpClient(client, "");
GetMethod method = new GetMethod(location.getUrl());
try {
HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, monitor);
int result = WebUtil.execute(client, hostConfiguration, method, monitor);
if (result == HttpStatus.SC_OK) {
InputStream in = WebUtil.getResponseBodyAsStream(method, monitor);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
HtmlStreamTokenizer tokenizer = new HtmlStreamTokenizer(reader, null);
try {
for (Token token = tokenizer.nextToken(); token.getType() != Token.EOF; token = tokenizer.nextToken()) {
if (token.getType() == Token.TAG) {
HtmlTag tag = (HtmlTag) token.getValue();
if (tag.getTagType() == Tag.TITLE) {
return getText(tokenizer);
}
}
}
} catch (ParseException e) {
throw new IOException("Error reading url");
}
} finally {
in.close();
}
}
} finally {
method.releaseConnection();
}
} finally {
monitor.done();
}
return null;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getTitleFromUrl" | "public static String getTitleFromUrl(AbstractWebLocation location, IProgressMonitor monitor) throws IOException {
monitor = Policy.monitorFor(monitor);
try {
monitor.beginTask("Retrieving " + location.getUrl(), IProgressMonitor.UNKNOWN);
HttpClient client = new HttpClient();
WebUtil.configureHttpClient(client, "");
<MASK>HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, monitor);</MASK>
GetMethod method = new GetMethod(location.getUrl());
try {
int result = WebUtil.execute(client, hostConfiguration, method, monitor);
if (result == HttpStatus.SC_OK) {
InputStream in = WebUtil.getResponseBodyAsStream(method, monitor);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
HtmlStreamTokenizer tokenizer = new HtmlStreamTokenizer(reader, null);
try {
for (Token token = tokenizer.nextToken(); token.getType() != Token.EOF; token = tokenizer.nextToken()) {
if (token.getType() == Token.TAG) {
HtmlTag tag = (HtmlTag) token.getValue();
if (tag.getTagType() == Tag.TITLE) {
return getText(tokenizer);
}
}
}
} catch (ParseException e) {
throw new IOException("Error reading url");
}
} finally {
in.close();
}
}
} finally {
method.releaseConnection();
}
} finally {
monitor.done();
}
return null;
}" |
Inversion-Mutation | megadiff | "public boolean onBlockDestroy(Player player, Block block) {
if (block.getType() != Portal.SIGN && block.getType() != Portal.OBSIDIAN && block.getType() != Portal.BUTTON) return false;
Portal gate = Portal.getByBlock(block);
if (gate == null) return false;
if ((block.getType() == Portal.BUTTON) && (block.getStatus() == 0)) {
onButtonPressed(player, gate);
return true;
} else if (block.getStatus() == 3) {
if (!player.canUseCommand("/stargate")) return true;
gate.unregister();
player.sendMessage(Colors.Red + destroyzMessage);
}
return false;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onBlockDestroy" | "public boolean onBlockDestroy(Player player, Block block) {
if (block.getType() != Portal.SIGN && block.getType() != Portal.OBSIDIAN && block.getType() != Portal.BUTTON) return false;
Portal gate = Portal.getByBlock(block);
if (gate == null) return false;
<MASK>if (!player.canUseCommand("/stargate")) return true;</MASK>
if ((block.getType() == Portal.BUTTON) && (block.getStatus() == 0)) {
onButtonPressed(player, gate);
return true;
} else if (block.getStatus() == 3) {
gate.unregister();
player.sendMessage(Colors.Red + destroyzMessage);
}
return false;
}" |
Inversion-Mutation | megadiff | "public boolean performItemClick(View view, int position, long id) {
if (mOnItemClickListener != null) {
if (view != null) {
view.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
}
mOnItemClickListener.onItemClick(this, view, position, id);
playSoundEffect(SoundEffectConstants.CLICK);
return true;
}
return false;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "performItemClick" | "public boolean performItemClick(View view, int position, long id) {
if (mOnItemClickListener != null) {
<MASK>playSoundEffect(SoundEffectConstants.CLICK);</MASK>
if (view != null) {
view.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
}
mOnItemClickListener.onItemClick(this, view, position, id);
return true;
}
return false;
}" |
Inversion-Mutation | megadiff | "public void installSources(IPackageFragmentRoot root) {
NuxeoSDK sdk = NuxeoSDK.getDefault();
if (sdk == null) {
UI.showError("No Nuxeo SDK configured. Cannot continue.");
return;
}
Artifact artifact = Artifact.fromJarName(root.getElementName());
if (artifact == null) {
UI.showError("Cannot resolve JAR " + root.getElementName()
+ " to Maven GAV");
return;
}
try {
FileRef ref = MavenDownloader.downloadSourceJar(artifact);
if (ref == null) {
UI.showError("No sources found for corresponding artifact: "
+ artifact);
return;
}
ref.installTo(sdk.getBundlesSrcDir());
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
NuxeoSDK.reload();
setMessage("Sources are configured");
}
});
} catch (IOException e) {
UI.showError("Faield to download artifact file", e);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "installSources" | "public void installSources(IPackageFragmentRoot root) {
NuxeoSDK sdk = NuxeoSDK.getDefault();
if (sdk == null) {
UI.showError("No Nuxeo SDK configured. Cannot continue.");
return;
}
Artifact artifact = Artifact.fromJarName(root.getElementName());
if (artifact == null) {
UI.showError("Cannot resolve JAR " + root.getElementName()
+ " to Maven GAV");
return;
}
try {
FileRef ref = MavenDownloader.downloadSourceJar(artifact);
if (ref == null) {
UI.showError("No sources found for corresponding artifact: "
+ artifact);
return;
}
ref.installTo(sdk.getBundlesSrcDir());
<MASK>NuxeoSDK.reload();</MASK>
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
setMessage("Sources are configured");
}
});
} catch (IOException e) {
UI.showError("Faield to download artifact file", e);
}
}" |
Inversion-Mutation | megadiff | "public ParticleEmitter (ParticleEmitter emitter) {
sprite = emitter.sprite;
name = emitter.name;
setMaxParticleCount(emitter.maxParticleCount);
minParticleCount = emitter.minParticleCount;
delayValue.load(emitter.delayValue);
durationValue.load(emitter.durationValue);
emissionValue.load(emitter.emissionValue);
lifeValue.load(emitter.lifeValue);
lifeOffsetValue.load(emitter.lifeOffsetValue);
scaleValue.load(emitter.scaleValue);
rotationValue.load(emitter.rotationValue);
velocityValue.load(emitter.velocityValue);
angleValue.load(emitter.angleValue);
windValue.load(emitter.windValue);
gravityValue.load(emitter.gravityValue);
transparencyValue.load(emitter.transparencyValue);
tintValue.load(emitter.tintValue);
xOffsetValue.load(emitter.xOffsetValue);
yOffsetValue.load(emitter.yOffsetValue);
spawnWidthValue.load(emitter.spawnWidthValue);
spawnHeightValue.load(emitter.spawnHeightValue);
spawnShapeValue.load(emitter.spawnShapeValue);
attached = emitter.attached;
continuous = emitter.continuous;
aligned = emitter.aligned;
behind = emitter.behind;
additive = emitter.additive;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "ParticleEmitter" | "public ParticleEmitter (ParticleEmitter emitter) {
<MASK>name = emitter.name;</MASK>
sprite = emitter.sprite;
setMaxParticleCount(emitter.maxParticleCount);
minParticleCount = emitter.minParticleCount;
delayValue.load(emitter.delayValue);
durationValue.load(emitter.durationValue);
emissionValue.load(emitter.emissionValue);
lifeValue.load(emitter.lifeValue);
lifeOffsetValue.load(emitter.lifeOffsetValue);
scaleValue.load(emitter.scaleValue);
rotationValue.load(emitter.rotationValue);
velocityValue.load(emitter.velocityValue);
angleValue.load(emitter.angleValue);
windValue.load(emitter.windValue);
gravityValue.load(emitter.gravityValue);
transparencyValue.load(emitter.transparencyValue);
tintValue.load(emitter.tintValue);
xOffsetValue.load(emitter.xOffsetValue);
yOffsetValue.load(emitter.yOffsetValue);
spawnWidthValue.load(emitter.spawnWidthValue);
spawnHeightValue.load(emitter.spawnHeightValue);
spawnShapeValue.load(emitter.spawnShapeValue);
attached = emitter.attached;
continuous = emitter.continuous;
aligned = emitter.aligned;
behind = emitter.behind;
additive = emitter.additive;
}" |
Inversion-Mutation | megadiff | "private void loadWorkspace() {
final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
final boolean isSafeMode = manager.isSafeMode();
// Make sure the default workspace is loaded, if needed
boolean loadOldDb = mApp.getLauncherProvider().shouldLoadOldDb();
Uri contentUri = loadOldDb ? LauncherSettings.Favorites.OLD_CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI;
mIsUpgradePath = loadOldDb;
synchronized (sBgLock) {
sBgWorkspaceItems.clear();
sBgAppWidgets.clear();
sBgFolders.clear();
sBgItemsIdMap.clear();
sBgDbIconCache.clear();
sBgWorkspaceScreens.clear();
final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
final Cursor c = contentResolver.query(contentUri, null, null, null, null);
// +1 for the hotseat (it can be larger than the workspace)
// Load workspace in reverse order to ensure that latest items are loaded first (and
// before any earlier duplicates)
final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
//final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
//final int displayModeIndex = c.getColumnIndexOrThrow(
// LauncherSettings.Favorites.DISPLAY_MODE);
ShortcutInfo info;
String intentDescription;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getShortcutInfo(manager, intent, context, c, iconIndex,
titleIndex, mLabelCache);
} else {
info = getShortcutInfo(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex,
titleIndex);
// App shortcuts that used to be automatically added to Launcher
// didn't always have the correct intent flags set, so do that
// here
if (intent.getAction() != null &&
intent.getCategories() != null &&
intent.getAction().equals(Intent.ACTION_MAIN) &&
intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
intent.addFlags(
Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
}
}
if (info != null) {
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screenId = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, info)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
sBgWorkspaceItems.add(info);
break;
default:
// Item is in a user folder
FolderInfo folderInfo =
findOrMakeFolder(sBgFolders, container);
folderInfo.add(info);
break;
}
if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
loadOldDb) {
info.screenId = permuteScreens(info.screenId);
}
sBgItemsIdMap.put(info.id, info);
// now that we've loaded everthing re-save it with the
// icon in case it disappears somehow.
queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
} else {
// Failed to load the shortcut, probably because the
// activity manager couldn't resolve it (maybe the app
// was uninstalled), or the db row was somehow screwed up.
// Delete it.
id = c.getLong(idIndex);
Log.e(TAG, "Error loading shortcut " + id + ", removing it");
contentResolver.delete(LauncherSettings.Favorites.getContentUri(
id, false), null, null);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
id = c.getLong(idIndex);
FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screenId = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, folderInfo)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
sBgWorkspaceItems.add(folderInfo);
break;
}
if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
loadOldDb) {
folderInfo.screenId = permuteScreens(folderInfo.screenId);
}
sBgItemsIdMap.put(folderInfo.id, folderInfo);
sBgFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
id = c.getLong(idIndex);
final AppWidgetProviderInfo provider =
widgets.getAppWidgetInfo(appWidgetId);
if (!isSafeMode && (provider == null || provider.provider == null ||
provider.provider.getPackageName() == null)) {
String log = "Deleting widget that isn't installed anymore: id="
+ id + " appWidgetId=" + appWidgetId;
Log.e(TAG, log);
Launcher.sDumpLogs.add(log);
itemsToRemove.add(id);
} else {
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
provider.provider);
appWidgetInfo.id = id;
appWidgetInfo.screenId = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
appWidgetInfo.minSpanX = minSpan[0];
appWidgetInfo.minSpanY = minSpan[1];
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Log.e(TAG, "Widget found where container != " +
"CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
continue;
}
if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
loadOldDb) {
appWidgetInfo.screenId =
permuteScreens(appWidgetInfo.screenId);
}
appWidgetInfo.container = c.getInt(containerIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, appWidgetInfo)) {
break;
}
sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
sBgAppWidgets.add(appWidgetInfo);
}
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
if (itemsToRemove.size() > 0) {
ContentProviderClient client = contentResolver.acquireContentProviderClient(
LauncherSettings.Favorites.CONTENT_URI);
// Remove dead items
for (long id : itemsToRemove) {
if (DEBUG_LOADERS) {
Log.d(TAG, "Removed id = " + id);
}
// Don't notify content observers
try {
client.delete(LauncherSettings.Favorites.getContentUri(id, false),
null, null);
} catch (RemoteException e) {
Log.w(TAG, "Could not remove id = " + id);
}
}
}
if (loadOldDb) {
long maxScreenId = 0;
// If we're importing we use the old screen order.
for (ItemInfo item: sBgItemsIdMap.values()) {
long screenId = item.screenId;
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
!sBgWorkspaceScreens.contains(screenId)) {
sBgWorkspaceScreens.add(screenId);
if (screenId > maxScreenId) {
maxScreenId = screenId;
}
}
}
Collections.sort(sBgWorkspaceScreens);
mApp.getLauncherProvider().updateMaxScreenId(maxScreenId);
updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
} else {
Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
try {
final int idIndex = sc.getColumnIndexOrThrow(
LauncherSettings.WorkspaceScreens._ID);
final int rankIndex = sc.getColumnIndexOrThrow(
LauncherSettings.WorkspaceScreens.SCREEN_RANK);
while (sc.moveToNext()) {
try {
long screenId = sc.getLong(idIndex);
int rank = sc.getInt(rankIndex);
orderedScreens.put(rank, screenId);
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
sc.close();
}
Iterator<Integer> iter = orderedScreens.keySet().iterator();
while (iter.hasNext()) {
sBgWorkspaceScreens.add(orderedScreens.get(iter.next()));
}
// Remove any empty screens
ArrayList<Long> unusedScreens = new ArrayList<Long>();
unusedScreens.addAll(sBgWorkspaceScreens);
for (ItemInfo item: sBgItemsIdMap.values()) {
long screenId = item.screenId;
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
unusedScreens.contains(screenId)) {
unusedScreens.remove(screenId);
}
}
// If there are any empty screens remove them, and update.
if (unusedScreens.size() != 0) {
sBgWorkspaceScreens.removeAll(unusedScreens);
updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
Log.d(TAG, "workspace layout: ");
int nScreens = occupied.size();
for (int y = 0; y < mCellCountY; y++) {
String line = "";
Iterator<Long> iter = occupied.keySet().iterator();
for (int s = 0; s < nScreens; s++) {
long screenId = iter.next();
if (s > 0) {
line += " | ";
}
for (int x = 0; x < mCellCountX; x++) {
line += ((occupied.get(screenId)[x][y] != null) ? "#" : ".");
}
}
Log.d(TAG, "[ " + line + " ]");
}
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "loadWorkspace" | "private void loadWorkspace() {
final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
final boolean isSafeMode = manager.isSafeMode();
// Make sure the default workspace is loaded, if needed
boolean loadOldDb = mApp.getLauncherProvider().shouldLoadOldDb();
Uri contentUri = loadOldDb ? LauncherSettings.Favorites.OLD_CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI;
mIsUpgradePath = loadOldDb;
synchronized (sBgLock) {
sBgWorkspaceItems.clear();
sBgAppWidgets.clear();
sBgFolders.clear();
sBgItemsIdMap.clear();
sBgDbIconCache.clear();
sBgWorkspaceScreens.clear();
final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
final Cursor c = contentResolver.query(contentUri, null, null, null, null);
// +1 for the hotseat (it can be larger than the workspace)
// Load workspace in reverse order to ensure that latest items are loaded first (and
// before any earlier duplicates)
final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
//final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
//final int displayModeIndex = c.getColumnIndexOrThrow(
// LauncherSettings.Favorites.DISPLAY_MODE);
ShortcutInfo info;
String intentDescription;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getShortcutInfo(manager, intent, context, c, iconIndex,
titleIndex, mLabelCache);
} else {
info = getShortcutInfo(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex,
titleIndex);
// App shortcuts that used to be automatically added to Launcher
// didn't always have the correct intent flags set, so do that
// here
if (intent.getAction() != null &&
intent.getCategories() != null &&
intent.getAction().equals(Intent.ACTION_MAIN) &&
intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
intent.addFlags(
Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
}
}
if (info != null) {
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screenId = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, info)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
sBgWorkspaceItems.add(info);
break;
default:
// Item is in a user folder
FolderInfo folderInfo =
findOrMakeFolder(sBgFolders, container);
folderInfo.add(info);
break;
}
if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
loadOldDb) {
info.screenId = permuteScreens(info.screenId);
}
sBgItemsIdMap.put(info.id, info);
// now that we've loaded everthing re-save it with the
// icon in case it disappears somehow.
queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
} else {
// Failed to load the shortcut, probably because the
// activity manager couldn't resolve it (maybe the app
// was uninstalled), or the db row was somehow screwed up.
// Delete it.
id = c.getLong(idIndex);
Log.e(TAG, "Error loading shortcut " + id + ", removing it");
contentResolver.delete(LauncherSettings.Favorites.getContentUri(
id, false), null, null);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
id = c.getLong(idIndex);
FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screenId = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, folderInfo)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
sBgWorkspaceItems.add(folderInfo);
break;
}
if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
loadOldDb) {
folderInfo.screenId = permuteScreens(folderInfo.screenId);
}
sBgItemsIdMap.put(folderInfo.id, folderInfo);
sBgFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
id = c.getLong(idIndex);
final AppWidgetProviderInfo provider =
widgets.getAppWidgetInfo(appWidgetId);
if (!isSafeMode && (provider == null || provider.provider == null ||
provider.provider.getPackageName() == null)) {
String log = "Deleting widget that isn't installed anymore: id="
+ id + " appWidgetId=" + appWidgetId;
Log.e(TAG, log);
Launcher.sDumpLogs.add(log);
itemsToRemove.add(id);
} else {
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
provider.provider);
appWidgetInfo.id = id;
appWidgetInfo.screenId = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
appWidgetInfo.minSpanX = minSpan[0];
appWidgetInfo.minSpanY = minSpan[1];
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Log.e(TAG, "Widget found where container != " +
"CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
continue;
}
if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
loadOldDb) {
appWidgetInfo.screenId =
permuteScreens(appWidgetInfo.screenId);
}
appWidgetInfo.container = c.getInt(containerIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, appWidgetInfo)) {
break;
}
sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
sBgAppWidgets.add(appWidgetInfo);
}
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
if (itemsToRemove.size() > 0) {
ContentProviderClient client = contentResolver.acquireContentProviderClient(
LauncherSettings.Favorites.CONTENT_URI);
// Remove dead items
for (long id : itemsToRemove) {
if (DEBUG_LOADERS) {
Log.d(TAG, "Removed id = " + id);
}
// Don't notify content observers
try {
client.delete(LauncherSettings.Favorites.getContentUri(id, false),
null, null);
} catch (RemoteException e) {
Log.w(TAG, "Could not remove id = " + id);
}
}
}
if (loadOldDb) {
long maxScreenId = 0;
// If we're importing we use the old screen order.
for (ItemInfo item: sBgItemsIdMap.values()) {
long screenId = item.screenId;
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
!sBgWorkspaceScreens.contains(screenId)) {
sBgWorkspaceScreens.add(screenId);
if (screenId > maxScreenId) {
maxScreenId = screenId;
}
}
}
Collections.sort(sBgWorkspaceScreens);
mApp.getLauncherProvider().updateMaxScreenId(maxScreenId);
updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
} else {
Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
try {
final int idIndex = sc.getColumnIndexOrThrow(
LauncherSettings.WorkspaceScreens._ID);
final int rankIndex = sc.getColumnIndexOrThrow(
LauncherSettings.WorkspaceScreens.SCREEN_RANK);
while (sc.moveToNext()) {
try {
long screenId = sc.getLong(idIndex);
int rank = sc.getInt(rankIndex);
orderedScreens.put(rank, screenId);
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
sc.close();
}
Iterator<Integer> iter = orderedScreens.keySet().iterator();
while (iter.hasNext()) {
sBgWorkspaceScreens.add(orderedScreens.get(iter.next()));
}
// Remove any empty screens
ArrayList<Long> unusedScreens = new ArrayList<Long>();
unusedScreens.addAll(sBgWorkspaceScreens);
for (ItemInfo item: sBgItemsIdMap.values()) {
long screenId = item.screenId;
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
unusedScreens.contains(screenId)) {
unusedScreens.remove(screenId);
}
}
// If there are any empty screens remove them, and update.
if (unusedScreens.size() != 0) {
sBgWorkspaceScreens.removeAll(unusedScreens);
updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
Log.d(TAG, "workspace layout: ");
<MASK>Iterator<Long> iter = occupied.keySet().iterator();</MASK>
int nScreens = occupied.size();
for (int y = 0; y < mCellCountY; y++) {
String line = "";
for (int s = 0; s < nScreens; s++) {
long screenId = iter.next();
if (s > 0) {
line += " | ";
}
for (int x = 0; x < mCellCountX; x++) {
line += ((occupied.get(screenId)[x][y] != null) ? "#" : ".");
}
}
Log.d(TAG, "[ " + line + " ]");
}
}
}
}" |
Inversion-Mutation | megadiff | "@Override
public void onPageFinished(WebView view, String url) {
if (imagesLoadingState) {
imagesLoadingState = false;
imageLoadingFinished();
}
if(!isResumed()){
Log.e(TAG,"PageFinished after pausing. Forcing Webview.pauseTimers");
mHandler.postDelayed(new Runnable(){
@Override
public void run() {
mThreadView.pauseTimers();
mThreadView.onPause();
}
}, 500);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onPageFinished" | "@Override
public void onPageFinished(WebView view, String url) {
if (imagesLoadingState) {
imagesLoadingState = false;
imageLoadingFinished();
}
if(!isResumed()){
Log.e(TAG,"PageFinished after pausing. Forcing Webview.pauseTimers");
mHandler.postDelayed(new Runnable(){
@Override
public void run() {
<MASK>mThreadView.onPause();</MASK>
mThreadView.pauseTimers();
}
}, 500);
}
}" |
Inversion-Mutation | megadiff | "@Override
public void run() {
mThreadView.pauseTimers();
mThreadView.onPause();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run" | "@Override
public void run() {
<MASK>mThreadView.onPause();</MASK>
mThreadView.pauseTimers();
}" |
Inversion-Mutation | megadiff | "protected void installListeners() {
//David: Adding the MouseEventHandler synchronously causes a strange
// initialization sequence if the popup owner is a tree/table editor:
//
// - The editor gets moved to its initial location based on the cell location,
// generating a COMPONENT_MOVED ComponentEvent.
// - You add the MouseEventHandler, which includes a ComponentEvent listener on
// the owner's hierarchy, including the editor.
// - ComponentEvent is asynchronous. The ComponentEvent generated from moving
// the editor to its initial position was placed on the event queue. So the
// ComponentEvent gets handled by the MouseEventHandler's ComponentEvent
// listener, even though it happened before the listener was added.
//
// I fixed it by calling addMouseEventHandler asynchronously, guaranteeing that
// any previously-generated event it may listen for has been removed from the
// event queue before the listener is added.
//
// This causes a couple of minor problems:
//
// - It is possible that hidePopupImmediately can be called synchronously before
// the asynchronous call to addMouseEventHandler is executed. This can cause
// NPEs because the listener handler methods dereference _window, which is set
// to null in hidePopupImmediately. So I added null checks on _window in the
// listener handler methods.
//
// - The removeMouseEventHandler method is called from hidePopupImmediately.
// That means it could be called before addMouseEventHandler is executed
// asynchronously; that would result in the listener not getting removed. So
// I changed the removeMouseEventHandler to an asynchronous call, as well.
//
// This issue appeared in the 1.8.3 release because you changed the
// COMPONENT_MOVED handler to hide the popup instead of moving it. Since you
// made this an option in the 1.8.4 release, all of this asynchronous code is
// needed.
//
// addMouseEventHandler()
SwingUtilities.invokeLater(new Runnable() {
public void run() {
addMouseEventHandler();
}
});
_componentListener = new ComponentAdapter() {
@Override
public void componentHidden(ComponentEvent e) {
hidePopup();
}
};
_escapeActionListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
Component owner = getActualOwner();
hidePopupImmediately(true);
if (owner != null) {
owner.requestFocus();
}
}
};
registerKeyboardAction(_escapeActionListener, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
if (_popupType == HEAVY_WEIGHT_POPUP) {
_window.addComponentListener(_componentListener);
_windowListener = new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
hidePopup();
}
};
_window.addWindowListener(_windowListener);
}
Component owner = getActualOwner();
if (owner != null) {
_ownerComponentListener = new ComponentAdapter() {
@Override
public void componentHidden(ComponentEvent e) {
ancestorHidden();
}
@Override
public void componentMoved(ComponentEvent e) {
if (_actualOwnerLocation == null || _actualOwner == null || !_actualOwner.getLocationOnScreen().equals(_actualOwnerLocation)) {
ancestorMoved();
}
}
};
owner.addComponentListener(_ownerComponentListener);
_hierarchyListener = new HierarchyListener() {
public void hierarchyChanged(HierarchyEvent e) {
ancestorHidden();
}
};
owner.addHierarchyListener(_hierarchyListener);
}
_popupResizeListener = new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
removeComponentListener(_popupResizeListener);
contentResized();
addComponentListener(_popupResizeListener);
}
};
addComponentListener(_popupResizeListener);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "installListeners" | "protected void installListeners() {
//David: Adding the MouseEventHandler synchronously causes a strange
// initialization sequence if the popup owner is a tree/table editor:
//
// - The editor gets moved to its initial location based on the cell location,
// generating a COMPONENT_MOVED ComponentEvent.
// - You add the MouseEventHandler, which includes a ComponentEvent listener on
// the owner's hierarchy, including the editor.
// - ComponentEvent is asynchronous. The ComponentEvent generated from moving
// the editor to its initial position was placed on the event queue. So the
// ComponentEvent gets handled by the MouseEventHandler's ComponentEvent
// listener, even though it happened before the listener was added.
//
// I fixed it by calling addMouseEventHandler asynchronously, guaranteeing that
// any previously-generated event it may listen for has been removed from the
// event queue before the listener is added.
//
// This causes a couple of minor problems:
//
// - It is possible that hidePopupImmediately can be called synchronously before
// the asynchronous call to addMouseEventHandler is executed. This can cause
// NPEs because the listener handler methods dereference _window, which is set
// to null in hidePopupImmediately. So I added null checks on _window in the
// listener handler methods.
//
// - The removeMouseEventHandler method is called from hidePopupImmediately.
// That means it could be called before addMouseEventHandler is executed
// asynchronously; that would result in the listener not getting removed. So
// I changed the removeMouseEventHandler to an asynchronous call, as well.
//
// This issue appeared in the 1.8.3 release because you changed the
// COMPONENT_MOVED handler to hide the popup instead of moving it. Since you
// made this an option in the 1.8.4 release, all of this asynchronous code is
// needed.
//
// addMouseEventHandler()
SwingUtilities.invokeLater(new Runnable() {
public void run() {
addMouseEventHandler();
}
});
_componentListener = new ComponentAdapter() {
@Override
public void componentHidden(ComponentEvent e) {
hidePopup();
}
};
_escapeActionListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
<MASK>hidePopupImmediately(true);</MASK>
Component owner = getActualOwner();
if (owner != null) {
owner.requestFocus();
}
}
};
registerKeyboardAction(_escapeActionListener, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
if (_popupType == HEAVY_WEIGHT_POPUP) {
_window.addComponentListener(_componentListener);
_windowListener = new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
hidePopup();
}
};
_window.addWindowListener(_windowListener);
}
Component owner = getActualOwner();
if (owner != null) {
_ownerComponentListener = new ComponentAdapter() {
@Override
public void componentHidden(ComponentEvent e) {
ancestorHidden();
}
@Override
public void componentMoved(ComponentEvent e) {
if (_actualOwnerLocation == null || _actualOwner == null || !_actualOwner.getLocationOnScreen().equals(_actualOwnerLocation)) {
ancestorMoved();
}
}
};
owner.addComponentListener(_ownerComponentListener);
_hierarchyListener = new HierarchyListener() {
public void hierarchyChanged(HierarchyEvent e) {
ancestorHidden();
}
};
owner.addHierarchyListener(_hierarchyListener);
}
_popupResizeListener = new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
removeComponentListener(_popupResizeListener);
contentResized();
addComponentListener(_popupResizeListener);
}
};
addComponentListener(_popupResizeListener);
}" |
Inversion-Mutation | megadiff | "public void actionPerformed(ActionEvent e) {
Component owner = getActualOwner();
hidePopupImmediately(true);
if (owner != null) {
owner.requestFocus();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "actionPerformed" | "public void actionPerformed(ActionEvent e) {
<MASK>hidePopupImmediately(true);</MASK>
Component owner = getActualOwner();
if (owner != null) {
owner.requestFocus();
}
}" |
Inversion-Mutation | megadiff | "@Override
protected void onPostResume() {
super.onPostResume();
if (!Flags.checkAndClear(Flags.TLA_DISMISSED_FROM_TASK_EDIT)) {
TaskEditFragment tea = getTaskEditFragment();
if (tea != null)
onBackPressed();
}
if (getIntent().hasExtra(NEW_LIST)) {
Filter newList = getIntent().getParcelableExtra(NEW_LIST);
getIntent().removeExtra(NEW_LIST);
onFilterItemClicked(newList);
}
if (getIntent().hasExtra(OPEN_TASK)) {
long id = getIntent().getLongExtra(OPEN_TASK, 0);
if (id > 0) {
onTaskListItemClicked(id);
} else {
TaskListFragment tlf = getTaskListFragment();
if (tlf != null) {
Task result = tlf.quickAddBar.quickAddTask("", true); //$NON-NLS-1$
if (result != null)
onTaskListItemClicked(result.getId());
}
}
getIntent().removeExtra(OPEN_TASK);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onPostResume" | "@Override
protected void onPostResume() {
super.onPostResume();
if (!Flags.checkAndClear(Flags.TLA_DISMISSED_FROM_TASK_EDIT)) {
TaskEditFragment tea = getTaskEditFragment();
if (tea != null)
onBackPressed();
}
if (getIntent().hasExtra(NEW_LIST)) {
Filter newList = getIntent().getParcelableExtra(NEW_LIST);
<MASK>onFilterItemClicked(newList);</MASK>
getIntent().removeExtra(NEW_LIST);
}
if (getIntent().hasExtra(OPEN_TASK)) {
long id = getIntent().getLongExtra(OPEN_TASK, 0);
if (id > 0) {
onTaskListItemClicked(id);
} else {
TaskListFragment tlf = getTaskListFragment();
if (tlf != null) {
Task result = tlf.quickAddBar.quickAddTask("", true); //$NON-NLS-1$
if (result != null)
onTaskListItemClicked(result.getId());
}
}
getIntent().removeExtra(OPEN_TASK);
}
}" |
Inversion-Mutation | megadiff | "private void move(int position, UIComponent uiSource, final UIContainer uiTarget, PortalRequestContext pcontext) {
org.exoplatform.portal.webui.container.UIContainer uiParent = uiSource.getParent();
List<UIComponent> children = uiTarget.getChildren();
if (uiParent == uiTarget) {
int currentIdx = children.indexOf(uiSource);
if (position != currentIdx) {
children.remove(currentIdx);
if (position > children.size()) {
children.add(uiSource);
} else {
children.add(position, uiSource);
}
}
} else {
boolean hadParent = uiSource.getParent() != null;
children.add(position, uiSource);
if (hadParent) {
tidyUp(pcontext, uiSource);
}
uiSource.setParent(uiTarget);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "move" | "private void move(int position, UIComponent uiSource, final UIContainer uiTarget, PortalRequestContext pcontext) {
org.exoplatform.portal.webui.container.UIContainer uiParent = uiSource.getParent();
List<UIComponent> children = uiTarget.getChildren();
if (uiParent == uiTarget) {
int currentIdx = children.indexOf(uiSource);
if (position != currentIdx) {
children.remove(currentIdx);
if (position > children.size()) {
children.add(uiSource);
} else {
children.add(position, uiSource);
}
}
} else {
boolean hadParent = uiSource.getParent() != null;
<MASK>uiSource.setParent(uiTarget);</MASK>
children.add(position, uiSource);
if (hadParent) {
tidyUp(pcontext, uiSource);
}
}
}" |
Inversion-Mutation | megadiff | "public void asyncClose(final CloseCallback origCb, final Object origCtx) {
CloseCallback cb = new CloseCallback() {
@Override
public void closeComplete(int rc, LedgerHandle lh, Object ctx) {
if (rc == BKException.Code.OK) {
if (refCount.decrementAndGet() == 0) {
// Closed a ledger
bk.getStatsLogger().getSimpleStatLogger(BookkeeperClientSimpleStatType.NUM_OPEN_LEDGERS).dec();
}
}
origCb.closeComplete(rc, lh, origCtx);
}
};
asyncCloseInternal(cb, origCtx, BKException.Code.LedgerClosedException);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "asyncClose" | "public void asyncClose(final CloseCallback origCb, final Object origCtx) {
CloseCallback cb = new CloseCallback() {
@Override
public void closeComplete(int rc, LedgerHandle lh, Object ctx) {
if (rc == BKException.Code.OK) {
if (refCount.decrementAndGet() == 0) {
// Closed a ledger
bk.getStatsLogger().getSimpleStatLogger(BookkeeperClientSimpleStatType.NUM_OPEN_LEDGERS).dec();
}
<MASK>origCb.closeComplete(rc, lh, origCtx);</MASK>
}
}
};
asyncCloseInternal(cb, origCtx, BKException.Code.LedgerClosedException);
}" |
Inversion-Mutation | megadiff | "@Override
public void closeComplete(int rc, LedgerHandle lh, Object ctx) {
if (rc == BKException.Code.OK) {
if (refCount.decrementAndGet() == 0) {
// Closed a ledger
bk.getStatsLogger().getSimpleStatLogger(BookkeeperClientSimpleStatType.NUM_OPEN_LEDGERS).dec();
}
}
origCb.closeComplete(rc, lh, origCtx);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "closeComplete" | "@Override
public void closeComplete(int rc, LedgerHandle lh, Object ctx) {
if (rc == BKException.Code.OK) {
if (refCount.decrementAndGet() == 0) {
// Closed a ledger
bk.getStatsLogger().getSimpleStatLogger(BookkeeperClientSimpleStatType.NUM_OPEN_LEDGERS).dec();
}
<MASK>origCb.closeComplete(rc, lh, origCtx);</MASK>
}
}" |
Inversion-Mutation | megadiff | "protected void validateSettings() {
final Validator validator = getValidator(createTaskRepository());
if (validator == null) {
return;
}
try {
getWizard().getContainer().run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
monitor.beginTask(Messages.AbstractRepositorySettingsPage_Validating_server_settings,
IProgressMonitor.UNKNOWN);
try {
validator.run(monitor);
if (validator.getStatus() == null) {
validator.setStatus(Status.OK_STATUS);
}
} catch (CoreException e) {
validator.setStatus(e.getStatus());
} catch (OperationCanceledException e) {
validator.setStatus(Status.CANCEL_STATUS);
throw new InterruptedException();
} catch (Exception e) {
throw new InvocationTargetException(e);
} finally {
monitor.done();
}
}
});
} catch (InvocationTargetException e) {
StatusHandler.fail(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN,
Messages.AbstractRepositorySettingsPage_Internal_error_validating_repository, e.getCause()));
return;
} catch (InterruptedException e) {
// canceled
return;
}
getWizard().getContainer().updateButtons();
applyValidatorResult(validator);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "validateSettings" | "protected void validateSettings() {
final Validator validator = getValidator(createTaskRepository());
if (validator == null) {
return;
}
try {
getWizard().getContainer().run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
monitor.beginTask(Messages.AbstractRepositorySettingsPage_Validating_server_settings,
IProgressMonitor.UNKNOWN);
try {
validator.run(monitor);
if (validator.getStatus() == null) {
validator.setStatus(Status.OK_STATUS);
}
} catch (CoreException e) {
validator.setStatus(e.getStatus());
} catch (OperationCanceledException e) {
validator.setStatus(Status.CANCEL_STATUS);
throw new InterruptedException();
} catch (Exception e) {
throw new InvocationTargetException(e);
} finally {
monitor.done();
}
}
});
} catch (InvocationTargetException e) {
StatusHandler.fail(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN,
Messages.AbstractRepositorySettingsPage_Internal_error_validating_repository, e.getCause()));
return;
} catch (InterruptedException e) {
// canceled
return;
}
<MASK>applyValidatorResult(validator);</MASK>
getWizard().getContainer().updateButtons();
}" |
Inversion-Mutation | megadiff | "public void destroy() {
mContent.destroy();
disableRemoteDebugging();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "destroy" | "public void destroy() {
<MASK>disableRemoteDebugging();</MASK>
mContent.destroy();
}" |
Inversion-Mutation | megadiff | "public RunResult run(String className, String[] args, final String classpath, boolean useLTW) {
lastRunResult = null;
StringBuffer cp = new StringBuffer();
if (classpath != null) {
// allow replacing this special variable, rather than copying all files to allow tests of jars that don't end in .jar
cp.append(substituteSandbox(classpath));
cp.append(File.pathSeparator);
}
cp.append(ajc.getSandboxDirectory().getAbsolutePath());
getAnyJars(ajc.getSandboxDirectory(),cp);
URLClassLoader sandboxLoader;
URLClassLoader testLoader = (URLClassLoader)getClass().getClassLoader();
ClassLoader parentLoader = testLoader.getParent();
/* Sandbox -> AspectJ -> Extension -> Bootstrap */
if (useLTW) {
/*
* Create a new AspectJ class loader using the existing test CLASSPATH
* and any missing Java 5 projects
*/
URL[] testUrls = testLoader.getURLs();
URL[] java5Urls = getURLs(JAVA5_CLASSPATH_ENTRIES);
URL[] urls = new URL[testUrls.length + java5Urls.length];
System.arraycopy(testUrls,0,urls,0,testUrls.length);
System.arraycopy(java5Urls,0,urls,testUrls.length,java5Urls.length);
// ClassLoader aspectjLoader = new URLClassLoader(getURLs(DEFAULT_CLASSPATH_ENTRIES),parent);
ClassLoader aspectjLoader = new URLClassLoader(urls,parentLoader);
URL[] sandboxUrls = getURLs(cp.toString());
sandboxLoader = createWeavingClassLoader(sandboxUrls,aspectjLoader);
// sandboxLoader = createWeavingClassLoader(sandboxUrls,testLoader);
}
/* Sandbox + AspectJ -> Extension -> Bootstrap */
else {
cp.append(DEFAULT_CLASSPATH_ENTRIES);
URL[] urls = getURLs(cp.toString());
sandboxLoader = new URLClassLoader(urls,parentLoader);
}
StringBuffer command = new StringBuffer("java -classpath ");
command.append(cp.toString());
command.append(" ");
command.append(className);
for (int i = 0; i < args.length; i++) {
command.append(" ");
command.append(args[i]);
}
ByteArrayOutputStream baosOut = new ByteArrayOutputStream();
ByteArrayOutputStream baosErr = new ByteArrayOutputStream();
ClassLoader contexClassLoader = Thread.currentThread().getContextClassLoader();
try {
try {
Class testerClass = sandboxLoader.loadClass("org.aspectj.testing.Tester");
Method setBaseDir = testerClass.getDeclaredMethod("setBASEDIR",new Class[] {File.class});
setBaseDir.invoke(null,new Object[] {ajc.getSandboxDirectory()});
} catch (InvocationTargetException itEx) {
fail ("Unable to prepare org.aspectj.testing.Tester for test run: " + itEx.getTargetException());
} catch (Exception ex) {
fail ("Unable to prepare org.aspectj.testing.Tester for test run: " + ex);
}
startCapture(baosErr,baosOut);
/* Frameworks like XML use context class loader for dynamic loading */
Thread.currentThread().setContextClassLoader(sandboxLoader);
Class toRun = sandboxLoader.loadClass(className);
Method mainMethod = toRun.getMethod("main",new Class[] {String[].class});
mainMethod.invoke(null,new Object[] {args});
} catch(ClassNotFoundException cnf) {
fail("Can't find class: " + className);
} catch(NoSuchMethodException nsm) {
fail(className + " does not have a main method");
} catch (IllegalAccessException illEx) {
fail("main method in class " + className + " is not public");
} catch (InvocationTargetException invTgt) {
// the main method threw an exception...
fail("Exception thrown by " + className + ".main(String[]) :" + invTgt.getTargetException());
} finally {
Thread.currentThread().setContextClassLoader(contexClassLoader);
stopCapture(baosErr,baosOut);
lastRunResult = new RunResult(command.toString(),new String(baosOut.toByteArray()),new String(baosErr.toByteArray()));
}
return lastRunResult;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run" | "public RunResult run(String className, String[] args, final String classpath, boolean useLTW) {
lastRunResult = null;
StringBuffer cp = new StringBuffer();
if (classpath != null) {
// allow replacing this special variable, rather than copying all files to allow tests of jars that don't end in .jar
cp.append(substituteSandbox(classpath));
cp.append(File.pathSeparator);
}
cp.append(ajc.getSandboxDirectory().getAbsolutePath());
getAnyJars(ajc.getSandboxDirectory(),cp);
URLClassLoader sandboxLoader;
URLClassLoader testLoader = (URLClassLoader)getClass().getClassLoader();
ClassLoader parentLoader = testLoader.getParent();
/* Sandbox -> AspectJ -> Extension -> Bootstrap */
if (useLTW) {
/*
* Create a new AspectJ class loader using the existing test CLASSPATH
* and any missing Java 5 projects
*/
URL[] testUrls = testLoader.getURLs();
URL[] java5Urls = getURLs(JAVA5_CLASSPATH_ENTRIES);
URL[] urls = new URL[testUrls.length + java5Urls.length];
System.arraycopy(testUrls,0,urls,0,testUrls.length);
System.arraycopy(java5Urls,0,urls,testUrls.length,java5Urls.length);
// ClassLoader aspectjLoader = new URLClassLoader(getURLs(DEFAULT_CLASSPATH_ENTRIES),parent);
ClassLoader aspectjLoader = new URLClassLoader(urls,parentLoader);
URL[] sandboxUrls = getURLs(cp.toString());
sandboxLoader = createWeavingClassLoader(sandboxUrls,aspectjLoader);
// sandboxLoader = createWeavingClassLoader(sandboxUrls,testLoader);
}
/* Sandbox + AspectJ -> Extension -> Bootstrap */
else {
cp.append(DEFAULT_CLASSPATH_ENTRIES);
URL[] urls = getURLs(cp.toString());
sandboxLoader = new URLClassLoader(urls,parentLoader);
}
StringBuffer command = new StringBuffer("java -classpath ");
command.append(cp.toString());
command.append(" ");
command.append(className);
for (int i = 0; i < args.length; i++) {
command.append(" ");
command.append(args[i]);
}
ByteArrayOutputStream baosOut = new ByteArrayOutputStream();
ByteArrayOutputStream baosErr = new ByteArrayOutputStream();
ClassLoader contexClassLoader = Thread.currentThread().getContextClassLoader();
try {
try {
Class testerClass = sandboxLoader.loadClass("org.aspectj.testing.Tester");
Method setBaseDir = testerClass.getDeclaredMethod("setBASEDIR",new Class[] {File.class});
setBaseDir.invoke(null,new Object[] {ajc.getSandboxDirectory()});
} catch (InvocationTargetException itEx) {
fail ("Unable to prepare org.aspectj.testing.Tester for test run: " + itEx.getTargetException());
} catch (Exception ex) {
fail ("Unable to prepare org.aspectj.testing.Tester for test run: " + ex);
}
startCapture(baosErr,baosOut);
/* Frameworks like XML use context class loader for dynamic loading */
Thread.currentThread().setContextClassLoader(sandboxLoader);
Class toRun = sandboxLoader.loadClass(className);
Method mainMethod = toRun.getMethod("main",new Class[] {String[].class});
mainMethod.invoke(null,new Object[] {args});
<MASK>lastRunResult = new RunResult(command.toString(),new String(baosOut.toByteArray()),new String(baosErr.toByteArray()));</MASK>
} catch(ClassNotFoundException cnf) {
fail("Can't find class: " + className);
} catch(NoSuchMethodException nsm) {
fail(className + " does not have a main method");
} catch (IllegalAccessException illEx) {
fail("main method in class " + className + " is not public");
} catch (InvocationTargetException invTgt) {
// the main method threw an exception...
fail("Exception thrown by " + className + ".main(String[]) :" + invTgt.getTargetException());
} finally {
Thread.currentThread().setContextClassLoader(contexClassLoader);
stopCapture(baosErr,baosOut);
}
return lastRunResult;
}" |
Inversion-Mutation | megadiff | "@Override
protected void
processUnsolicited (Parcel p) {
Object ret;
int dataPosition = p.dataPosition(); // save off position within the Parcel
int response = p.readInt();
switch(response) {
case RIL_UNSOL_RIL_CONNECTED: // Fix for NV/RUIM setting on CDMA SIM devices
// skip getcdmascriptionsource as if qualcomm handles it in the ril binary
ret = responseInts(p);
setRadioPower(false, null);
setPreferredNetworkType(mPreferredNetworkType, null);
notifyRegistrantsRilConnectionChanged(((int[])ret)[0]);
isGSM = (mPhoneType != RILConstants.CDMA_PHONE);
samsungDriverCall = (needsOldRilFeature("newDriverCall") && !isGSM) || mRilVersion < 7 ? false : true;
break;
case RIL_UNSOL_NITZ_TIME_RECEIVED:
handleNitzTimeReceived(p);
break;
default:
// Rewind the Parcel
p.setDataPosition(dataPosition);
// Forward responses that we are not overriding to the super class
super.processUnsolicited(p);
return;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "processUnsolicited" | "@Override
protected void
processUnsolicited (Parcel p) {
Object ret;
int dataPosition = p.dataPosition(); // save off position within the Parcel
int response = p.readInt();
switch(response) {
case RIL_UNSOL_RIL_CONNECTED: // Fix for NV/RUIM setting on CDMA SIM devices
// skip getcdmascriptionsource as if qualcomm handles it in the ril binary
ret = responseInts(p);
setRadioPower(false, null);
setPreferredNetworkType(mPreferredNetworkType, null);
notifyRegistrantsRilConnectionChanged(((int[])ret)[0]);
<MASK>samsungDriverCall = (needsOldRilFeature("newDriverCall") && !isGSM) || mRilVersion < 7 ? false : true;</MASK>
isGSM = (mPhoneType != RILConstants.CDMA_PHONE);
break;
case RIL_UNSOL_NITZ_TIME_RECEIVED:
handleNitzTimeReceived(p);
break;
default:
// Rewind the Parcel
p.setDataPosition(dataPosition);
// Forward responses that we are not overriding to the super class
super.processUnsolicited(p);
return;
}
}" |
Inversion-Mutation | megadiff | "public RemoteFilter(String rulesSource, String hostname, int port,
String user, String password, boolean ssl)
throws RemoteFilterException {
this.setDaemon(true);
rules = rulesSource;
this.hostname = hostname;
this.port = port;
this.user = user;
this.password = password;
this.ssl = ssl;
store = getRemoteStore();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "RemoteFilter" | "public RemoteFilter(String rulesSource, String hostname, int port,
String user, String password, boolean ssl)
throws RemoteFilterException {
this.setDaemon(true);
<MASK>store = getRemoteStore();</MASK>
rules = rulesSource;
this.hostname = hostname;
this.port = port;
this.user = user;
this.password = password;
this.ssl = ssl;
}" |
Inversion-Mutation | megadiff | "protected ActionForward performAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
Transaction tx = HibernateUtil.getSession().beginTransaction();
String forward = FWD_SUCCESS;
String referer = request.getParameter("referer");
List<IResultUpdate> updaters = ResultUpdateRegister.getRegisteredUpdaters();
BaseActionForm dynaForm = (BaseActionForm) form;
resultValidation.setSupportReferrals(supportReferrals);
resultValidation.setUseTechnicianName(useTechnicianName);
ResultsPaging paging = new ResultsPaging();
paging.updatePagedResults(request, dynaForm);
List<TestResultItem> tests = paging.getResults(request);
setModifiedItems(tests);
ActionMessages errors = resultValidation.validateModifiedItems(modifiedItems);
if (errors.size() > 0) {
saveErrors(request, errors);
request.setAttribute(Globals.ERROR_KEY, errors);
return mapping.findForward(FWD_VALIDATION_ERROR);
}
initializeLists();
createResultsFromItems();
try {
for (ResultSet resultSet : newResults) {
resultDAO.insertData(resultSet.result);
if (resultSet.signature != null) {
resultSet.signature.setResultId(resultSet.result.getId());
resultSigDAO.insertData(resultSet.signature);
}
if (resultSet.testKit != null && resultSet.testKit.getInventoryLocationId() != null) {
resultSet.testKit.setResultId(resultSet.result.getId());
resultInventoryDAO.insertData(resultSet.testKit);
}
if (resultSet.note != null) {
resultSet.note.setReferenceId(resultSet.result.getId());
noteDAO.insertData(resultSet.note);
}
if (resultSet.newReferral != null) {
insertNewReferralAndReferralResult(resultSet);
}
}
for (ResultSet resultSet : modifiedResults) {
resultDAO.updateData(resultSet.result);
if (resultSet.signature != null) {
resultSet.signature.setResultId(resultSet.result.getId());
if (resultSet.alwaysInsertSignature) {
resultSigDAO.insertData(resultSet.signature);
} else {
resultSigDAO.updateData(resultSet.signature);
}
}
if (resultSet.testKit != null && resultSet.testKit.getInventoryLocationId() != null) {
resultSet.testKit.setResultId(resultSet.result.getId());
if (resultSet.testKit.getId() == null) {
resultInventoryDAO.insertData(resultSet.testKit);
} else {
resultInventoryDAO.updateData(resultSet.testKit);
}
}
if (resultSet.note != null) {
resultSet.note.setReferenceId(resultSet.result.getId());
if (resultSet.note.getId() == null) {
noteDAO.insertData(resultSet.note);
} else {
noteDAO.updateData(resultSet.note);
}
}
if (resultSet.newReferral != null) {
// we can't just create a referral with a blank result,
// because referral page assumes a referralResult and a
// result.
insertNewReferralAndReferralResult(resultSet);
}
if (resultSet.existingReferral != null) {
referralDAO.updateData(resultSet.existingReferral);
}
}
for (Analysis analysis : modifiedAnalysis) {
analysisDAO.updateData(analysis);
}
removeDeletedResults();
setTestReflexes();
setSampleStatus();
for (IResultUpdate updater : updaters) {
updater.transactionalUpdate(this);
}
tx.commit();
} catch (LIMSRuntimeException lre) {
logger.error("Could not update Results", lre);
tx.rollback();
ActionError error = null;
if (lre instanceof LIMSDuplicateRecordException) {
//error = new ActionError("errors.StaleViewException", ((LIMSDuplicateRecordException) lre).getObjectDescription(), "http://google.com?q=mujir", null);
error = new ActionError("errors.StaleViewException", null, null);
}
if (lre.getException() instanceof StaleObjectStateException) {
error = new ActionError("errors.OptimisticLockException", null, null);
}
if (error == null) {
lre.printStackTrace();
error = new ActionError("errors.UpdateException", null, null);
}
errors.add(ActionMessages.GLOBAL_MESSAGE, error);
saveErrors(request, errors);
request.setAttribute(Globals.ERROR_KEY, errors);
return mapping.findForward("error");
}
for (IResultUpdate updater : updaters) {
updater.postTransactionalCommitUpdate(this);
}
setSuccessFlag(request, forward);
if(referer != null && referer.matches("LabDashboard")) {
return mapping.findForward(FWD_DASHBOARD);
}
if (GenericValidator.isBlankOrNull(dynaForm.getString("logbookType"))) {
return mapping.findForward(forward);
} else {
Map<String, String> params = new HashMap<String, String>();
params.put("type", dynaForm.getString("logbookType"));
params.put("forward", forward);
return getForwardWithParameters(mapping.findForward(forward), params);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "performAction" | "protected ActionForward performAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
String forward = FWD_SUCCESS;
String referer = request.getParameter("referer");
List<IResultUpdate> updaters = ResultUpdateRegister.getRegisteredUpdaters();
BaseActionForm dynaForm = (BaseActionForm) form;
resultValidation.setSupportReferrals(supportReferrals);
resultValidation.setUseTechnicianName(useTechnicianName);
ResultsPaging paging = new ResultsPaging();
paging.updatePagedResults(request, dynaForm);
List<TestResultItem> tests = paging.getResults(request);
setModifiedItems(tests);
ActionMessages errors = resultValidation.validateModifiedItems(modifiedItems);
if (errors.size() > 0) {
saveErrors(request, errors);
request.setAttribute(Globals.ERROR_KEY, errors);
return mapping.findForward(FWD_VALIDATION_ERROR);
}
initializeLists();
createResultsFromItems();
<MASK>Transaction tx = HibernateUtil.getSession().beginTransaction();</MASK>
try {
for (ResultSet resultSet : newResults) {
resultDAO.insertData(resultSet.result);
if (resultSet.signature != null) {
resultSet.signature.setResultId(resultSet.result.getId());
resultSigDAO.insertData(resultSet.signature);
}
if (resultSet.testKit != null && resultSet.testKit.getInventoryLocationId() != null) {
resultSet.testKit.setResultId(resultSet.result.getId());
resultInventoryDAO.insertData(resultSet.testKit);
}
if (resultSet.note != null) {
resultSet.note.setReferenceId(resultSet.result.getId());
noteDAO.insertData(resultSet.note);
}
if (resultSet.newReferral != null) {
insertNewReferralAndReferralResult(resultSet);
}
}
for (ResultSet resultSet : modifiedResults) {
resultDAO.updateData(resultSet.result);
if (resultSet.signature != null) {
resultSet.signature.setResultId(resultSet.result.getId());
if (resultSet.alwaysInsertSignature) {
resultSigDAO.insertData(resultSet.signature);
} else {
resultSigDAO.updateData(resultSet.signature);
}
}
if (resultSet.testKit != null && resultSet.testKit.getInventoryLocationId() != null) {
resultSet.testKit.setResultId(resultSet.result.getId());
if (resultSet.testKit.getId() == null) {
resultInventoryDAO.insertData(resultSet.testKit);
} else {
resultInventoryDAO.updateData(resultSet.testKit);
}
}
if (resultSet.note != null) {
resultSet.note.setReferenceId(resultSet.result.getId());
if (resultSet.note.getId() == null) {
noteDAO.insertData(resultSet.note);
} else {
noteDAO.updateData(resultSet.note);
}
}
if (resultSet.newReferral != null) {
// we can't just create a referral with a blank result,
// because referral page assumes a referralResult and a
// result.
insertNewReferralAndReferralResult(resultSet);
}
if (resultSet.existingReferral != null) {
referralDAO.updateData(resultSet.existingReferral);
}
}
for (Analysis analysis : modifiedAnalysis) {
analysisDAO.updateData(analysis);
}
removeDeletedResults();
setTestReflexes();
setSampleStatus();
for (IResultUpdate updater : updaters) {
updater.transactionalUpdate(this);
}
tx.commit();
} catch (LIMSRuntimeException lre) {
logger.error("Could not update Results", lre);
tx.rollback();
ActionError error = null;
if (lre instanceof LIMSDuplicateRecordException) {
//error = new ActionError("errors.StaleViewException", ((LIMSDuplicateRecordException) lre).getObjectDescription(), "http://google.com?q=mujir", null);
error = new ActionError("errors.StaleViewException", null, null);
}
if (lre.getException() instanceof StaleObjectStateException) {
error = new ActionError("errors.OptimisticLockException", null, null);
}
if (error == null) {
lre.printStackTrace();
error = new ActionError("errors.UpdateException", null, null);
}
errors.add(ActionMessages.GLOBAL_MESSAGE, error);
saveErrors(request, errors);
request.setAttribute(Globals.ERROR_KEY, errors);
return mapping.findForward("error");
}
for (IResultUpdate updater : updaters) {
updater.postTransactionalCommitUpdate(this);
}
setSuccessFlag(request, forward);
if(referer != null && referer.matches("LabDashboard")) {
return mapping.findForward(FWD_DASHBOARD);
}
if (GenericValidator.isBlankOrNull(dynaForm.getString("logbookType"))) {
return mapping.findForward(forward);
} else {
Map<String, String> params = new HashMap<String, String>();
params.put("type", dynaForm.getString("logbookType"));
params.put("forward", forward);
return getForwardWithParameters(mapping.findForward(forward), params);
}
}" |
Inversion-Mutation | megadiff | "@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
String currentQuiz = getIntent().getStringExtra("quizType");
String textInfo = null;
// Retrieves everything from the text file
if (currentQuiz.equals("profileQuiz"))
textInfo = readTextFile("profile.txt");
else if (currentQuiz.equals("articQuiz"))
textInfo = readTextFile("bering.txt");
else if (currentQuiz.equals("desertQuiz"))
textInfo = readTextFile("desert.txt");
else if (currentQuiz.equals("forestQuiz"))
textInfo = readTextFile("forest.txt");
else if (currentQuiz.equals("swampQuiz"))
textInfo = readTextFile("swamp.txt");
else if (currentQuiz.equals("mountainQuiz"))
textInfo = readTextFile("mountain.txt");
// Parses the file and sets the question and answer
mQuestion = parseFileSetQuestionAndAnswer(textInfo);
// Everything is read and parsed, put into activity
mQtv = (TextView) findViewById(R.id.questionTV);
mAns1 = (RadioButton) findViewById(R.id.radioButton1);
mAns2 = (RadioButton) findViewById(R.id.radioButton2);
mAns3 = (RadioButton) findViewById(R.id.radioButton3);
mAns4 = (RadioButton) findViewById(R.id.radioButton4);
addQuestionAnswersToActivity();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCreate" | "@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
<MASK>String textInfo = null;</MASK>
String currentQuiz = getIntent().getStringExtra("quizType");
// Retrieves everything from the text file
if (currentQuiz.equals("profileQuiz"))
textInfo = readTextFile("profile.txt");
else if (currentQuiz.equals("articQuiz"))
textInfo = readTextFile("bering.txt");
else if (currentQuiz.equals("desertQuiz"))
textInfo = readTextFile("desert.txt");
else if (currentQuiz.equals("forestQuiz"))
textInfo = readTextFile("forest.txt");
else if (currentQuiz.equals("swampQuiz"))
textInfo = readTextFile("swamp.txt");
else if (currentQuiz.equals("mountainQuiz"))
textInfo = readTextFile("mountain.txt");
// Parses the file and sets the question and answer
mQuestion = parseFileSetQuestionAndAnswer(textInfo);
// Everything is read and parsed, put into activity
mQtv = (TextView) findViewById(R.id.questionTV);
mAns1 = (RadioButton) findViewById(R.id.radioButton1);
mAns2 = (RadioButton) findViewById(R.id.radioButton2);
mAns3 = (RadioButton) findViewById(R.id.radioButton3);
mAns4 = (RadioButton) findViewById(R.id.radioButton4);
addQuestionAnswersToActivity();
}" |
Inversion-Mutation | megadiff | "public void applyChanges(){
axis.setTitle(titleText.getText());
axis.setFont(scaleFont);
axis.setTitleFont(titleFont);
axis.setForegroundColor(XYGraphMediaFactory.getInstance().getColor(
axisColorSelector.getColorValue()));
axis.setPrimarySide(primaryButton.getSelection());
axis.setLogScale(logButton.getSelection());
axis.setAutoScale(autoScaleButton.getSelection());
if(autoScaleButton.getSelection())
axis.setAutoScaleThreshold(maxOrAutoScaleThrText.getDoubleValue());
else
axis.setRange(minText.getDoubleValue(), maxOrAutoScaleThrText.getDoubleValue());
axis.setDateEnabled(dateEnabledButton.getSelection());
axis.setAutoFormat(autoFormat.getSelection());
if(!autoFormat.getSelection()){
String saveFormat = axis.getFormatPattern();
try {
axis.setFormatPattern(formatText.getText());
axis.format(0);
} catch (Exception e) {
axis.setFormatPattern(saveFormat);
MessageBox mb = new MessageBox(Display.getCurrent().getActiveShell(),
SWT.ICON_ERROR | SWT.OK);
mb.setMessage("Failed to set format due to incorrect format pattern: "
+ e.getMessage());
mb.setText("Format pattern error!");
mb.open();
}
}
axis.setShowMajorGrid(showGridButton.getSelection());
axis.setDashGridLine(dashGridLineButton.getSelection());
axis.setMajorGridColor( XYGraphMediaFactory.getInstance().getColor(
gridColorSelector.getColorValue()));
axis.setVisible(showAxisButton.getSelection());
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "applyChanges" | "public void applyChanges(){
axis.setTitle(titleText.getText());
axis.setFont(scaleFont);
axis.setTitleFont(titleFont);
axis.setForegroundColor(XYGraphMediaFactory.getInstance().getColor(
axisColorSelector.getColorValue()));
axis.setPrimarySide(primaryButton.getSelection());
axis.setLogScale(logButton.getSelection());
axis.setAutoScale(autoScaleButton.getSelection());
if(autoScaleButton.getSelection())
axis.setAutoScaleThreshold(maxOrAutoScaleThrText.getDoubleValue());
else
axis.setRange(minText.getDoubleValue(), maxOrAutoScaleThrText.getDoubleValue());
axis.setDateEnabled(dateEnabledButton.getSelection());
axis.setAutoFormat(autoFormat.getSelection());
if(!autoFormat.getSelection()){
String saveFormat = axis.getFormatPattern();
<MASK>axis.setFormatPattern(formatText.getText());</MASK>
try {
axis.format(0);
} catch (Exception e) {
axis.setFormatPattern(saveFormat);
MessageBox mb = new MessageBox(Display.getCurrent().getActiveShell(),
SWT.ICON_ERROR | SWT.OK);
mb.setMessage("Failed to set format due to incorrect format pattern: "
+ e.getMessage());
mb.setText("Format pattern error!");
mb.open();
}
}
axis.setShowMajorGrid(showGridButton.getSelection());
axis.setDashGridLine(dashGridLineButton.getSelection());
axis.setMajorGridColor( XYGraphMediaFactory.getInstance().getColor(
gridColorSelector.getColorValue()));
axis.setVisible(showAxisButton.getSelection());
}" |
Inversion-Mutation | megadiff | "public void timestep() throws InterruptedException, KernelException, LogException {
synchronized (this) {
++time;
// Work out what the agents can see and hear (using the commands from the previous timestep).
// Wait for new commands
// Send commands to simulators/viewers and wait for updates
// Collate updates and broadcast to simulators/viewers
System.out.println("Timestep " + time);
System.out.println("Sending agent updates");
long start = System.currentTimeMillis();
sendAgentUpdates(time, agentCommandsLastTimestep);
long perceptionTime = System.currentTimeMillis();
System.out.println("Waiting for commands");
agentCommandsLastTimestep = waitForCommands(time);
log.writeRecord(new CommandsRecord(time, agentCommandsLastTimestep));
long commandsTime = System.currentTimeMillis();
System.out.println("Broadcasting commands");
Collection<Entity> updates = sendCommandsToViewersAndSimulators(time, agentCommandsLastTimestep);
log.writeRecord(new UpdatesRecord(time, updates));
long updatesTime = System.currentTimeMillis();
// Merge updates into world model
worldModel.merge(updates);
long mergeTime = System.currentTimeMillis();
System.out.println("Broadcasting updates");
sendUpdatesToViewersAndSimulators(time, updates);
long broadcastTime = System.currentTimeMillis();
System.out.println("Timestep " + time + " complete");
System.out.println("Perception took : " + (perceptionTime - start) + "ms");
System.out.println("Agent commands took : " + (commandsTime - perceptionTime) + "ms");
System.out.println("Simulator updates took : " + (updatesTime - commandsTime) + "ms");
System.out.println("World model merge took : " + (mergeTime - updatesTime) + "ms");
System.out.println("Update broadcast took : " + (broadcastTime - mergeTime) + "ms");
System.out.println("Total time : " + (broadcastTime - start) + "ms");
previous = new Timestep(time, agentCommandsLastTimestep, updates);
fireTimestepCompleted(previous);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "timestep" | "public void timestep() throws InterruptedException, KernelException, LogException {
synchronized (this) {
++time;
// Work out what the agents can see and hear (using the commands from the previous timestep).
// Wait for new commands
// Send commands to simulators/viewers and wait for updates
// Collate updates and broadcast to simulators/viewers
System.out.println("Timestep " + time);
System.out.println("Sending agent updates");
long start = System.currentTimeMillis();
sendAgentUpdates(time, agentCommandsLastTimestep);
long perceptionTime = System.currentTimeMillis();
System.out.println("Waiting for commands");
agentCommandsLastTimestep = waitForCommands(time);
log.writeRecord(new CommandsRecord(time, agentCommandsLastTimestep));
long commandsTime = System.currentTimeMillis();
System.out.println("Broadcasting commands");
Collection<Entity> updates = sendCommandsToViewersAndSimulators(time, agentCommandsLastTimestep);
log.writeRecord(new UpdatesRecord(time, updates));
long updatesTime = System.currentTimeMillis();
// Merge updates into world model
<MASK>System.out.println("Broadcasting updates");</MASK>
worldModel.merge(updates);
long mergeTime = System.currentTimeMillis();
sendUpdatesToViewersAndSimulators(time, updates);
long broadcastTime = System.currentTimeMillis();
System.out.println("Timestep " + time + " complete");
System.out.println("Perception took : " + (perceptionTime - start) + "ms");
System.out.println("Agent commands took : " + (commandsTime - perceptionTime) + "ms");
System.out.println("Simulator updates took : " + (updatesTime - commandsTime) + "ms");
System.out.println("World model merge took : " + (mergeTime - updatesTime) + "ms");
System.out.println("Update broadcast took : " + (broadcastTime - mergeTime) + "ms");
System.out.println("Total time : " + (broadcastTime - start) + "ms");
previous = new Timestep(time, agentCommandsLastTimestep, updates);
fireTimestepCompleted(previous);
}
}" |
Inversion-Mutation | megadiff | "public static String getAt(Matcher matcher, int idx) {
idx = normaliseIndex(idx, matcher.groupCount());
// are we using groups?
if (matcher.groupCount() > 0) {
// yes, so return the specified group
matcher.find();
return matcher.group(idx);
} else {
// not using groups, so return the nth
// occurrence of the pattern
matcher.reset();
for (int i = 0; i <= idx; i++) {
matcher.find();
}
return matcher.group();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getAt" | "public static String getAt(Matcher matcher, int idx) {
<MASK>matcher.reset();</MASK>
idx = normaliseIndex(idx, matcher.groupCount());
// are we using groups?
if (matcher.groupCount() > 0) {
// yes, so return the specified group
matcher.find();
return matcher.group(idx);
} else {
// not using groups, so return the nth
// occurrence of the pattern
for (int i = 0; i <= idx; i++) {
matcher.find();
}
return matcher.group();
}
}" |
Inversion-Mutation | megadiff | "private static float parseTime(Element testCase) {
String time = testCase.attributeValue("time");
if(time!=null) {
time = time.replace(",","");
try {
return Float.parseFloat(time);
} catch (NumberFormatException e) {
try {
return new DecimalFormat().parse(time).floatValue();
} catch (ParseException x) {
// hmm, don't know what this format is.
}
}
}
return 0.0f;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "parseTime" | "private static float parseTime(Element testCase) {
String time = testCase.attributeValue("time");
<MASK>time = time.replace(",","");</MASK>
if(time!=null) {
try {
return Float.parseFloat(time);
} catch (NumberFormatException e) {
try {
return new DecimalFormat().parse(time).floatValue();
} catch (ParseException x) {
// hmm, don't know what this format is.
}
}
}
return 0.0f;
}" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.