type
stringclasses 1
value | dataset
stringclasses 1
value | input
stringlengths 75
160k
| instruction
stringlengths 117
171
| output
stringlengths 88
168k
|
---|---|---|---|---|
Inversion-Mutation | megadiff | "private String escapeUnsafe(String s) {
s = s.replace("&", "&");
s = s.replace("<", "<");
s = s.replace(">", ">");
s = s.replace("\n", "<BR/>");
return s;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "escapeUnsafe" | "private String escapeUnsafe(String s) {
<MASK>s = s.replace("\n", "<BR/>");</MASK>
s = s.replace("&", "&");
s = s.replace("<", "<");
s = s.replace(">", ">");
return s;
}" |
Inversion-Mutation | megadiff | "public void end() {
_running.set(false);
_events.add(false);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "end" | "public void end() {
<MASK>_events.add(false);</MASK>
_running.set(false);
}" |
Inversion-Mutation | megadiff | "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 startElement(String uri, String localName, String qName,
Attributes a) throws SAXException {
// Initialize string buffer to hold content of the new element.
// This will start a fresh buffer for every element encountered.
m_elementContent=new StringBuffer();
if (uri.equals(F) && !m_inXMLMetadata) {
// WE ARE NOT INSIDE A BLOCK OF INLINE XML...
if (localName.equals("digitalObject")) {
m_rootElementFound=true;
//======================
// OBJECT IDENTIFIERS...
//======================
m_obj.setPid(grab(a, F, "PID"));
//=====================
// OBJECT PROPERTIES...
//=====================
} else if (localName.equals("property") || localName.equals("extproperty")) {
m_objPropertyName = grab(a, F, "NAME");
if (m_objPropertyName.equals(MODEL.STATE.uri)){
String stateString = grab(a, F, "VALUE");
String stateCode = null;
if (MODEL.DELETED.looselyMatches(stateString, true)) {
stateCode = "D";
} else if (MODEL.INACTIVE.looselyMatches(stateString, true)) {
stateCode = "I";
} else if (MODEL.ACTIVE.looselyMatches(stateString, true)) {
stateCode = "A";
}
m_obj.setState(stateCode);
} else if (m_objPropertyName.equals(MODEL.CONTENT_MODEL.uri)){
m_obj.setContentModelId(grab(a, F, "VALUE"));
} else if (m_objPropertyName.equals(MODEL.LABEL.uri)){
m_obj.setLabel(grab(a, F, "VALUE"));
} else if (m_objPropertyName.equals(MODEL.CREATED_DATE.uri)){
m_obj.setCreateDate(DateUtility.convertStringToDate(grab(a, F, "VALUE")));
} else if (m_objPropertyName.equals(VIEW.LAST_MODIFIED_DATE.uri)){
m_obj.setLastModDate(DateUtility.convertStringToDate(grab(a, F, "VALUE")));
} else if (m_objPropertyName.equals(RDF.TYPE.uri)) {
String oType = grab(a, F, "VALUE");
if (oType==null || oType.equals("")) { oType=MODEL.DATA_OBJECT.localName; }
if (MODEL.BDEF_OBJECT.looselyMatches(oType, false)) {
m_obj.setFedoraObjectType(DigitalObject.FEDORA_BDEF_OBJECT);
} else if (MODEL.BMECH_OBJECT.looselyMatches(oType, false)) {
m_obj.setFedoraObjectType(DigitalObject.FEDORA_BMECH_OBJECT);
} else {
m_obj.setFedoraObjectType(DigitalObject.FEDORA_OBJECT);
}
} else {
// add an extensible property in the property map
m_obj.setExtProperty(m_objPropertyName, grab(a, F, "VALUE"));
}
//===============
// DATASTREAMS...
//===============
} else if (localName.equals("datastream")) {
// get datastream container-level attributes...
// These are common for all versions of the datastream.
m_dsId=grab(a, F, "ID");
m_dsState=grab(a, F, "STATE");
m_dsControlGrp=grab(a, F, "CONTROL_GROUP");
String versionable =grab(a, F, "VERSIONABLE");
// If dsVersionable is null or missing, default to true.
if (versionable==null || versionable.equals("")) {
m_dsVersionable=true;
} else {
m_dsVersionable=new Boolean(versionable).booleanValue();
}
// Never allow the AUDIT datastream to be versioned
// since it naturally represents a system-controlled
// view of changes over time.
if (m_dsId.equals("AUDIT")) {
m_dsVersionable=false;
}
} else if (localName.equals("datastreamVersion")) {
// get datastream version-level attributes...
m_dsVersId=grab(a, F, "ID");
m_dsLabel=grab(a, F, "LABEL");
m_dsCreateDate=DateUtility.convertStringToDate(grab(a, F, "CREATED"));
String altIDsString = grab(a, F, "ALT_IDS");
if (altIDsString.length() == 0) {
m_dsAltIds = new String[0];
} else {
m_dsAltIds = altIDsString.split(" ");
}
m_dsFormatURI=grab(a, F, "FORMAT_URI");
if (m_dsFormatURI.length() == 0) {
m_dsFormatURI = null;
}
checkMETSFormat(m_dsFormatURI);
m_dsMimeType=grab(a, F, "MIMETYPE");
String sizeString=grab(a, F, "SIZE");
if (sizeString!=null && !sizeString.equals("")) {
try {
m_dsSize=Long.parseLong(sizeString);
} catch (NumberFormatException nfe) {
throw new SAXException("If specified, a datastream's "
+ "SIZE attribute must be an xsd:long.");
}
} else {
m_dsSize=-1;
}
if (m_dsVersId.equals("AUDIT.0")) {
m_gotAudit=true;
}
//======================
// DATASTREAM CONTENT...
//======================
// inside a datastreamVersion element, it's either going to be
// xmlContent (inline xml), contentLocation (a reference) or binaryContent
} else if (localName.equals("xmlContent")) {
m_dsXMLBuffer=new StringBuffer();
m_xmlDataLevel=0;
m_inXMLMetadata=true;
} else if (localName.equals("contentLocation")) {
String dsLocation=grab(a,F,"REF");
if (dsLocation==null || dsLocation.equals("")) {
throw new SAXException("REF attribute must be specified in contentLocation element");
}
// check if datastream is ExternalReferenced
if (m_dsControlGrp.equalsIgnoreCase("E") ||
m_dsControlGrp.equalsIgnoreCase("R") ) {
// URL FORMAT VALIDATION for dsLocation:
// make sure we have a properly formed URL
try {
ValidationUtility.validateURL(dsLocation, false);
} catch (ValidationException ve) {
throw new SAXException(ve.getMessage());
}
// system will set dsLocationType for E and R datastreams...
m_dsLocationType="URL";
m_dsLocation=dsLocation;
instantiateDatastream(new DatastreamReferencedContent());
// check if datastream is ManagedContent
} else if (m_dsControlGrp.equalsIgnoreCase("M")) {
// URL FORMAT VALIDATION for dsLocation:
// For Managed Content the URL is only checked when we are parsing a
// a NEW ingest file because the URL is replaced with an internal identifier
// once the repository has sucked in the content for storage.
if (m_obj.isNew()) {
try {
ValidationUtility.validateURL(dsLocation, false);
} catch (ValidationException ve) {
throw new SAXException(ve.getMessage());
}
}
m_dsLocationType="INTERNAL_ID";
m_dsLocation=dsLocation;
instantiateDatastream(new DatastreamManagedContent());
}
} else if (localName.equals("binaryContent")) {
// FIXME: implement support for this in Fedora 1.2
if (m_dsControlGrp.equalsIgnoreCase("M"))
{
m_readingBinaryContent=true;
m_binaryContentTempFile = null;
try {
m_binaryContentTempFile = File.createTempFile("binary-datastream", null);
}
catch (IOException ioe)
{
throw new SAXException(new StreamIOException("Unable to create temporary file for binary content"));
}
}
//==================
// DISSEMINATORS...
//==================
} else if (localName.equals("disseminator")) {
m_dissID=grab(a, F,"ID");
m_bDefID=grab(a, F, "BDEF_CONTRACT_PID");
m_dissState=grab(a, F,"STATE");
String versionable =grab(a, F, "VERSIONABLE");
// disseminator versioning is defaulted to true
if (versionable==null || versionable.equals("")) {
m_dissVersionable=true;
} else {
m_dissVersionable=new Boolean(versionable).booleanValue();
}
} else if (localName.equals("disseminatorVersion")) {
m_diss = new Disseminator();
m_diss.dissID=m_dissID;
m_diss.bDefID=m_bDefID;
m_diss.dissState=m_dissState;
String versionable =grab(a, F, "VERSIONABLE");
// disseminator versioning is defaulted to true
if (versionable==null || versionable.equals("")) {
m_dissVersionable=true;
} else {
m_dissVersionable=new Boolean(versionable).booleanValue();
}
m_diss.dissVersionID=grab(a, F,"ID");
m_diss.dissLabel=grab(a, F, "LABEL");
m_diss.bMechID=grab(a, F, "BMECH_SERVICE_PID");
m_diss.dissCreateDT=DateUtility.convertStringToDate(grab(a, F, "CREATED"));
} else if (localName.equals("serviceInputMap")) {
m_diss.dsBindMap=new DSBindingMap();
m_dsBindings = new ArrayList();
// Note that the dsBindMapID is not really necessary from the
// FOXML standpoint, but it was necessary in METS since the structMap
// was outside the disseminator. (Look at how it's used in the sql db.)
// Also, the rest of the attributes on the DSBindingMap are not
// really necessary since they are inherited from the disseminator.
// I just use the values picked up from disseminatorVersion.
m_diss.dsBindMapID=m_diss.dissVersionID + "b";
m_diss.dsBindMap.dsBindMapID=m_diss.dsBindMapID;
m_diss.dsBindMap.dsBindMechanismPID = m_diss.bMechID;
m_diss.dsBindMap.dsBindMapLabel = ""; // does not exist in FOXML
m_diss.dsBindMap.state = m_diss.dissState;
} else if (localName.equals("datastreamBinding")) {
DSBinding dsb = new DSBinding();
dsb.bindKeyName = grab(a, F,"KEY");
dsb.bindLabel = grab(a, F,"LABEL");
dsb.datastreamID = grab(a, F,"DATASTREAM_ID");
dsb.seqNo = grab(a, F,"ORDER");
m_dsBindings.add(dsb);
}
} else {
//===============
// INLINE XML...
//===============
if (m_inXMLMetadata) {
// we are inside an xmlContent element.
// just output it, remembering the number of foxml:xmlContent elements we see,
appendElementStart(uri, localName, qName, a, m_dsXMLBuffer);
// FOXML INSIDE FOXML! we have an inline XML datastream
// that is itself FOXML. We do not want to parse this!
if (uri.equals(F) && localName.equals("xmlContent")) {
m_xmlDataLevel++;
}
// if AUDIT datastream, initialize new audit record object
if (m_gotAudit) {
if (localName.equals("record")) {
m_auditRec=new AuditRecord();
m_auditRec.id=grab(a, uri, "ID");
} else if (localName.equals("process")) {
m_auditProcessType=grab(a, uri, "type");
}
}
} else {
// ignore all else
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "startElement" | "public void startElement(String uri, String localName, String qName,
Attributes a) throws SAXException {
// Initialize string buffer to hold content of the new element.
// This will start a fresh buffer for every element encountered.
m_elementContent=new StringBuffer();
if (uri.equals(F) && !m_inXMLMetadata) {
// WE ARE NOT INSIDE A BLOCK OF INLINE XML...
if (localName.equals("digitalObject")) {
m_rootElementFound=true;
//======================
// OBJECT IDENTIFIERS...
//======================
m_obj.setPid(grab(a, F, "PID"));
//=====================
// OBJECT PROPERTIES...
//=====================
} else if (localName.equals("property") || localName.equals("extproperty")) {
m_objPropertyName = grab(a, F, "NAME");
if (m_objPropertyName.equals(MODEL.STATE.uri)){
String stateString = grab(a, F, "VALUE");
String stateCode = null;
if (MODEL.DELETED.looselyMatches(stateString, true)) {
stateCode = "D";
} else if (MODEL.INACTIVE.looselyMatches(stateString, true)) {
stateCode = "I";
} else if (MODEL.ACTIVE.looselyMatches(stateString, true)) {
stateCode = "A";
}
m_obj.setState(stateCode);
} else if (m_objPropertyName.equals(MODEL.CONTENT_MODEL.uri)){
m_obj.setContentModelId(grab(a, F, "VALUE"));
} else if (m_objPropertyName.equals(MODEL.LABEL.uri)){
m_obj.setLabel(grab(a, F, "VALUE"));
} else if (m_objPropertyName.equals(MODEL.CREATED_DATE.uri)){
m_obj.setCreateDate(DateUtility.convertStringToDate(grab(a, F, "VALUE")));
} else if (m_objPropertyName.equals(VIEW.LAST_MODIFIED_DATE.uri)){
m_obj.setLastModDate(DateUtility.convertStringToDate(grab(a, F, "VALUE")));
} else if (m_objPropertyName.equals(RDF.TYPE.uri)) {
String oType = grab(a, F, "VALUE");
if (oType==null || oType.equals("")) { oType=MODEL.DATA_OBJECT.localName; }
if (MODEL.BDEF_OBJECT.looselyMatches(oType, false)) {
m_obj.setFedoraObjectType(DigitalObject.FEDORA_BDEF_OBJECT);
} else if (MODEL.BMECH_OBJECT.looselyMatches(oType, false)) {
m_obj.setFedoraObjectType(DigitalObject.FEDORA_BMECH_OBJECT);
} else {
m_obj.setFedoraObjectType(DigitalObject.FEDORA_OBJECT);
}
} else {
// add an extensible property in the property map
m_obj.setExtProperty(m_objPropertyName, grab(a, F, "VALUE"));
}
//===============
// DATASTREAMS...
//===============
} else if (localName.equals("datastream")) {
// get datastream container-level attributes...
// These are common for all versions of the datastream.
m_dsId=grab(a, F, "ID");
m_dsState=grab(a, F, "STATE");
m_dsControlGrp=grab(a, F, "CONTROL_GROUP");
String versionable =grab(a, F, "VERSIONABLE");
// If dsVersionable is null or missing, default to true.
if (versionable==null || versionable.equals("")) {
m_dsVersionable=true;
} else {
m_dsVersionable=new Boolean(versionable).booleanValue();
}
// Never allow the AUDIT datastream to be versioned
// since it naturally represents a system-controlled
// view of changes over time.
<MASK>checkMETSFormat(m_dsFormatURI);</MASK>
if (m_dsId.equals("AUDIT")) {
m_dsVersionable=false;
}
} else if (localName.equals("datastreamVersion")) {
// get datastream version-level attributes...
m_dsVersId=grab(a, F, "ID");
m_dsLabel=grab(a, F, "LABEL");
m_dsCreateDate=DateUtility.convertStringToDate(grab(a, F, "CREATED"));
String altIDsString = grab(a, F, "ALT_IDS");
if (altIDsString.length() == 0) {
m_dsAltIds = new String[0];
} else {
m_dsAltIds = altIDsString.split(" ");
}
m_dsFormatURI=grab(a, F, "FORMAT_URI");
if (m_dsFormatURI.length() == 0) {
m_dsFormatURI = null;
}
m_dsMimeType=grab(a, F, "MIMETYPE");
String sizeString=grab(a, F, "SIZE");
if (sizeString!=null && !sizeString.equals("")) {
try {
m_dsSize=Long.parseLong(sizeString);
} catch (NumberFormatException nfe) {
throw new SAXException("If specified, a datastream's "
+ "SIZE attribute must be an xsd:long.");
}
} else {
m_dsSize=-1;
}
if (m_dsVersId.equals("AUDIT.0")) {
m_gotAudit=true;
}
//======================
// DATASTREAM CONTENT...
//======================
// inside a datastreamVersion element, it's either going to be
// xmlContent (inline xml), contentLocation (a reference) or binaryContent
} else if (localName.equals("xmlContent")) {
m_dsXMLBuffer=new StringBuffer();
m_xmlDataLevel=0;
m_inXMLMetadata=true;
} else if (localName.equals("contentLocation")) {
String dsLocation=grab(a,F,"REF");
if (dsLocation==null || dsLocation.equals("")) {
throw new SAXException("REF attribute must be specified in contentLocation element");
}
// check if datastream is ExternalReferenced
if (m_dsControlGrp.equalsIgnoreCase("E") ||
m_dsControlGrp.equalsIgnoreCase("R") ) {
// URL FORMAT VALIDATION for dsLocation:
// make sure we have a properly formed URL
try {
ValidationUtility.validateURL(dsLocation, false);
} catch (ValidationException ve) {
throw new SAXException(ve.getMessage());
}
// system will set dsLocationType for E and R datastreams...
m_dsLocationType="URL";
m_dsLocation=dsLocation;
instantiateDatastream(new DatastreamReferencedContent());
// check if datastream is ManagedContent
} else if (m_dsControlGrp.equalsIgnoreCase("M")) {
// URL FORMAT VALIDATION for dsLocation:
// For Managed Content the URL is only checked when we are parsing a
// a NEW ingest file because the URL is replaced with an internal identifier
// once the repository has sucked in the content for storage.
if (m_obj.isNew()) {
try {
ValidationUtility.validateURL(dsLocation, false);
} catch (ValidationException ve) {
throw new SAXException(ve.getMessage());
}
}
m_dsLocationType="INTERNAL_ID";
m_dsLocation=dsLocation;
instantiateDatastream(new DatastreamManagedContent());
}
} else if (localName.equals("binaryContent")) {
// FIXME: implement support for this in Fedora 1.2
if (m_dsControlGrp.equalsIgnoreCase("M"))
{
m_readingBinaryContent=true;
m_binaryContentTempFile = null;
try {
m_binaryContentTempFile = File.createTempFile("binary-datastream", null);
}
catch (IOException ioe)
{
throw new SAXException(new StreamIOException("Unable to create temporary file for binary content"));
}
}
//==================
// DISSEMINATORS...
//==================
} else if (localName.equals("disseminator")) {
m_dissID=grab(a, F,"ID");
m_bDefID=grab(a, F, "BDEF_CONTRACT_PID");
m_dissState=grab(a, F,"STATE");
String versionable =grab(a, F, "VERSIONABLE");
// disseminator versioning is defaulted to true
if (versionable==null || versionable.equals("")) {
m_dissVersionable=true;
} else {
m_dissVersionable=new Boolean(versionable).booleanValue();
}
} else if (localName.equals("disseminatorVersion")) {
m_diss = new Disseminator();
m_diss.dissID=m_dissID;
m_diss.bDefID=m_bDefID;
m_diss.dissState=m_dissState;
String versionable =grab(a, F, "VERSIONABLE");
// disseminator versioning is defaulted to true
if (versionable==null || versionable.equals("")) {
m_dissVersionable=true;
} else {
m_dissVersionable=new Boolean(versionable).booleanValue();
}
m_diss.dissVersionID=grab(a, F,"ID");
m_diss.dissLabel=grab(a, F, "LABEL");
m_diss.bMechID=grab(a, F, "BMECH_SERVICE_PID");
m_diss.dissCreateDT=DateUtility.convertStringToDate(grab(a, F, "CREATED"));
} else if (localName.equals("serviceInputMap")) {
m_diss.dsBindMap=new DSBindingMap();
m_dsBindings = new ArrayList();
// Note that the dsBindMapID is not really necessary from the
// FOXML standpoint, but it was necessary in METS since the structMap
// was outside the disseminator. (Look at how it's used in the sql db.)
// Also, the rest of the attributes on the DSBindingMap are not
// really necessary since they are inherited from the disseminator.
// I just use the values picked up from disseminatorVersion.
m_diss.dsBindMapID=m_diss.dissVersionID + "b";
m_diss.dsBindMap.dsBindMapID=m_diss.dsBindMapID;
m_diss.dsBindMap.dsBindMechanismPID = m_diss.bMechID;
m_diss.dsBindMap.dsBindMapLabel = ""; // does not exist in FOXML
m_diss.dsBindMap.state = m_diss.dissState;
} else if (localName.equals("datastreamBinding")) {
DSBinding dsb = new DSBinding();
dsb.bindKeyName = grab(a, F,"KEY");
dsb.bindLabel = grab(a, F,"LABEL");
dsb.datastreamID = grab(a, F,"DATASTREAM_ID");
dsb.seqNo = grab(a, F,"ORDER");
m_dsBindings.add(dsb);
}
} else {
//===============
// INLINE XML...
//===============
if (m_inXMLMetadata) {
// we are inside an xmlContent element.
// just output it, remembering the number of foxml:xmlContent elements we see,
appendElementStart(uri, localName, qName, a, m_dsXMLBuffer);
// FOXML INSIDE FOXML! we have an inline XML datastream
// that is itself FOXML. We do not want to parse this!
if (uri.equals(F) && localName.equals("xmlContent")) {
m_xmlDataLevel++;
}
// if AUDIT datastream, initialize new audit record object
if (m_gotAudit) {
if (localName.equals("record")) {
m_auditRec=new AuditRecord();
m_auditRec.id=grab(a, uri, "ID");
} else if (localName.equals("process")) {
m_auditProcessType=grab(a, uri, "type");
}
}
} else {
// ignore all else
}
}
}" |
Inversion-Mutation | megadiff | "private void fireValueChange ( final DataItemValue.Builder builder )
{
injectAttributes ( builder );
this.sourceValue = builder.build ();
updateData ( this.sourceValue );
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "fireValueChange" | "private void fireValueChange ( final DataItemValue.Builder builder )
{
<MASK>this.sourceValue = builder.build ();</MASK>
injectAttributes ( builder );
updateData ( this.sourceValue );
}" |
Inversion-Mutation | megadiff | "protected ThreadState pickNextThread() {
//Set up an Iterator and go through it
Random randomGenerator = new Random();
int ticketCount = 0;
Iterator<ThreadState> itr = this.waitQueue.iterator();
while(itr.hasNext()) {
ticketCount += itr.next().getEffectivePriority();
System.out.println("ticketCount is " + ticketCount);
}
if(ticketCount > 0) {
int num = randomGenerator.nextInt(ticketCount);
itr = this.waitQueue.iterator();
ThreadState temp;
while(itr.hasNext()) {
temp = itr.next();
num -= temp.effectivePriority;
if(num <= 0){
return temp;
}
}
}
return null;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "pickNextThread" | "protected ThreadState pickNextThread() {
//Set up an Iterator and go through it
Random randomGenerator = new Random();
int ticketCount = 0;
Iterator<ThreadState> itr = this.waitQueue.iterator();
while(itr.hasNext()) {
ticketCount += itr.next().getEffectivePriority();
}
<MASK>System.out.println("ticketCount is " + ticketCount);</MASK>
if(ticketCount > 0) {
int num = randomGenerator.nextInt(ticketCount);
itr = this.waitQueue.iterator();
ThreadState temp;
while(itr.hasNext()) {
temp = itr.next();
num -= temp.effectivePriority;
if(num <= 0){
return temp;
}
}
}
return null;
}" |
Inversion-Mutation | megadiff | "protected int childCount(IThread thread) {
try {
int count = thread.getStackFrames().length;
if (isDisplayMonitors()) {
if (((IJavaDebugTarget)thread.getDebugTarget()).supportsMonitorInformation()) {
IJavaThread jThread = (IJavaThread) thread;
count += jThread.getOwnedMonitors().length;
if (jThread.getContendedMonitor() != null) {
count++;
}
} else {
// make room for the 'no monitor info' element
count++;
}
}
return count;
} catch (DebugException e) {
}
return -1;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "childCount" | "protected int childCount(IThread thread) {
try {
int count = thread.getStackFrames().length;
if (isDisplayMonitors()) {
if (((IJavaDebugTarget)thread.getDebugTarget()).supportsMonitorInformation()) {
IJavaThread jThread = (IJavaThread) thread;
count += jThread.getOwnedMonitors().length;
if (jThread.getContendedMonitor() != null) {
count++;
}
} else {
// make room for the 'no monitor info' element
count++;
}
<MASK>return count;</MASK>
}
} catch (DebugException e) {
}
return -1;
}" |
Inversion-Mutation | megadiff | "public void setRelativeAxisVisible(boolean visibility)
{
this.isVisibleRelativeAxis = visibility;
canvas.lock();
marker.SetEnabled(Utils.booleanToInt(visibility));
relativeAxes.SetVisibility(Utils.booleanToInt(visibility));
canvas.RenderSecured();
canvas.unlock();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setRelativeAxisVisible" | "public void setRelativeAxisVisible(boolean visibility)
{
this.isVisibleRelativeAxis = visibility;
canvas.lock();
marker.SetEnabled(Utils.booleanToInt(visibility));
<MASK>canvas.unlock();</MASK>
relativeAxes.SetVisibility(Utils.booleanToInt(visibility));
canvas.RenderSecured();
}" |
Inversion-Mutation | megadiff | "public void close() {
if (closed == null) {
try {
closed = new Exception("Connection Closed Traceback");
shutdownConnection();
jcbcStorageClientConnection.releaseClient(this);
LOGGER.info("Sparse Content Map Database Connection closed.");
} catch (Throwable t) {
LOGGER.error("Failed to close connection ", t);
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "close" | "public void close() {
if (closed == null) {
try {
shutdownConnection();
jcbcStorageClientConnection.releaseClient(this);
<MASK>closed = new Exception("Connection Closed Traceback");</MASK>
LOGGER.info("Sparse Content Map Database Connection closed.");
} catch (Throwable t) {
LOGGER.error("Failed to close connection ", t);
}
}
}" |
Inversion-Mutation | megadiff | "public static void mutate(Individual ind, double prob)
{
int mask = 1;
for (int i = 0; i < BITS; i++) {
double r = rand.nextDouble();
if (r < prob) {
ind.val ^= mask;
}
mask <<= 1;
}
ind.fitness(MIN_G);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "mutate" | "public static void mutate(Individual ind, double prob)
{
int mask = 1;
for (int i = 0; i < BITS; i++) {
<MASK>mask <<= 1;</MASK>
double r = rand.nextDouble();
if (r < prob) {
ind.val ^= mask;
}
}
ind.fitness(MIN_G);
}" |
Inversion-Mutation | megadiff | "protected JPanel buildInfoPanel() {
JPanel pnl = new JPanel();
pnl.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
pnl.setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.fill = GridBagConstraints.BOTH;
gc.weighty = 1.0;
gc.weightx = 1.0;
gc.anchor = GridBagConstraints.LINE_START;
pnl.add(new JLabel(tr("<html>Please select the values to keep for the following tags.</html>")), gc);
gc.gridy = 1;
gc.fill = GridBagConstraints.HORIZONTAL;
gc.weighty = 0.0;
pnl.add(cbShowTagsWithConflictsOnly = new JCheckBox(tr("Show tags with conflicts only")), gc);
pnl.add(cbShowTagsWithMultiValuesOnly = new JCheckBox(tr("Show tags with multiple values only")), gc);
cbShowTagsWithConflictsOnly.addChangeListener(
new ChangeListener() {
public void stateChanged(ChangeEvent e) {
model.setShowTagsWithConflictsOnly(cbShowTagsWithConflictsOnly.isSelected());
cbShowTagsWithMultiValuesOnly.setEnabled(cbShowTagsWithConflictsOnly.isSelected());
}
}
);
cbShowTagsWithConflictsOnly.setSelected(
Main.pref.getBoolean(getClass().getName() + ".showTagsWithConflictsOnly", false)
);
cbShowTagsWithMultiValuesOnly.addChangeListener(
new ChangeListener() {
public void stateChanged(ChangeEvent e) {
model.setShowTagsWithMultiValuesOnly(cbShowTagsWithMultiValuesOnly.isSelected());
}
}
);
cbShowTagsWithMultiValuesOnly.setSelected(
Main.pref.getBoolean(getClass().getName() + ".showTagsWithMultiValuesOnly", false)
);
cbShowTagsWithMultiValuesOnly.setEnabled(cbShowTagsWithConflictsOnly.isSelected());
return pnl;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "buildInfoPanel" | "protected JPanel buildInfoPanel() {
JPanel pnl = new JPanel();
pnl.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
pnl.setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.fill = GridBagConstraints.BOTH;
gc.weighty = 1.0;
gc.weightx = 1.0;
gc.anchor = GridBagConstraints.LINE_START;
pnl.add(new JLabel(tr("<html>Please select the values to keep for the following tags.</html>")), gc);
gc.gridy = 1;
gc.fill = GridBagConstraints.HORIZONTAL;
gc.weighty = 0.0;
pnl.add(cbShowTagsWithConflictsOnly = new JCheckBox(tr("Show tags with conflicts only")), gc);
cbShowTagsWithConflictsOnly.addChangeListener(
new ChangeListener() {
public void stateChanged(ChangeEvent e) {
model.setShowTagsWithConflictsOnly(cbShowTagsWithConflictsOnly.isSelected());
cbShowTagsWithMultiValuesOnly.setEnabled(cbShowTagsWithConflictsOnly.isSelected());
}
}
);
cbShowTagsWithConflictsOnly.setSelected(
Main.pref.getBoolean(getClass().getName() + ".showTagsWithConflictsOnly", false)
);
<MASK>pnl.add(cbShowTagsWithMultiValuesOnly = new JCheckBox(tr("Show tags with multiple values only")), gc);</MASK>
cbShowTagsWithMultiValuesOnly.addChangeListener(
new ChangeListener() {
public void stateChanged(ChangeEvent e) {
model.setShowTagsWithMultiValuesOnly(cbShowTagsWithMultiValuesOnly.isSelected());
}
}
);
cbShowTagsWithMultiValuesOnly.setSelected(
Main.pref.getBoolean(getClass().getName() + ".showTagsWithMultiValuesOnly", false)
);
cbShowTagsWithMultiValuesOnly.setEnabled(cbShowTagsWithConflictsOnly.isSelected());
return pnl;
}" |
Inversion-Mutation | megadiff | "@Test
public void testChannelAwareMessageListenerDontExpose() throws Exception {
ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
Connection mockConnection = mock(Connection.class);
final Channel firstChannel = mock(Channel.class);
when(firstChannel.isOpen()).thenReturn(true);
final Channel secondChannel = mock(Channel.class);
when(secondChannel.isOpen()).thenReturn(true);
final SingleConnectionFactory singleConnectionFactory = new SingleConnectionFactory(mockConnectionFactory);
when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection);
when(mockConnection.isOpen()).thenReturn(true);
final AtomicReference<Exception> tooManyChannels = new AtomicReference<Exception>();
doAnswer(new Answer<Channel>(){
boolean done;
@Override
public Channel answer(InvocationOnMock invocation) throws Throwable {
if (!done) {
done = true;
return firstChannel;
}
return secondChannel;
}
}).when(mockConnection).createChannel();
final AtomicReference<Consumer> consumer = new AtomicReference<Consumer>();
doAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
consumer.set((Consumer) invocation.getArguments()[2]);
return null;
}
}).when(firstChannel)
.basicConsume(Mockito.anyString(), Mockito.anyBoolean(), Mockito.any(Consumer.class));
final CountDownLatch commitLatch = new CountDownLatch(1);
doAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
commitLatch.countDown();
return null;
}
}).when(firstChannel).txCommit();
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<Channel> exposed = new AtomicReference<Channel>();
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(singleConnectionFactory);
container.setMessageListener(new ChannelAwareMessageListener() {
public void onMessage(Message message, Channel channel) {
exposed.set(channel);
RabbitTemplate rabbitTemplate = new RabbitTemplate(singleConnectionFactory);
rabbitTemplate.setChannelTransacted(true);
// should use same channel as container
rabbitTemplate.convertAndSend("foo", "bar", "baz");
latch.countDown();
}
});
container.setQueueNames("queue");
container.setChannelTransacted(true);
container.setExposeListenerChannel(false);
container.setShutdownTimeout(100);
container.afterPropertiesSet();
container.start();
consumer.get().handleDelivery("qux", new Envelope(1, false, "foo", "bar"), new BasicProperties(), new byte[] {0});
assertTrue(latch.await(10, TimeUnit.SECONDS));
Exception e = tooManyChannels.get();
if (e != null) {
throw e;
}
// once for listener, once for exposed + 0 for template (used bound)
verify(mockConnection, Mockito.times(2)).createChannel();
assertTrue(commitLatch.await(10, TimeUnit.SECONDS));
verify(firstChannel).txCommit();
verify(secondChannel).txCommit();
verify(secondChannel).basicPublish(Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(),
Mockito.anyBoolean(), Mockito.any(BasicProperties.class), Mockito.any(byte[].class));
assertSame(secondChannel, exposed.get());
verify(firstChannel, Mockito.never()).close();
verify(secondChannel, Mockito.times(1)).close();
container.stop();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "testChannelAwareMessageListenerDontExpose" | "@Test
public void testChannelAwareMessageListenerDontExpose() throws Exception {
ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
Connection mockConnection = mock(Connection.class);
final Channel firstChannel = mock(Channel.class);
when(firstChannel.isOpen()).thenReturn(true);
final Channel secondChannel = mock(Channel.class);
when(secondChannel.isOpen()).thenReturn(true);
final SingleConnectionFactory singleConnectionFactory = new SingleConnectionFactory(mockConnectionFactory);
when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection);
when(mockConnection.isOpen()).thenReturn(true);
final AtomicReference<Exception> tooManyChannels = new AtomicReference<Exception>();
doAnswer(new Answer<Channel>(){
boolean done;
@Override
public Channel answer(InvocationOnMock invocation) throws Throwable {
if (!done) {
done = true;
return firstChannel;
}
return secondChannel;
}
}).when(mockConnection).createChannel();
final AtomicReference<Consumer> consumer = new AtomicReference<Consumer>();
doAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
consumer.set((Consumer) invocation.getArguments()[2]);
return null;
}
}).when(firstChannel)
.basicConsume(Mockito.anyString(), Mockito.anyBoolean(), Mockito.any(Consumer.class));
final CountDownLatch commitLatch = new CountDownLatch(1);
doAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
commitLatch.countDown();
return null;
}
}).when(firstChannel).txCommit();
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<Channel> exposed = new AtomicReference<Channel>();
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(singleConnectionFactory);
container.setMessageListener(new ChannelAwareMessageListener() {
public void onMessage(Message message, Channel channel) {
exposed.set(channel);
RabbitTemplate rabbitTemplate = new RabbitTemplate(singleConnectionFactory);
rabbitTemplate.setChannelTransacted(true);
// should use same channel as container
rabbitTemplate.convertAndSend("foo", "bar", "baz");
latch.countDown();
}
});
container.setQueueNames("queue");
container.setChannelTransacted(true);
container.setExposeListenerChannel(false);
container.setShutdownTimeout(100);
container.afterPropertiesSet();
container.start();
consumer.get().handleDelivery("qux", new Envelope(1, false, "foo", "bar"), new BasicProperties(), new byte[] {0});
assertTrue(latch.await(10, TimeUnit.SECONDS));
Exception e = tooManyChannels.get();
if (e != null) {
throw e;
}
// once for listener, once for exposed + 0 for template (used bound)
verify(mockConnection, Mockito.times(2)).createChannel();
assertTrue(commitLatch.await(10, TimeUnit.SECONDS));
verify(firstChannel).txCommit();
verify(secondChannel).txCommit();
verify(secondChannel).basicPublish(Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(),
Mockito.anyBoolean(), Mockito.any(BasicProperties.class), Mockito.any(byte[].class));
<MASK>container.stop();</MASK>
assertSame(secondChannel, exposed.get());
verify(firstChannel, Mockito.never()).close();
verify(secondChannel, Mockito.times(1)).close();
}" |
Inversion-Mutation | megadiff | "@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String ipAddressesList = nullToEmpty(request.getParameter("ipAddressesList"));
String getAllLogs = nullToEmpty(request.getParameter("getLogs"));
String clearLogs = nullToEmpty(request.getParameter("clearLogs"));
String[] ipAddresses = null;
if (!ipAddressesList.isEmpty()) {
if (ipAddressesList.contains(",")) {
ipAddressesList = ipAddressesList
.substring(0, ipAddressesList.length() - 1);
ipAddresses = ipAddressesList.split(",");
} else {
ipAddresses = new String[]{ipAddressesList};
}
} else {
response.sendError(404, "empty ip address");
}
if(!getAllLogs.isEmpty()){
for(String ipAddress : ipAddresses){
getLogsFromIp(ipAddress);
}
formatLogs(LOCALHOST);
}
if(!clearLogs.isEmpty()){
for(String ipAddress : ipAddresses){
clearLogs(ipAddress);
}
}
response.sendRedirect(PageNames.AMAZON);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doGet" | "@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String ipAddressesList = nullToEmpty(request.getParameter("ipAddressesList"));
String getAllLogs = nullToEmpty(request.getParameter("getLogs"));
String clearLogs = nullToEmpty(request.getParameter("clearLogs"));
String[] ipAddresses = null;
if (!ipAddressesList.isEmpty()) {
if (ipAddressesList.contains(",")) {
ipAddressesList = ipAddressesList
.substring(0, ipAddressesList.length() - 1);
ipAddresses = ipAddressesList.split(",");
} else {
ipAddresses = new String[]{ipAddressesList};
}
} else {
response.sendError(404, "empty ip address");
}
if(!getAllLogs.isEmpty()){
for(String ipAddress : ipAddresses){
getLogsFromIp(ipAddress);
<MASK>formatLogs(LOCALHOST);</MASK>
}
}
if(!clearLogs.isEmpty()){
for(String ipAddress : ipAddresses){
clearLogs(ipAddress);
}
}
response.sendRedirect(PageNames.AMAZON);
}" |
Inversion-Mutation | megadiff | "@Override
protected void setup(Context context) throws IOException, InterruptedException {
_blurTask = BlurTask.read(context.getConfiguration());
_configuration = context.getConfiguration();
setupCounters(context);
setupZookeeper(context);
setupAnalyzer(context);
setupDirectory(context);
setupWriter(context);
if (_blurTask.getIndexingType() == INDEXING_TYPE.UPDATE) {
_reader = IndexReader.open(_directory, true);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setup" | "@Override
protected void setup(Context context) throws IOException, InterruptedException {
_blurTask = BlurTask.read(context.getConfiguration());
setupCounters(context);
setupZookeeper(context);
setupAnalyzer(context);
setupDirectory(context);
setupWriter(context);
<MASK>_configuration = context.getConfiguration();</MASK>
if (_blurTask.getIndexingType() == INDEXING_TYPE.UPDATE) {
_reader = IndexReader.open(_directory, true);
}
}" |
Inversion-Mutation | megadiff | "public void clear () {
Object[] items = this.items;
for (int i = 0, n = size; i < n; i++)
items[i] = null;
size = 0;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "clear" | "public void clear () {
<MASK>size = 0;</MASK>
Object[] items = this.items;
for (int i = 0, n = size; i < n; i++)
items[i] = null;
}" |
Inversion-Mutation | megadiff | "private void createProject() {
// get the target and try to resolve it.
int targetId = mSdkCommandLine.getParamTargetId();
IAndroidTarget[] targets = mSdkManager.getTargets();
if (targetId < 1 || targetId > targets.length) {
errorAndExit("Target id is not valid. Use '%s list targets' to get the target ids.",
SdkConstants.androidCmdName());
}
IAndroidTarget target = targets[targetId - 1];
ProjectCreator creator = new ProjectCreator(mSdkFolder,
mSdkCommandLine.isVerbose() ? OutputLevel.VERBOSE :
mSdkCommandLine.isSilent() ? OutputLevel.SILENT :
OutputLevel.NORMAL,
mSdkLog);
String projectDir = getProjectLocation(mSdkCommandLine.getParamLocationPath());
String projectName = mSdkCommandLine.getParamName();
String packageName = mSdkCommandLine.getParamProjectPackage();
String activityName = mSdkCommandLine.getParamProjectActivity();
if (projectName != null &&
!ProjectCreator.RE_PROJECT_NAME.matcher(projectName).matches()) {
errorAndExit(
"Project name '%1$s' contains invalid characters.\nAllowed characters are: %2$s",
projectName, ProjectCreator.CHARS_PROJECT_NAME);
return;
}
if (activityName != null &&
!ProjectCreator.RE_ACTIVITY_NAME.matcher(activityName).matches()) {
errorAndExit(
"Activity name '%1$s' contains invalid characters.\nAllowed characters are: %2$s",
activityName, ProjectCreator.CHARS_ACTIVITY_NAME);
return;
}
if (packageName != null &&
!ProjectCreator.RE_PACKAGE_NAME.matcher(packageName).matches()) {
errorAndExit(
"Package name '%1$s' contains invalid characters.\n" +
"A package name must be constitued of two Java identifiers.\n" +
"Each identifier allowed characters are: %2$s",
packageName, ProjectCreator.CHARS_PACKAGE_NAME);
return;
}
creator.createProject(projectDir,
projectName,
packageName,
activityName,
target,
false /* isTestProject*/);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createProject" | "private void createProject() {
// get the target and try to resolve it.
int targetId = mSdkCommandLine.getParamTargetId();
IAndroidTarget[] targets = mSdkManager.getTargets();
if (targetId < 1 || targetId > targets.length) {
errorAndExit("Target id is not valid. Use '%s list targets' to get the target ids.",
SdkConstants.androidCmdName());
}
IAndroidTarget target = targets[targetId - 1];
ProjectCreator creator = new ProjectCreator(mSdkFolder,
mSdkCommandLine.isVerbose() ? OutputLevel.VERBOSE :
mSdkCommandLine.isSilent() ? OutputLevel.SILENT :
OutputLevel.NORMAL,
mSdkLog);
String projectDir = getProjectLocation(mSdkCommandLine.getParamLocationPath());
String projectName = mSdkCommandLine.getParamName();
String packageName = mSdkCommandLine.getParamProjectPackage();
String activityName = mSdkCommandLine.getParamProjectActivity();
if (projectName != null &&
!ProjectCreator.RE_PROJECT_NAME.matcher(projectName).matches()) {
errorAndExit(
"Project name '%1$s' contains invalid characters.\nAllowed characters are: %2$s",
projectName, ProjectCreator.CHARS_PROJECT_NAME);
return;
}
if (activityName != null &&
!ProjectCreator.RE_ACTIVITY_NAME.matcher(activityName).matches()) {
errorAndExit(
"Activity name '%1$s' contains invalid characters.\nAllowed characters are: %2$s",
<MASK>activityName,</MASK> ProjectCreator.CHARS_ACTIVITY_NAME);
return;
}
if (packageName != null &&
!ProjectCreator.RE_PACKAGE_NAME.matcher(packageName).matches()) {
errorAndExit(
"Package name '%1$s' contains invalid characters.\n" +
"A package name must be constitued of two Java identifiers.\n" +
"Each identifier allowed characters are: %2$s",
packageName, ProjectCreator.CHARS_PACKAGE_NAME);
return;
}
creator.createProject(projectDir,
projectName,
<MASK>activityName,</MASK>
packageName,
target,
false /* isTestProject*/);
}" |
Inversion-Mutation | megadiff | "private void chartMouseMoved(java.awt.event.MouseEvent evt) {
int x = evt.getX();
int y = evt.getY();
if (x >= chartRect.x
&& x <= (chartRect.x + chartRect.width)
&& y >= chartRect.y
&& y <= (chartRect.y + chartRect.height)) {
xHoverInfo = x;
yHoverInfo = y;
showHoverInfo();
hoverWindow.setVisible(true);
} else {
hoverWindow.setVisible(false);
xHoverInfo = -1;
yHoverInfo = -1;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "chartMouseMoved" | "private void chartMouseMoved(java.awt.event.MouseEvent evt) {
int x = evt.getX();
int y = evt.getY();
if (x >= chartRect.x
&& x <= (chartRect.x + chartRect.width)
&& y >= chartRect.y
&& y <= (chartRect.y + chartRect.height)) {
<MASK>hoverWindow.setVisible(true);</MASK>
xHoverInfo = x;
yHoverInfo = y;
showHoverInfo();
} else {
hoverWindow.setVisible(false);
xHoverInfo = -1;
yHoverInfo = -1;
}
}" |
Inversion-Mutation | megadiff | "private void drawWord(int x, int y, ZLTextWord word, int start, int length, boolean addHyphenationSign) {
final ZLPaintContext context = getContext();
context.setColor(myTextStyle.getColor());
if ((start == 0) && (length == -1)) {
context.drawString(x, y, word.Data, word.Offset, word.Length);
} else {
int startPos = start;
int endPos = (length == -1) ? word.Length : start + length;
if (!addHyphenationSign) {
context.drawString(x, y, word.Data, word.Offset + startPos, endPos - startPos);
} else {
String substr = new String(word.Data);
substr = substr.substring(word.Offset + startPos, word.Offset + endPos);
substr += "-";
context.drawString(x, y, substr.toCharArray(), 0, substr.length());
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "drawWord" | "private void drawWord(int x, int y, ZLTextWord word, int start, int length, boolean addHyphenationSign) {
final ZLPaintContext context = getContext();
if ((start == 0) && (length == -1)) {
<MASK>context.setColor(myTextStyle.getColor());</MASK>
context.drawString(x, y, word.Data, word.Offset, word.Length);
} else {
int startPos = start;
int endPos = (length == -1) ? word.Length : start + length;
if (!addHyphenationSign) {
context.drawString(x, y, word.Data, word.Offset + startPos, endPos - startPos);
} else {
String substr = new String(word.Data);
substr = substr.substring(word.Offset + startPos, word.Offset + endPos);
substr += "-";
context.drawString(x, y, substr.toCharArray(), 0, substr.length());
}
}
}" |
Inversion-Mutation | megadiff | "private void initFromConfig() {
Properties props = new Properties();
try {
String aliasFileName = System.getProperty("alias.file");
if (aliasFileName != null) {
log.info("Reading from file " + aliasFileName);
props.load(new FileInputStream(aliasFileName));
reinit(props);
}
} catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException(e);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "initFromConfig" | "private void initFromConfig() {
Properties props = new Properties();
try {
String aliasFileName = System.getProperty("alias.file");
<MASK>log.info("Reading from file " + aliasFileName);</MASK>
if (aliasFileName != null) {
props.load(new FileInputStream(aliasFileName));
reinit(props);
}
} catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException(e);
}
}" |
Inversion-Mutation | megadiff | "@FireExtended
public void setDTG_Start(HiResDate newStart)
{
// check that we're still after the start of the host track
if(newStart.lessThan(this.getReferenceTrack().getStartDTG()))
{
newStart = this.getReferenceTrack().getStartDTG();
}
// ok, how far is this from the current end
long delta = newStart.getMicros() - startDTG().getMicros();
// and what distance does this mean?
double deltaHrs = delta / 1000000d / 60d / 60d;
double distDegs = this.getSpeed().getValueIn(WorldSpeed.Kts) * deltaHrs / 60;
double theDirection = MWC.Algorithms.Conversions.Degs2Rads(this.getCourse());
// we don't need to worry about reversing the direction, since we have a -ve distance
// so what's the new origin?
WorldLocation currentStart =new WorldLocation(this.getTrackStart());
WorldLocation newOrigin = currentStart.add(new WorldVector(theDirection, distDegs, 0));
// and what's the point on the host track
Watchable[] matches = this.getReferenceTrack().getNearestTo(newStart);
Watchable newRefPt = matches[0];
WorldVector newOffset = newOrigin.subtract(newRefPt.getLocation());
// right, we know where the new track will be, see if we need to ditch any
if(delta > 0)
{
// right, we're shortening the track.
// check the end point is before the end
if (newStart.getMicros() > endDTG().getMicros())
return;
// ok, it's worth bothering with. get ready to store ones we'll lose
Vector<FixWrapper> onesToRemove = new Vector<FixWrapper>();
Iterator<Editable> iter = this.getData().iterator();
while (iter.hasNext())
{
FixWrapper thisF = (FixWrapper) iter.next();
if (thisF.getTime().lessThan(newStart))
{
onesToRemove.add(thisF);
}
}
// and ditch them
for (Iterator<FixWrapper> iterator = onesToRemove.iterator(); iterator
.hasNext();)
{
FixWrapper thisFix = iterator.next();
this.removeElement(thisFix);
}
}
// right, we may have pruned off too far. See if we need to put a bit back in...
if (newStart.lessThan(startDTG()))
{
// right, we if we have to add another
// find the current last point
FixWrapper theLoc = (FixWrapper) this.first();
// don't worry about the location, we're going to DR it on anyway...
WorldLocation newLoc = null;
Fix newFix = new Fix(newStart, newLoc, MWC.Algorithms.Conversions
.Degs2Rads(this.getCourse()), MWC.Algorithms.Conversions.Kts2Yps(this.getSpeed().getValueIn(
WorldSpeed.Kts)));
// and apply the stretch
FixWrapper newItem = new FixWrapper(newFix);
// set some other bits
newItem.setTrackWrapper(this._myTrack);
newItem.setColor(theLoc.getActualColor());
newItem.setSymbolShowing(theLoc.getSymbolShowing());
newItem.setLabelShowing(theLoc.getLabelShowing());
newItem.setLabelLocation(theLoc.getLabelLocation());
newItem.setLabelFormat(theLoc.getLabelFormat());
this.add(newItem);
}
// and sort out the new offset
this._offset = newOffset;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setDTG_Start" | "@FireExtended
public void setDTG_Start(HiResDate newStart)
{
// check that we're still after the start of the host track
if(newStart.lessThan(this.getReferenceTrack().getStartDTG()))
{
newStart = this.getReferenceTrack().getStartDTG();
}
// ok, how far is this from the current end
long delta = newStart.getMicros() - startDTG().getMicros();
// and what distance does this mean?
double deltaHrs = delta / 1000000d / 60d / 60d;
double distDegs = this.getSpeed().getValueIn(WorldSpeed.Kts) * deltaHrs / 60;
double theDirection = MWC.Algorithms.Conversions.Degs2Rads(this.getCourse());
// we don't need to worry about reversing the direction, since we have a -ve distance
// so what's the new origin?
WorldLocation currentStart =new WorldLocation(this.getTrackStart());
WorldLocation newOrigin = currentStart.add(new WorldVector(theDirection, distDegs, 0));
// and what's the point on the host track
Watchable[] matches = this.getReferenceTrack().getNearestTo(newStart);
Watchable newRefPt = matches[0];
WorldVector newOffset = newOrigin.subtract(newRefPt.getLocation());
// right, we know where the new track will be, see if we need to ditch any
if(delta > 0)
{
// right, we're shortening the track.
// check the end point is before the end
if (newStart.getMicros() > endDTG().getMicros())
return;
// ok, it's worth bothering with. get ready to store ones we'll lose
Vector<FixWrapper> onesToRemove = new Vector<FixWrapper>();
Iterator<Editable> iter = this.getData().iterator();
while (iter.hasNext())
{
FixWrapper thisF = (FixWrapper) iter.next();
if (thisF.getTime().lessThan(newStart))
{
onesToRemove.add(thisF);
}
}
// and ditch them
for (Iterator<FixWrapper> iterator = onesToRemove.iterator(); iterator
.hasNext();)
{
FixWrapper thisFix = iterator.next();
this.removeElement(thisFix);
}
}
// right, we may have pruned off too far. See if we need to put a bit back in...
if (newStart.lessThan(startDTG()))
{
// right, we if we have to add another
// find the current last point
FixWrapper theLoc = (FixWrapper) this.first();
// don't worry about the location, we're going to DR it on anyway...
WorldLocation newLoc = null;
Fix newFix = new Fix(newStart, newLoc, MWC.Algorithms.Conversions
.Degs2Rads(this.getCourse()), MWC.Algorithms.Conversions.Kts2Yps(this.getSpeed().getValueIn(
WorldSpeed.Kts)));
// and apply the stretch
FixWrapper newItem = new FixWrapper(newFix);
// set some other bits
<MASK>newItem.setColor(theLoc.getActualColor());</MASK>
newItem.setTrackWrapper(this._myTrack);
newItem.setSymbolShowing(theLoc.getSymbolShowing());
newItem.setLabelShowing(theLoc.getLabelShowing());
newItem.setLabelLocation(theLoc.getLabelLocation());
newItem.setLabelFormat(theLoc.getLabelFormat());
this.add(newItem);
}
// and sort out the new offset
this._offset = newOffset;
}" |
Inversion-Mutation | megadiff | "private void addDatabaseComponents() {
container.addSingleton(JdbcDriverHolder.class);
container.addSingleton(DryRunDatabase.class);
// mybatis
container.addSingleton(BatchDatabase.class);
container.addSingleton(MyBatis.class);
container.addSingleton(DatabaseVersion.class);
container.addSingleton(DatabaseBatchCompatibility.class);
for (Class daoClass : DaoUtils.getDaoClasses()) {
container.addSingleton(daoClass);
}
// hibernate
container.addSingleton(DefaultDatabaseConnector.class);
container.addSingleton(ThreadLocalDatabaseSessionFactory.class);
container.addPicoAdapter(new DatabaseSessionProvider());
container.addSingleton(BatchDatabaseSettingsLoader.class);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addDatabaseComponents" | "private void addDatabaseComponents() {
container.addSingleton(JdbcDriverHolder.class);
container.addSingleton(DryRunDatabase.class);
// mybatis
container.addSingleton(BatchDatabase.class);
container.addSingleton(MyBatis.class);
container.addSingleton(DatabaseVersion.class);
for (Class daoClass : DaoUtils.getDaoClasses()) {
container.addSingleton(daoClass);
}
// hibernate
container.addSingleton(DefaultDatabaseConnector.class);
container.addSingleton(ThreadLocalDatabaseSessionFactory.class);
container.addPicoAdapter(new DatabaseSessionProvider());
<MASK>container.addSingleton(DatabaseBatchCompatibility.class);</MASK>
container.addSingleton(BatchDatabaseSettingsLoader.class);
}" |
Inversion-Mutation | megadiff | "@Test
public void testUpgradeReadLockToOptimisticForceIncrement() throws Exception {
EntityManager em = getOrCreateEntityManager();
final EntityManager em2 = createIsolatedEntityManager();
try {
Lock lock = new Lock(); //
lock.setName( "name" );
em.getTransaction().begin(); // create the test entity first
em.persist( lock );
em.getTransaction().commit();
em.getTransaction().begin(); // start tx1
lock = em.getReference( Lock.class, lock.getId() );
final Integer id = lock.getId();
em.lock( lock, LockModeType.READ ); // start with READ lock in tx1
// upgrade to OPTIMISTIC_FORCE_INCREMENT in tx1
em.lock( lock, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
lock.setName( "surname" ); // don't end tx1 yet
final CountDownLatch latch = new CountDownLatch(1);
Thread t = new Thread( new Runnable() {
public void run() {
try {
em2.getTransaction().begin(); // start tx2
Lock lock2 = em2.getReference( Lock.class, id );
lock2.setName("renamed"); // change entity
}
finally {
em2.getTransaction().commit();
em2.close();
latch.countDown(); // signal that tx2 is committed
}
}
} );
t.setDaemon( true );
t.setName("testUpgradeReadLockToOptimisticForceIncrement tx2");
t.start();
log.info("testUpgradeReadLockToOptimisticForceIncrement: wait on BG thread");
boolean latchSet = latch.await( 10, TimeUnit.SECONDS );
assertTrue( "background test thread finished (lock timeout is broken)", latchSet );
// tx2 is complete, try to commit tx1
try {
em.getTransaction().commit();
}
catch (Throwable expectedToFail) {
while(expectedToFail != null &&
!(expectedToFail instanceof javax.persistence.OptimisticLockException)) {
expectedToFail = expectedToFail.getCause();
}
assertTrue("upgrade to OPTIMISTIC_FORCE_INCREMENT is expected to fail at end of transaction1 since tranaction2 already updated the entity",
expectedToFail instanceof javax.persistence.OptimisticLockException);
}
}
finally {
em.close();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "testUpgradeReadLockToOptimisticForceIncrement" | "@Test
public void testUpgradeReadLockToOptimisticForceIncrement() throws Exception {
EntityManager em = getOrCreateEntityManager();
final EntityManager em2 = createIsolatedEntityManager();
try {
Lock lock = new Lock(); //
lock.setName( "name" );
em.getTransaction().begin(); // create the test entity first
em.persist( lock );
em.getTransaction().commit();
em.getTransaction().begin(); // start tx1
lock = em.getReference( Lock.class, lock.getId() );
final Integer id = lock.getId();
em.lock( lock, LockModeType.READ ); // start with READ lock in tx1
// upgrade to OPTIMISTIC_FORCE_INCREMENT in tx1
em.lock( lock, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
lock.setName( "surname" ); // don't end tx1 yet
final CountDownLatch latch = new CountDownLatch(1);
Thread t = new Thread( new Runnable() {
public void run() {
try {
em2.getTransaction().begin(); // start tx2
Lock lock2 = em2.getReference( Lock.class, id );
lock2.setName("renamed"); // change entity
}
finally {
em2.getTransaction().commit();
<MASK>latch.countDown(); // signal that tx2 is committed</MASK>
em2.close();
}
}
} );
t.setDaemon( true );
t.setName("testUpgradeReadLockToOptimisticForceIncrement tx2");
t.start();
log.info("testUpgradeReadLockToOptimisticForceIncrement: wait on BG thread");
boolean latchSet = latch.await( 10, TimeUnit.SECONDS );
assertTrue( "background test thread finished (lock timeout is broken)", latchSet );
// tx2 is complete, try to commit tx1
try {
em.getTransaction().commit();
}
catch (Throwable expectedToFail) {
while(expectedToFail != null &&
!(expectedToFail instanceof javax.persistence.OptimisticLockException)) {
expectedToFail = expectedToFail.getCause();
}
assertTrue("upgrade to OPTIMISTIC_FORCE_INCREMENT is expected to fail at end of transaction1 since tranaction2 already updated the entity",
expectedToFail instanceof javax.persistence.OptimisticLockException);
}
}
finally {
em.close();
}
}" |
Inversion-Mutation | megadiff | "public void run() {
try {
em2.getTransaction().begin(); // start tx2
Lock lock2 = em2.getReference( Lock.class, id );
lock2.setName("renamed"); // change entity
}
finally {
em2.getTransaction().commit();
em2.close();
latch.countDown(); // signal that tx2 is committed
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run" | "public void run() {
try {
em2.getTransaction().begin(); // start tx2
Lock lock2 = em2.getReference( Lock.class, id );
lock2.setName("renamed"); // change entity
}
finally {
em2.getTransaction().commit();
<MASK>latch.countDown(); // signal that tx2 is committed</MASK>
em2.close();
}
}" |
Inversion-Mutation | megadiff | "@Override
public void onAnimationEnd(Animation animation) {
mCurrentModeFrame.setVisibility(View.VISIBLE);
mModeSelectionFrame.setVisibility(View.GONE);
changeToSelectedMode();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onAnimationEnd" | "@Override
public void onAnimationEnd(Animation animation) {
<MASK>changeToSelectedMode();</MASK>
mCurrentModeFrame.setVisibility(View.VISIBLE);
mModeSelectionFrame.setVisibility(View.GONE);
}" |
Inversion-Mutation | megadiff | "@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException {
try {
this.context = context;
classType = context.getTypeOracle().getType(typeName);
PrintWriter sourceWriter = context.tryCreate(logger, getPackageName(),getClassName());
if (sourceWriter != null) {
StringWriter templateWriter = new StringWriter();
createTemplate().process(scan(), templateWriter);
sourceWriter.print(templateWriter.toString());
context.commit(logger, sourceWriter);
}
return getPackageName() + "." + getClassName();
} catch (Exception e) {
logger.log(TreeLogger.Type.ERROR, e.getMessage());
}
return null;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "generate" | "@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException {
try {
this.context = context;
classType = context.getTypeOracle().getType(typeName);
PrintWriter sourceWriter = context.tryCreate(logger, getPackageName(),getClassName());
if (sourceWriter != null) {
StringWriter templateWriter = new StringWriter();
createTemplate().process(scan(), templateWriter);
sourceWriter.print(templateWriter.toString());
context.commit(logger, sourceWriter);
<MASK>return getPackageName() + "." + getClassName();</MASK>
}
} catch (Exception e) {
logger.log(TreeLogger.Type.ERROR, e.getMessage());
}
return null;
}" |
Inversion-Mutation | megadiff | "public void refresh(final ResourceTraversal[] traversals, int flags, IProgressMonitor monitor) throws CoreException {
SubscriberDiffTreeEventHandler handler = getHandler();
if (handler != null) {
GroupProgressMonitor group = getGroup(monitor);
if (group != null)
handler.setProgressGroupHint(group.getGroup(), group.getTicks());
handler.initializeIfNeeded();
((CVSWorkspaceSubscriber)getSubscriber()).refreshWithContentFetch(traversals, monitor);
runInBackground(new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
cacheContents(traversals, getDiffTree(), true, monitor);
}
});
} else {
super.refresh(traversals, flags, monitor);
runInBackground(new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
cacheContents(traversals, getDiffTree(), false, monitor);
}
});
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "refresh" | "public void refresh(final ResourceTraversal[] traversals, int flags, IProgressMonitor monitor) throws CoreException {
SubscriberDiffTreeEventHandler handler = getHandler();
if (handler != null) {
GroupProgressMonitor group = getGroup(monitor);
if (group != null)
handler.setProgressGroupHint(group.getGroup(), group.getTicks());
handler.initializeIfNeeded();
runInBackground(new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
cacheContents(traversals, getDiffTree(), true, monitor);
}
});
<MASK>((CVSWorkspaceSubscriber)getSubscriber()).refreshWithContentFetch(traversals, monitor);</MASK>
} else {
super.refresh(traversals, flags, monitor);
runInBackground(new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
cacheContents(traversals, getDiffTree(), false, monitor);
}
});
}
}" |
Inversion-Mutation | megadiff | "@Override
public void run() {
while (!done) {
Map<Lock,T> map = ((PessimisticLockManagerImpl)mgr).getLockStore();
System.out.println("Locks currently held at " + new Date() + ":");
for (Lock lock : map.keySet()) {
LockImpl<T> l = (LockImpl) lock;
System.out.println(l);
final long now = System.currentTimeMillis();
final long then = l.getCreationTime();
if (now - then > timeOutMinutes * 60000) {
System.out.println("Removing stale lock " + l);
mgr.releaseLock(l);
}
}
try {
Thread.sleep(1000 * sleepSeconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run" | "@Override
public void run() {
while (!done) {
Map<Lock,T> map = ((PessimisticLockManagerImpl)mgr).getLockStore();
System.out.println("Locks currently held at " + new Date() + ":");
for (Lock lock : map.keySet()) {
LockImpl<T> l = (LockImpl) lock;
System.out.println(l);
final long now = System.currentTimeMillis();
final long then = l.getCreationTime();
if (now - then > timeOutMinutes * 60000) {
System.out.println("Removing stale lock " + l);
}
<MASK>mgr.releaseLock(l);</MASK>
}
try {
Thread.sleep(1000 * sleepSeconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}" |
Inversion-Mutation | megadiff | "private String takeScreenshotAndReturnFileName(ITestResult result) {
String imageName = screenshotFileNameFrom(result);
String imagePath = concat(output, separator, imageName);
try {
output.createIfNecessary();
screenshotTaker.saveDesktopAsPng(imagePath);
} catch (Exception e) {
logger.log(SEVERE, e.getMessage(), e);
return null;
}
return imageName;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "takeScreenshotAndReturnFileName" | "private String takeScreenshotAndReturnFileName(ITestResult result) {
<MASK>output.createIfNecessary();</MASK>
String imageName = screenshotFileNameFrom(result);
String imagePath = concat(output, separator, imageName);
try {
screenshotTaker.saveDesktopAsPng(imagePath);
} catch (Exception e) {
logger.log(SEVERE, e.getMessage(), e);
return null;
}
return imageName;
}" |
Inversion-Mutation | megadiff | "@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_tag_activity);
if (savedInstanceState != null) {
mTagIdInEdit = savedInstanceState.getLong(BUNDLE_KEY_TAG_ID_IN_EDIT, -1);
}
// Set up the check box to toggle My tag sharing.
mEnabled = (CheckBox) findViewById(R.id.toggle_enabled_checkbox);
mEnabled.setChecked(false); // Set after initial data load completes.
findViewById(R.id.toggle_enabled_target).setOnClickListener(this);
// Setup the active tag selector.
mActiveTagDetails = findViewById(R.id.active_tag_details);
mSelectActiveTagAnchor = findViewById(R.id.choose_my_tag);
findViewById(R.id.active_tag).setOnClickListener(this);
updateActiveTagView(null); // Filled in after initial data load.
mActiveTagId = getPreferences(Context.MODE_PRIVATE).getLong(PREF_KEY_ACTIVE_TAG, -1);
// Setup the list.
mAdapter = new TagAdapter(this);
mList = (ListView) findViewById(android.R.id.list);
mList.setAdapter(mAdapter);
mList.setOnItemClickListener(this);
findViewById(R.id.add_tag).setOnClickListener(this);
// Don't setup the empty view until after the first load
// so the empty text doesn't flash when first loading the
// activity.
mList.setEmptyView(null);
// Kick off an async task to load the tags.
new TagLoaderTask().execute((Void[]) null);
// If we're not on a user build offer a back door for writing tags.
// The UX is horrible so we don't want to ship it but need it for testing.
if (!Build.TYPE.equalsIgnoreCase("user")) {
mWriteSupport = true;
}
registerForContextMenu(mList);
if (getIntent().hasExtra(EditTagActivity.EXTRA_RESULT_MSG)) {
NdefMessage msg = (NdefMessage) Preconditions.checkNotNull(
getIntent().getParcelableExtra(EditTagActivity.EXTRA_RESULT_MSG));
saveNewMessage(msg);
}
}" | 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.my_tag_activity);
if (savedInstanceState != null) {
mTagIdInEdit = savedInstanceState.getLong(BUNDLE_KEY_TAG_ID_IN_EDIT, -1);
}
// Set up the check box to toggle My tag sharing.
mEnabled = (CheckBox) findViewById(R.id.toggle_enabled_checkbox);
mEnabled.setChecked(false); // Set after initial data load completes.
findViewById(R.id.toggle_enabled_target).setOnClickListener(this);
// Setup the active tag selector.
mActiveTagDetails = findViewById(R.id.active_tag_details);
mSelectActiveTagAnchor = findViewById(R.id.choose_my_tag);
findViewById(R.id.active_tag).setOnClickListener(this);
updateActiveTagView(null); // Filled in after initial data load.
mActiveTagId = getPreferences(Context.MODE_PRIVATE).getLong(PREF_KEY_ACTIVE_TAG, -1);
// Setup the list.
mAdapter = new TagAdapter(this);
mList = (ListView) findViewById(android.R.id.list);
mList.setAdapter(mAdapter);
mList.setOnItemClickListener(this);
findViewById(R.id.add_tag).setOnClickListener(this);
// Don't setup the empty view until after the first load
// so the empty text doesn't flash when first loading the
// activity.
mList.setEmptyView(null);
// Kick off an async task to load the tags.
new TagLoaderTask().execute((Void[]) null);
// If we're not on a user build offer a back door for writing tags.
// The UX is horrible so we don't want to ship it but need it for testing.
if (!Build.TYPE.equalsIgnoreCase("user")) {
mWriteSupport = true;
<MASK>registerForContextMenu(mList);</MASK>
}
if (getIntent().hasExtra(EditTagActivity.EXTRA_RESULT_MSG)) {
NdefMessage msg = (NdefMessage) Preconditions.checkNotNull(
getIntent().getParcelableExtra(EditTagActivity.EXTRA_RESULT_MSG));
saveNewMessage(msg);
}
}" |
Inversion-Mutation | megadiff | "private void applySepia() {
if (mCurrentlyDisplayedBitmap != null) {
Bitmap tmp = ImageFilter.sepia(mCurrentlyDisplayedBitmap);
ivPicture.setImageBitmap(mCurrentlyDisplayedBitmap);
mCurrentlyDisplayedBitmap.recycle();
mCurrentlyDisplayedBitmap = tmp;
} else {
Toast.makeText(this, "No ale nie ma jeszcze żadnego zdjęcia...", Toast.LENGTH_LONG).show();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "applySepia" | "private void applySepia() {
if (mCurrentlyDisplayedBitmap != null) {
Bitmap tmp = ImageFilter.sepia(mCurrentlyDisplayedBitmap);
mCurrentlyDisplayedBitmap.recycle();
mCurrentlyDisplayedBitmap = tmp;
<MASK>ivPicture.setImageBitmap(mCurrentlyDisplayedBitmap);</MASK>
} else {
Toast.makeText(this, "No ale nie ma jeszcze żadnego zdjęcia...", Toast.LENGTH_LONG).show();
}
}" |
Inversion-Mutation | megadiff | "@Override
public boolean engine(GPSProblem myProblem, SearchStrategy myStrategy,
StatsHolder holder) {
boolean solutionFound = false;
while (!solutionFound) {
holder.resetStats();
solutionFound = super.engine(myProblem, myStrategy, holder);
depth++;
}
return solutionFound;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "engine" | "@Override
public boolean engine(GPSProblem myProblem, SearchStrategy myStrategy,
StatsHolder holder) {
boolean solutionFound = false;
while (!solutionFound) {
<MASK>depth++;</MASK>
holder.resetStats();
solutionFound = super.engine(myProblem, myStrategy, holder);
}
return solutionFound;
}" |
Inversion-Mutation | megadiff | "public void endElement(final Object parent, final String tag, final Object node, final XMLElement attributes,
final String content) {
if (tag.equals("richcontent")) {
final String xmlText = content;
final Object typeAttribute = attributes.getAttribute(NodeTextBuilder.XML_NODE_XHTML_TYPE_TAG, null);
if (NodeTextBuilder.XML_NODE_XHTML_TYPE_NOTE.equals(typeAttribute)) {
final NoteModel note = new NoteModel();
note.setXml(xmlText);
((NodeModel) node).addExtension((IExtension) note);
noteController.setStateIcon(((NodeModel) node), true);
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "endElement" | "public void endElement(final Object parent, final String tag, final Object node, final XMLElement attributes,
final String content) {
if (tag.equals("richcontent")) {
final String xmlText = content;
final Object typeAttribute = attributes.getAttribute(NodeTextBuilder.XML_NODE_XHTML_TYPE_TAG, null);
if (NodeTextBuilder.XML_NODE_XHTML_TYPE_NOTE.equals(typeAttribute)) {
final NoteModel note = new NoteModel();
<MASK>noteController.setStateIcon(((NodeModel) node), true);</MASK>
note.setXml(xmlText);
((NodeModel) node).addExtension((IExtension) note);
}
}
}" |
Inversion-Mutation | megadiff | "public void switchLogFile() throws StandardException
{
boolean switchedOver = false;
/////////////////////////////////////////////////////
// Freeze the log for the switch over to a new log file.
// This blocks out any other threads from sending log
// record to the log stream.
//
// The switching of the log file and checkpoint are really
// independent events, they are tied together just because a
// checkpoint is the natural place to switch the log and vice
// versa. This could happen before the cache is flushed or
// after the checkpoint log record is written.
/////////////////////////////////////////////////////
synchronized (this)
{
// Make sure that this thread of control is guaranteed to complete
// it's work of switching the log file without having to give up
// the semaphore to a backup or another flusher. Do this by looping
// until we have the semaphore, the log is not being flushed, and
// the log is not frozen for backup. Track (2985).
while(logBeingFlushed | isFrozen)
{
try
{
wait();
}
catch (InterruptedException ie)
{
InterruptStatus.setInterrupted();
}
}
// we have an empty log file here, refuse to switch.
if (endPosition == LOG_FILE_HEADER_SIZE)
{
if (SanityManager.DEBUG)
{
Monitor.logMessage("not switching from an empty log file (" +
logFileNumber + ")");
}
return;
}
// log file isn't being flushed right now and logOut is not being
// used.
StorageFile newLogFile = getLogFileName(logFileNumber+1);
if (logFileNumber+1 >= maxLogFileNumber)
{
throw StandardException.newException(
SQLState.LOG_EXCEED_MAX_LOG_FILE_NUMBER,
new Long(maxLogFileNumber));
}
StorageRandomAccessFile newLog = null; // the new log file
try
{
// if the log file exist and cannot be deleted, cannot
// switch log right now
if (privExists(newLogFile) && !privDelete(newLogFile))
{
logErrMsg(MessageService.getTextMessage(
MessageId.LOG_NEW_LOGFILE_EXIST,
newLogFile.getPath()));
return;
}
try
{
newLog = privRandomAccessFile(newLogFile, "rw");
}
catch (IOException ioe)
{
newLog = null;
}
if (newLog == null || !privCanWrite(newLogFile))
{
if (newLog != null)
newLog.close();
newLog = null;
return;
}
if (initLogFile(newLog, logFileNumber+1,
LogCounter.makeLogInstantAsLong(logFileNumber, endPosition)))
{
// New log file init ok, close the old one and
// switch over, after this point, need to shutdown the
// database if any error crops up
switchedOver = true;
// write out an extra 0 at the end to mark the end of the log
// file.
logOut.writeEndMarker(0);
endPosition += 4;
//set that we are in log switch to prevent flusher
//not requesting to switch log again
inLogSwitch = true;
// flush everything including the int we just wrote
flush(logFileNumber, endPosition);
// simulate out of log error after the switch over
if (SanityManager.DEBUG)
{
if (SanityManager.DEBUG_ON(TEST_SWITCH_LOG_FAIL2))
throw new IOException("TestLogSwitchFail2");
}
logOut.close(); // close the old log file
logWrittenFromLastCheckPoint += endPosition;
endPosition = newLog.getFilePointer();
lastFlush = endPosition;
if(isWriteSynced)
{
//extend the file by wring zeros to it
preAllocateNewLogFile(newLog);
newLog.close();
newLog = openLogFileInWriteMode(newLogFile);
newLog.seek(endPosition);
}
logOut = new LogAccessFile(this, newLog, logBufferSize);
newLog = null;
if (SanityManager.DEBUG)
{
if (endPosition != LOG_FILE_HEADER_SIZE)
SanityManager.THROWASSERT(
"new log file has unexpected size" +
+ endPosition);
}
logFileNumber++;
if (SanityManager.DEBUG)
{
SanityManager.ASSERT(endPosition == LOG_FILE_HEADER_SIZE,
"empty log file has wrong size");
}
}
else // something went wrong, delete the half baked file
{
newLog.close();
newLog = null;
if (privExists(newLogFile))
privDelete(newLogFile);
logErrMsg(MessageService.getTextMessage(
MessageId.LOG_CANNOT_CREATE_NEW,
newLogFile.getPath()));
newLogFile = null;
}
}
catch (IOException ioe)
{
inLogSwitch = false;
// switching log file is an optional operation and there is no direct user
// control. Just sends a warning message to whomever, if any,
// system adminstrator there may be
logErrMsg(MessageService.getTextMessage(
MessageId.LOG_CANNOT_CREATE_NEW_DUETO,
newLogFile.getPath(),
ioe.toString()));
try
{
if (newLog != null)
{
newLog.close();
newLog = null;
}
}
catch (IOException ioe2) {}
if (newLogFile != null && privExists(newLogFile))
{
privDelete(newLogFile);
newLogFile = null;
}
if (switchedOver) // error occur after old log file has been closed!
{
logOut = null; // limit any damage
throw markCorrupt(
StandardException.newException(
SQLState.LOG_IO_ERROR, ioe));
}
}
// Replication slave: Recovery thread should be allowed to
// read the previous log file
if (inReplicationSlaveMode) {
allowedToReadFileNumber = logFileNumber-1;
synchronized (slaveRecoveryMonitor) {
slaveRecoveryMonitor.notify();
}
}
inLogSwitch = false;
}
// unfreezes the log
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "switchLogFile" | "public void switchLogFile() throws StandardException
{
boolean switchedOver = false;
/////////////////////////////////////////////////////
// Freeze the log for the switch over to a new log file.
// This blocks out any other threads from sending log
// record to the log stream.
//
// The switching of the log file and checkpoint are really
// independent events, they are tied together just because a
// checkpoint is the natural place to switch the log and vice
// versa. This could happen before the cache is flushed or
// after the checkpoint log record is written.
/////////////////////////////////////////////////////
synchronized (this)
{
// Make sure that this thread of control is guaranteed to complete
// it's work of switching the log file without having to give up
// the semaphore to a backup or another flusher. Do this by looping
// until we have the semaphore, the log is not being flushed, and
// the log is not frozen for backup. Track (2985).
while(logBeingFlushed | isFrozen)
{
try
{
wait();
}
catch (InterruptedException ie)
{
InterruptStatus.setInterrupted();
}
}
// we have an empty log file here, refuse to switch.
if (endPosition == LOG_FILE_HEADER_SIZE)
{
if (SanityManager.DEBUG)
{
Monitor.logMessage("not switching from an empty log file (" +
logFileNumber + ")");
}
return;
}
// log file isn't being flushed right now and logOut is not being
// used.
StorageFile newLogFile = getLogFileName(logFileNumber+1);
if (logFileNumber+1 >= maxLogFileNumber)
{
throw StandardException.newException(
SQLState.LOG_EXCEED_MAX_LOG_FILE_NUMBER,
new Long(maxLogFileNumber));
}
StorageRandomAccessFile newLog = null; // the new log file
try
{
// if the log file exist and cannot be deleted, cannot
// switch log right now
if (privExists(newLogFile) && !privDelete(newLogFile))
{
logErrMsg(MessageService.getTextMessage(
MessageId.LOG_NEW_LOGFILE_EXIST,
newLogFile.getPath()));
return;
}
try
{
newLog = privRandomAccessFile(newLogFile, "rw");
}
catch (IOException ioe)
{
newLog = null;
}
if (newLog == null || !privCanWrite(newLogFile))
{
if (newLog != null)
newLog.close();
newLog = null;
return;
}
if (initLogFile(newLog, logFileNumber+1,
LogCounter.makeLogInstantAsLong(logFileNumber, endPosition)))
{
// New log file init ok, close the old one and
// switch over, after this point, need to shutdown the
// database if any error crops up
switchedOver = true;
// write out an extra 0 at the end to mark the end of the log
// file.
logOut.writeEndMarker(0);
endPosition += 4;
//set that we are in log switch to prevent flusher
//not requesting to switch log again
inLogSwitch = true;
// flush everything including the int we just wrote
flush(logFileNumber, endPosition);
// simulate out of log error after the switch over
if (SanityManager.DEBUG)
{
if (SanityManager.DEBUG_ON(TEST_SWITCH_LOG_FAIL2))
throw new IOException("TestLogSwitchFail2");
}
logOut.close(); // close the old log file
logWrittenFromLastCheckPoint += endPosition;
endPosition = newLog.getFilePointer();
lastFlush = endPosition;
if(isWriteSynced)
{
//extend the file by wring zeros to it
preAllocateNewLogFile(newLog);
newLog.close();
newLog = openLogFileInWriteMode(newLogFile);
newLog.seek(endPosition);
}
logOut = new LogAccessFile(this, newLog, logBufferSize);
newLog = null;
if (SanityManager.DEBUG)
{
if (endPosition != LOG_FILE_HEADER_SIZE)
SanityManager.THROWASSERT(
"new log file has unexpected size" +
+ endPosition);
}
logFileNumber++;
if (SanityManager.DEBUG)
{
SanityManager.ASSERT(endPosition == LOG_FILE_HEADER_SIZE,
"empty log file has wrong size");
}
}
else // something went wrong, delete the half baked file
{
newLog.close();
newLog = null;
if (privExists(newLogFile))
privDelete(newLogFile);
<MASK>newLogFile = null;</MASK>
logErrMsg(MessageService.getTextMessage(
MessageId.LOG_CANNOT_CREATE_NEW,
newLogFile.getPath()));
}
}
catch (IOException ioe)
{
inLogSwitch = false;
// switching log file is an optional operation and there is no direct user
// control. Just sends a warning message to whomever, if any,
// system adminstrator there may be
logErrMsg(MessageService.getTextMessage(
MessageId.LOG_CANNOT_CREATE_NEW_DUETO,
newLogFile.getPath(),
ioe.toString()));
try
{
if (newLog != null)
{
newLog.close();
newLog = null;
}
}
catch (IOException ioe2) {}
if (newLogFile != null && privExists(newLogFile))
{
privDelete(newLogFile);
<MASK>newLogFile = null;</MASK>
}
if (switchedOver) // error occur after old log file has been closed!
{
logOut = null; // limit any damage
throw markCorrupt(
StandardException.newException(
SQLState.LOG_IO_ERROR, ioe));
}
}
// Replication slave: Recovery thread should be allowed to
// read the previous log file
if (inReplicationSlaveMode) {
allowedToReadFileNumber = logFileNumber-1;
synchronized (slaveRecoveryMonitor) {
slaveRecoveryMonitor.notify();
}
}
inLogSwitch = false;
}
// unfreezes the log
}" |
Inversion-Mutation | megadiff | "public void internalAbortWorkItem(long id) {
Environment env = this.kruntime.getEnvironment();
EntityManager em = (EntityManager) env.get(EnvironmentName.CMD_SCOPED_ENTITY_MANAGER);
WorkItemInfo workItemInfo = em.find(WorkItemInfo.class, id);
// work item may have been aborted
if (workItemInfo != null) {
WorkItemImpl workItem = (WorkItemImpl) workItemInfo.getWorkItem(env);
WorkItemHandler handler = (WorkItemHandler) this.workItemHandlers.get(workItem.getName());
if (handler != null) {
handler.abortWorkItem(workItem, this);
} else {
if ( workItems != null ) {
workItems.remove( id );
throwWorkItemNotFoundException( workItem );
}
}
if (workItems != null) {
workItems.remove(id);
}
em.remove(workItemInfo);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "internalAbortWorkItem" | "public void internalAbortWorkItem(long id) {
Environment env = this.kruntime.getEnvironment();
EntityManager em = (EntityManager) env.get(EnvironmentName.CMD_SCOPED_ENTITY_MANAGER);
WorkItemInfo workItemInfo = em.find(WorkItemInfo.class, id);
// work item may have been aborted
if (workItemInfo != null) {
WorkItemImpl workItem = (WorkItemImpl) workItemInfo.getWorkItem(env);
WorkItemHandler handler = (WorkItemHandler) this.workItemHandlers.get(workItem.getName());
if (handler != null) {
handler.abortWorkItem(workItem, this);
} else {
if ( workItems != null ) {
workItems.remove( id );
}
<MASK>throwWorkItemNotFoundException( workItem );</MASK>
}
if (workItems != null) {
workItems.remove(id);
}
em.remove(workItemInfo);
}
}" |
Inversion-Mutation | megadiff | "public boolean isConditionTrue(String id, Properties variables)
{
Condition cond = getCondition(id);
if (cond == null)
{
Debug.trace("Condition (" + id + ") not found.");
return true;
}
else
{
cond.setInstalldata(installdata);
Debug.trace("Checking condition");
try
{
return cond.isTrue();
}
catch (NullPointerException npe)
{
Debug.error("Nullpointerexception checking condition: " + id);
return false;
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "isConditionTrue" | "public boolean isConditionTrue(String id, Properties variables)
{
Condition cond = getCondition(id);
<MASK>cond.setInstalldata(installdata);</MASK>
if (cond == null)
{
Debug.trace("Condition (" + id + ") not found.");
return true;
}
else
{
Debug.trace("Checking condition");
try
{
return cond.isTrue();
}
catch (NullPointerException npe)
{
Debug.error("Nullpointerexception checking condition: " + id);
return false;
}
}
}" |
Inversion-Mutation | megadiff | "public static Test suite() {
TestSuite suite = new TestSuite("Test for org.eclipse.mylar.tests");
//$JUnit-BEGIN$
suite.addTest(AllMonitorTests.suite());
suite.addTest(AllXmlTests.suite()); // HACK: first because it doesn't clean up properly
suite.addTest(AllCoreTests.suite());
suite.addTest(AllTasklistTests.suite());
suite.addTest(AllJavaTests.suite());
suite.addTest(MiscTests.suite());
//$JUnit-END$
return suite;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "suite" | "public static Test suite() {
TestSuite suite = new TestSuite("Test for org.eclipse.mylar.tests");
//$JUnit-BEGIN$
suite.addTest(AllMonitorTests.suite());
suite.addTest(AllXmlTests.suite()); // HACK: first because it doesn't clean up properly
<MASK>suite.addTest(AllJavaTests.suite());</MASK>
suite.addTest(AllCoreTests.suite());
suite.addTest(AllTasklistTests.suite());
suite.addTest(MiscTests.suite());
//$JUnit-END$
return suite;
}" |
Inversion-Mutation | megadiff | "Painter(Area area, double mag, Layer la, AffineTransform at) throws Exception {
super("AreaWrapper.Painter");
setPriority(Thread.NORM_PRIORITY);
this.la = la;
this.at = at;
this.at_inv = at.createInverse();
// if adding areas, make it be a copy, to be added on mouse release
// (In this way, the receiving Area is small and can be operated on fast)
if (adding) {
this.target_area = area;
this.area = new Area();
} else {
this.target_area = area;
this.area = area;
}
brush_size = ProjectToolbar.getBrushSize();
brush = makeBrush(brush_size, mag);
if (null == brush) throw new RuntimeException("Can't paint with brush of size 0.");
accumulator = Utils.newFixedThreadPool(1, "AreaWrapper-accumulator");
composer = Executors.newScheduledThreadPool(1);
this.interpolator = new Runnable() {
public void run() {
final ArrayList<Point> ps;
final int n_points;
synchronized (arealock) {
n_points = points.size();
if (0 == n_points) return;
ps = new ArrayList<Point>(points);
points.clear();
points.add(ps.get(n_points -1)); // to start the next spline from the last point
}
if (n_points < 2) {
// No interpolation required
final AffineTransform atb = new AffineTransform(1, 0, 0, 1, ps.get(0).x, ps.get(0).y);
atb.preConcatenate(at_inv);
Area chunk = slashInInts(brush.createTransformedArea(atb));
synchronized (arealock) {
if (adding) Painter.this.area.add(chunk);
else Painter.this.area.subtract(chunk);
}
return;
}
try {
// paint the regions between points, using spline interpolation
// A cheap way would be to just make a rectangle between both points, with thickess radius.
// A better, expensive way is to fit a spline first, then add each one as a circle.
// The spline way is wasteful, but way more precise and beautiful. Since there's only one repaint, it's not excessively slow.
int[] xp = new int[ps.size()];
int[] yp = new int[xp.length];
int j = 0;
for (final Point p : ps) {
xp[j] = p.x;
yp[j] = p.y;
j++;
}
PolygonRoi proi = new PolygonRoi(xp, yp, xp.length, Roi.POLYLINE);
proi.fitSpline();
FloatPolygon fp = proi.getFloatPolygon();
proi = null;
double[] xpd = new double[fp.npoints];
double[] ypd = new double[fp.npoints];
// Fails: fp contains float[], which for some reason cannot be copied into double[]
//System.arraycopy(fp.xpoints, 0, xpd, 0, xpd.length);
//System.arraycopy(fp.ypoints, 0, ypd, 0, ypd.length);
for (int i=0; i<xpd.length; i++) {
xpd[i] = fp.xpoints[i];
ypd[i] = fp.ypoints[i];
}
fp = null;
// VectorString2D resampling doesn't work
VectorString3D vs = new VectorString3D(xpd, ypd, new double[xpd.length], false);
double delta = ((double)brush_size) / 10;
if (delta < 1) delta = 1;
vs.resample(delta);
xpd = vs.getPoints(0);
ypd = vs.getPoints(1);
vs = null;
// adjust first and last points back to integer precision
Point po = ps.get(0);
xpd[0] = po.x;
ypd[0] = po.y;
po = ps.get(ps.size()-1);
xpd[xpd.length-1] = po.x;
ypd[ypd.length-1] = po.y;
final Area chunk = new Area();
final AffineTransform atb = new AffineTransform();
for (int i=0; i<xpd.length; i++) {
atb.setToTranslation((int)xpd[i], (int)ypd[i]); // always integers
atb.preConcatenate(at_inv);
chunk.add(slashInInts(brush.createTransformedArea(atb)));
}
synchronized (arealock) {
if (adding) Painter.this.area.add(chunk);
else Painter.this.area.subtract(chunk);
}
Display.repaint(Painter.this.la, 3, r_old, false, false);
} catch (Exception e) {
IJError.print(e);
}
}
};
composition = composer.scheduleWithFixedDelay(interpolator, 200, 500, TimeUnit.MILLISECONDS);
start();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "Painter" | "Painter(Area area, double mag, Layer la, AffineTransform at) throws Exception {
super("AreaWrapper.Painter");
setPriority(Thread.NORM_PRIORITY);
this.la = la;
this.at = at;
this.at_inv = at.createInverse();
// if adding areas, make it be a copy, to be added on mouse release
// (In this way, the receiving Area is small and can be operated on fast)
if (adding) {
this.target_area = area;
this.area = new Area();
} else {
this.target_area = area;
this.area = area;
}
brush_size = ProjectToolbar.getBrushSize();
brush = makeBrush(brush_size, mag);
if (null == brush) throw new RuntimeException("Can't paint with brush of size 0.");
<MASK>start();</MASK>
accumulator = Utils.newFixedThreadPool(1, "AreaWrapper-accumulator");
composer = Executors.newScheduledThreadPool(1);
this.interpolator = new Runnable() {
public void run() {
final ArrayList<Point> ps;
final int n_points;
synchronized (arealock) {
n_points = points.size();
if (0 == n_points) return;
ps = new ArrayList<Point>(points);
points.clear();
points.add(ps.get(n_points -1)); // to start the next spline from the last point
}
if (n_points < 2) {
// No interpolation required
final AffineTransform atb = new AffineTransform(1, 0, 0, 1, ps.get(0).x, ps.get(0).y);
atb.preConcatenate(at_inv);
Area chunk = slashInInts(brush.createTransformedArea(atb));
synchronized (arealock) {
if (adding) Painter.this.area.add(chunk);
else Painter.this.area.subtract(chunk);
}
return;
}
try {
// paint the regions between points, using spline interpolation
// A cheap way would be to just make a rectangle between both points, with thickess radius.
// A better, expensive way is to fit a spline first, then add each one as a circle.
// The spline way is wasteful, but way more precise and beautiful. Since there's only one repaint, it's not excessively slow.
int[] xp = new int[ps.size()];
int[] yp = new int[xp.length];
int j = 0;
for (final Point p : ps) {
xp[j] = p.x;
yp[j] = p.y;
j++;
}
PolygonRoi proi = new PolygonRoi(xp, yp, xp.length, Roi.POLYLINE);
proi.fitSpline();
FloatPolygon fp = proi.getFloatPolygon();
proi = null;
double[] xpd = new double[fp.npoints];
double[] ypd = new double[fp.npoints];
// Fails: fp contains float[], which for some reason cannot be copied into double[]
//System.arraycopy(fp.xpoints, 0, xpd, 0, xpd.length);
//System.arraycopy(fp.ypoints, 0, ypd, 0, ypd.length);
for (int i=0; i<xpd.length; i++) {
xpd[i] = fp.xpoints[i];
ypd[i] = fp.ypoints[i];
}
fp = null;
// VectorString2D resampling doesn't work
VectorString3D vs = new VectorString3D(xpd, ypd, new double[xpd.length], false);
double delta = ((double)brush_size) / 10;
if (delta < 1) delta = 1;
vs.resample(delta);
xpd = vs.getPoints(0);
ypd = vs.getPoints(1);
vs = null;
// adjust first and last points back to integer precision
Point po = ps.get(0);
xpd[0] = po.x;
ypd[0] = po.y;
po = ps.get(ps.size()-1);
xpd[xpd.length-1] = po.x;
ypd[ypd.length-1] = po.y;
final Area chunk = new Area();
final AffineTransform atb = new AffineTransform();
for (int i=0; i<xpd.length; i++) {
atb.setToTranslation((int)xpd[i], (int)ypd[i]); // always integers
atb.preConcatenate(at_inv);
chunk.add(slashInInts(brush.createTransformedArea(atb)));
}
synchronized (arealock) {
if (adding) Painter.this.area.add(chunk);
else Painter.this.area.subtract(chunk);
}
Display.repaint(Painter.this.la, 3, r_old, false, false);
} catch (Exception e) {
IJError.print(e);
}
}
};
composition = composer.scheduleWithFixedDelay(interpolator, 200, 500, TimeUnit.MILLISECONDS);
}" |
Inversion-Mutation | megadiff | "@Override
public void update(float deltaTime) {
List<TouchEvent> touchEvents = game.getInput().getTouchEvents();
game.getInput().getKeyEvents();
int len = touchEvents.size();
for(int i = 0; i < len; i++) {
TouchEvent event = touchEvents.get(i);
if(event.type == TouchEvent.TOUCH_UP) {
//int contin_x = g.getWidth()/2 - Assets.contin.getWidth()/2;
//int contin_y = (int) (g.getHeight() - (g.getHeight()*.05)) - Assets.contin.getHeight();
int next_x = game.getGraphics().getWidth() - Assets.next.getWidth();
int next_y = game.getGraphics().getHeight() - Assets.next.getHeight();
int back_x = game.getGraphics().getWidth() - Assets.back.getWidth() - Assets.next.getWidth() - 50;
int back_y = game.getGraphics().getHeight() - Assets.back.getHeight();
int home_x = 0;
int home_y = game.getGraphics().getHeight() - Assets.home.getHeight();
//Did you click next?
if(event.x > next_x && event.x < next_x + Assets.next.getWidth() && event.y > next_y && event.y < Assets.next.getWidth() + next_y){
Assets.click.play(1);
if(Assets.helpScreen.length == (index+1)){
game.getGraphics().clear(0);
game.setScreen(new MainMenuScreen(game));
return;
}else{
game.getGraphics().clear(0);
game.setScreen(new HelpScreen(game, index+1));
}
}
//Did you click back?
if(event.x > back_x && event.x < back_x + Assets.back.getWidth() && event.y > back_y && event.y < Assets.back.getWidth() + back_y){
Assets.click.play(1);
if(index == 0){
game.getGraphics().clear(0);
game.setScreen(new MainMenuScreen(game));
return;
}else{
game.getGraphics().clear(0);
game.setScreen(new HelpScreen(game, index-1));
}
}
//Did you click home?
if(event.x > home_x && event.x < home_x + Assets.home.getWidth() && event.y > home_y && event.y < Assets.home.getWidth() + home_y){
Assets.click.play(1);
game.getGraphics().clear(0);
game.setScreen(new MainMenuScreen(game));
}
/*if(event.x > 256 && event.y > 416 ) {
game.getGraphics().clear(0);
Assets.click.play(1);
if(!(Assets.helpScreen.length == i)){
game.setScreen(new HelpScreen(game, i+1));
}
return;
}*/
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "update" | "@Override
public void update(float deltaTime) {
List<TouchEvent> touchEvents = game.getInput().getTouchEvents();
game.getInput().getKeyEvents();
int len = touchEvents.size();
for(int i = 0; i < len; i++) {
TouchEvent event = touchEvents.get(i);
if(event.type == TouchEvent.TOUCH_UP) {
//int contin_x = g.getWidth()/2 - Assets.contin.getWidth()/2;
//int contin_y = (int) (g.getHeight() - (g.getHeight()*.05)) - Assets.contin.getHeight();
int next_x = game.getGraphics().getWidth() - Assets.next.getWidth();
int next_y = game.getGraphics().getHeight() - Assets.next.getHeight();
int back_x = game.getGraphics().getWidth() - Assets.back.getWidth() - Assets.next.getWidth() - 50;
int back_y = game.getGraphics().getHeight() - Assets.back.getHeight();
int home_x = 0;
int home_y = game.getGraphics().getHeight() - Assets.home.getHeight();
//Did you click next?
if(event.x > next_x && event.x < next_x + Assets.next.getWidth() && event.y > next_y && event.y < Assets.next.getWidth() + next_y){
<MASK>Assets.click.play(1);</MASK>
if(Assets.helpScreen.length == (index+1)){
game.getGraphics().clear(0);
game.setScreen(new MainMenuScreen(game));
return;
}else{
game.getGraphics().clear(0);
game.setScreen(new HelpScreen(game, index+1));
}
}
//Did you click back?
if(event.x > back_x && event.x < back_x + Assets.back.getWidth() && event.y > back_y && event.y < Assets.back.getWidth() + back_y){
if(index == 0){
<MASK>Assets.click.play(1);</MASK>
game.getGraphics().clear(0);
game.setScreen(new MainMenuScreen(game));
return;
}else{
game.getGraphics().clear(0);
game.setScreen(new HelpScreen(game, index-1));
}
}
//Did you click home?
if(event.x > home_x && event.x < home_x + Assets.home.getWidth() && event.y > home_y && event.y < Assets.home.getWidth() + home_y){
<MASK>Assets.click.play(1);</MASK>
game.getGraphics().clear(0);
game.setScreen(new MainMenuScreen(game));
}
/*if(event.x > 256 && event.y > 416 ) {
game.getGraphics().clear(0);
<MASK>Assets.click.play(1);</MASK>
if(!(Assets.helpScreen.length == i)){
game.setScreen(new HelpScreen(game, i+1));
}
return;
}*/
}
}
}" |
Inversion-Mutation | megadiff | "final void finishFullFlush(boolean success) {
assert setFlushingDeleteQueue(null);
if (success) {
// release the flush lock
flushControl.finishFullFlush();
} else {
flushControl.abortFullFlushes();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "finishFullFlush" | "final void finishFullFlush(boolean success) {
if (success) {
// release the flush lock
flushControl.finishFullFlush();
} else {
flushControl.abortFullFlushes();
}
<MASK>assert setFlushingDeleteQueue(null);</MASK>
}" |
Inversion-Mutation | megadiff | "public void run() {
startTime = System.currentTimeMillis();
if (DEBUG) System.out.println(jobType+" Job: "+jobName+" started");
ActivityLogger.logJobStarted(jobName, jobType, upCell, savedHighlights, savedHighlightsOffset);
try {
if (jobType != Type.EXAMINE) changingJob = this;
if (jobType == Type.CHANGE) Undo.startChanges(tool, jobName, upCell, savedHighlights, savedHighlightsOffset);
doIt();
if (jobType == Type.CHANGE) Undo.endChanges();
} catch (Throwable e) {
endTime = System.currentTimeMillis();
e.printStackTrace(System.err);
ActivityLogger.logException(e);
if (e instanceof Error) throw (Error)e;
} finally {
if (jobType == Type.EXAMINE)
{
databaseChangesThread.endExamine(this);
} else {
changingJob = null;
Library.clearChangeLocks();
}
endTime = System.currentTimeMillis();
}
if (DEBUG) System.out.println(jobType+" Job: "+jobName +" finished");
finished = true; // is this redundant with Thread.isAlive()?
// Job.removeJob(this);
//WindowFrame.wantToRedoJobTree();
// say something if it took more than a minute by default
if (reportExecution || (endTime - startTime) >= MIN_NUM_SECONDS)
{
if (User.isBeepAfterLongJobs())
{
Toolkit.getDefaultToolkit().beep();
}
System.out.println(this.getInfo());
}
// delete
if (deleteWhenDone) {
databaseChangesThread.removeJob(this);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run" | "public void run() {
startTime = System.currentTimeMillis();
if (DEBUG) System.out.println(jobType+" Job: "+jobName+" started");
ActivityLogger.logJobStarted(jobName, jobType, upCell, savedHighlights, savedHighlightsOffset);
try {
if (jobType == Type.CHANGE) Undo.startChanges(tool, jobName, upCell, savedHighlights, savedHighlightsOffset);
<MASK>if (jobType != Type.EXAMINE) changingJob = this;</MASK>
doIt();
if (jobType == Type.CHANGE) Undo.endChanges();
} catch (Throwable e) {
endTime = System.currentTimeMillis();
e.printStackTrace(System.err);
ActivityLogger.logException(e);
if (e instanceof Error) throw (Error)e;
} finally {
if (jobType == Type.EXAMINE)
{
databaseChangesThread.endExamine(this);
} else {
changingJob = null;
Library.clearChangeLocks();
}
endTime = System.currentTimeMillis();
}
if (DEBUG) System.out.println(jobType+" Job: "+jobName +" finished");
finished = true; // is this redundant with Thread.isAlive()?
// Job.removeJob(this);
//WindowFrame.wantToRedoJobTree();
// say something if it took more than a minute by default
if (reportExecution || (endTime - startTime) >= MIN_NUM_SECONDS)
{
if (User.isBeepAfterLongJobs())
{
Toolkit.getDefaultToolkit().beep();
}
System.out.println(this.getInfo());
}
// delete
if (deleteWhenDone) {
databaseChangesThread.removeJob(this);
}
}" |
Inversion-Mutation | megadiff | "protected int feedData() {
if(initFeed){
initFeed = false;
boolean feedResult;
if(learnAhead){
feedResult = dbHelper.getListItems(-1, learningQueueSize, learnQueue, 3, activeFilter);
}
else{
feedResult = dbHelper.getListItems(-1, learningQueueSize, learnQueue, 4, activeFilter);
}
if(feedResult == true){
for(int i = 0; i < learnQueue.size(); i++){
Item qItem = learnQueue.get(i);
if(qItem.isScheduled()){
if(maxRetId < qItem.getId()){
maxRetId = qItem.getId();
}
}
else{
if(maxNewId < qItem.getId()){
maxNewId = qItem.getId();
}
}
}
/* Shuffling the queue */
if(shufflingCards){
Collections.shuffle(learnQueue);
}
currentItem = learnQueue.get(0);
return 0;
}
else{
currentItem = null;
return 2;
}
}
else{
Item item;
for(int i = learnQueue.size(); i < learningQueueSize; i++){
if(learnAhead){
/* Flag = 3 for randomly choose item from future */
item = dbHelper.getItemById(0, 3, true, activeFilter);
learnQueue.add(item);
}
else{
/* Search out the maxRetId and maxNew Id
* before queuing in order to achive consistence
*/
for(int j = 0; j < learnQueue.size(); j++){
Item qItem = learnQueue.get(j);
if(qItem.isScheduled()){
if(maxRetId < qItem.getId()){
maxRetId = qItem.getId();
}
}
else{
if(maxNewId < qItem.getId()){
maxNewId = qItem.getId();
}
}
}
item = dbHelper.getItemById(maxRetId + 1, 2, true, activeFilter); // Revision first
if(item != null){
maxRetId = item.getId();
}
else{
item = dbHelper.getItemById(maxNewId + 1, 1, true, activeFilter); // Then learn new if no revision.
if(item != null){
maxNewId = item.getId();
}
}
if(item != null){
learnQueue.add(item);
}
else{
break;
}
}
}
int size = learnQueue.size();
if(size == 0){
/* No new items */
currentItem = null;
return 2;
}
else if(size == learningQueueSize){
currentItem = learnQueue.get(0);
return 0;
}
else{
/* Shuffling the queue */
if(shufflingCards){
Collections.shuffle(learnQueue);
}
currentItem = learnQueue.get(0);
return 1;
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "feedData" | "protected int feedData() {
if(initFeed){
initFeed = false;
boolean feedResult;
if(learnAhead){
feedResult = dbHelper.getListItems(-1, learningQueueSize, learnQueue, 3, activeFilter);
}
else{
feedResult = dbHelper.getListItems(-1, learningQueueSize, learnQueue, 4, activeFilter);
}
if(feedResult == true){
for(int i = 0; i < learnQueue.size(); i++){
Item qItem = learnQueue.get(i);
if(qItem.isScheduled()){
if(maxRetId < qItem.getId()){
maxRetId = qItem.getId();
}
}
else{
if(maxNewId < qItem.getId()){
maxNewId = qItem.getId();
}
}
}
/* Shuffling the queue */
if(shufflingCards){
Collections.shuffle(learnQueue);
}
<MASK>currentItem = learnQueue.get(0);</MASK>
return 0;
}
else{
currentItem = null;
return 2;
}
}
else{
Item item;
for(int i = learnQueue.size(); i < learningQueueSize; i++){
if(learnAhead){
/* Flag = 3 for randomly choose item from future */
item = dbHelper.getItemById(0, 3, true, activeFilter);
learnQueue.add(item);
}
else{
/* Search out the maxRetId and maxNew Id
* before queuing in order to achive consistence
*/
for(int j = 0; j < learnQueue.size(); j++){
Item qItem = learnQueue.get(j);
if(qItem.isScheduled()){
if(maxRetId < qItem.getId()){
maxRetId = qItem.getId();
}
}
else{
if(maxNewId < qItem.getId()){
maxNewId = qItem.getId();
}
}
}
item = dbHelper.getItemById(maxRetId + 1, 2, true, activeFilter); // Revision first
if(item != null){
maxRetId = item.getId();
}
else{
item = dbHelper.getItemById(maxNewId + 1, 1, true, activeFilter); // Then learn new if no revision.
if(item != null){
maxNewId = item.getId();
}
}
if(item != null){
learnQueue.add(item);
}
else{
break;
}
}
}
int size = learnQueue.size();
if(size == 0){
/* No new items */
currentItem = null;
return 2;
}
else if(size == learningQueueSize){
<MASK>currentItem = learnQueue.get(0);</MASK>
return 0;
}
else{
/* Shuffling the queue */
<MASK>currentItem = learnQueue.get(0);</MASK>
if(shufflingCards){
Collections.shuffle(learnQueue);
}
return 1;
}
}
}" |
Inversion-Mutation | megadiff | "public String[][] getUserNames() throws SQLException
{
String query="SELECT name, fullname from user_list;";
logger.debug("Running query: "+query);
stmt.executeQuery(query);
ResultSet rs = stmt.getResultSet();
ArrayList<String[]> als = new ArrayList<String[]>();
while(rs.next())
{
String[] row = new String[2];
row[0]=rs.getString(1);
row[1]=rs.getString(2);
als.add(row);
}
String[][] result = new String[1][1];
rs.close();
return als.toArray(result);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getUserNames" | "public String[][] getUserNames() throws SQLException
{
String query="SELECT name, fullname from user_list;";
logger.debug("Running query: "+query);
stmt.executeQuery(query);
ResultSet rs = stmt.getResultSet();
ArrayList<String[]> als = new ArrayList<String[]>();
<MASK>String[] row = new String[2];</MASK>
while(rs.next())
{
row[0]=rs.getString(1);
row[1]=rs.getString(2);
als.add(row);
}
String[][] result = new String[1][1];
rs.close();
return als.toArray(result);
}" |
Inversion-Mutation | megadiff | "public void turnOff(Player player, TurnOffReason reason) {
SPMPlayerSave spPlayerSave = spPlayersSave.remove(player);
spPlayerSave.restore(player);
player.setSleepingIgnored(false);
player.setNoDamageTicks(120);
if (isVanished(player)) {
turnOffVanish(player, reason);
}
for (Player vanished : spVanished.players()) {
vanish(player, vanished);
}
if (reason != TurnOffReason.Stop) {
EthilVan.getAccounts().removePseudoRole(player, "spm");
}
spPlayers.remove(player);
logConsole(ChatColor.GREEN + "SuperPig Mode desactivé pour "
+ player.getDisplayName());
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "turnOff" | "public void turnOff(Player player, TurnOffReason reason) {
<MASK>spPlayers.remove(player);</MASK>
SPMPlayerSave spPlayerSave = spPlayersSave.remove(player);
spPlayerSave.restore(player);
player.setSleepingIgnored(false);
player.setNoDamageTicks(120);
if (isVanished(player)) {
turnOffVanish(player, reason);
}
for (Player vanished : spVanished.players()) {
vanish(player, vanished);
}
if (reason != TurnOffReason.Stop) {
EthilVan.getAccounts().removePseudoRole(player, "spm");
}
logConsole(ChatColor.GREEN + "SuperPig Mode desactivé pour "
+ player.getDisplayName());
}" |
Inversion-Mutation | megadiff | "public void setUp() throws Exception {
super.setUp();
Locale.setDefault(Locale.US);
SimpleDateFormat dateFormat = new SimpleDateFormat(FitNesseContext.recentChangesDateFormat);
date = dateFormat.format(Clock.currentDate());
SimpleDateFormat rfcDateFormat = new SimpleDateFormat(FitNesseContext.rfcCompliantDateFormat);
rfcDate = rfcDateFormat.format(Clock.currentDate());
hostName = java.net.InetAddress.getLocalHost().getHostName();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setUp" | "public void setUp() throws Exception {
super.setUp();
SimpleDateFormat dateFormat = new SimpleDateFormat(FitNesseContext.recentChangesDateFormat);
date = dateFormat.format(Clock.currentDate());
SimpleDateFormat rfcDateFormat = new SimpleDateFormat(FitNesseContext.rfcCompliantDateFormat);
rfcDate = rfcDateFormat.format(Clock.currentDate());
hostName = java.net.InetAddress.getLocalHost().getHostName();
<MASK>Locale.setDefault(Locale.US);</MASK>
}" |
Inversion-Mutation | megadiff | "public static void fillInBreeding(IGenericCharacter character, Map<Object, Object> parameters) {
for (IGenericTrait background : character.getBackgrounds()) {
if (background.getType().getId().equals(DbCharacterModule.BACKGROUND_ID_BREEDING)) {
parameters.put(ICharacterReportConstants.BREEDING_VALUE, background.getCurrentValue());
return;
}
}
parameters.put(ICharacterReportConstants.BREEDING_VALUE, 0);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "fillInBreeding" | "public static void fillInBreeding(IGenericCharacter character, Map<Object, Object> parameters) {
for (IGenericTrait background : character.getBackgrounds()) {
if (background.getType().getId().equals(DbCharacterModule.BACKGROUND_ID_BREEDING)) {
parameters.put(ICharacterReportConstants.BREEDING_VALUE, background.getCurrentValue());
return;
}
<MASK>parameters.put(ICharacterReportConstants.BREEDING_VALUE, 0);</MASK>
}
}" |
Inversion-Mutation | megadiff | "protected void setSubscriber(Subscriber subscriber) {
super.setSubscriber(subscriber);
if (CVSUIPlugin.getPlugin().getPluginPreferences().getBoolean(ICVSUIConstants.PREF_CONSIDER_CONTENTS)) {
setSyncInfoFilter(contentComparison);
}
try {
ISynchronizeParticipantDescriptor descriptor = TeamUI.getSynchronizeManager().getParticipantDescriptor(CVSCompareSubscriber.ID);
setInitializationData(descriptor);
CVSCompareSubscriber s = (CVSCompareSubscriber)getSubscriber();
setSecondaryId(s.getId().getLocalName());
} catch (CoreException e) {
CVSUIPlugin.log(e);
}
CVSUIPlugin.getPlugin().getPluginPreferences().addPropertyChangeListener(this);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setSubscriber" | "protected void setSubscriber(Subscriber subscriber) {
super.setSubscriber(subscriber);
if (CVSUIPlugin.getPlugin().getPluginPreferences().getBoolean(ICVSUIConstants.PREF_CONSIDER_CONTENTS)) {
setSyncInfoFilter(contentComparison);
}
<MASK>CVSUIPlugin.getPlugin().getPluginPreferences().addPropertyChangeListener(this);</MASK>
try {
ISynchronizeParticipantDescriptor descriptor = TeamUI.getSynchronizeManager().getParticipantDescriptor(CVSCompareSubscriber.ID);
setInitializationData(descriptor);
CVSCompareSubscriber s = (CVSCompareSubscriber)getSubscriber();
setSecondaryId(s.getId().getLocalName());
} catch (CoreException e) {
CVSUIPlugin.log(e);
}
}" |
Inversion-Mutation | megadiff | "private void handleClosedSite(String string) {
if (!noDB) {
noDB = true;
DialogBox dialogBox = new DialogBox();
DOM.setElementAttribute(dialogBox.getElement(), "id", "closed_site");
HTML html = new HTML(string);
dialogBox.setWidget(html);
dialogBox.center();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handleClosedSite" | "private void handleClosedSite(String string) {
<MASK>noDB = true;</MASK>
if (!noDB) {
DialogBox dialogBox = new DialogBox();
DOM.setElementAttribute(dialogBox.getElement(), "id", "closed_site");
HTML html = new HTML(string);
dialogBox.setWidget(html);
dialogBox.center();
}
}" |
Inversion-Mutation | megadiff | "@Test
public void testMetricsCache() {
MetricsSystem ms = new MetricsSystemImpl("cache");
ms.start();
try {
String p1 = "root1";
String leafQueueName = "root1.leaf";
QueueMetrics p1Metrics =
QueueMetrics.forQueue(ms, p1, null, true, conf);
Queue parentQueue1 = make(stub(Queue.class).returning(p1Metrics).
from.getMetrics());
QueueMetrics metrics =
QueueMetrics.forQueue(ms, leafQueueName, parentQueue1, true, conf);
Assert.assertNotNull("QueueMetrics for A shoudn't be null", metrics);
// Re-register to check for cache hit, shouldn't blow up metrics-system...
// also, verify parent-metrics
QueueMetrics alterMetrics =
QueueMetrics.forQueue(ms, leafQueueName, parentQueue1, true, conf);
Assert.assertNotNull("QueueMetrics for alterMetrics shoudn't be null",
alterMetrics);
} finally {
ms.shutdown();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "testMetricsCache" | "@Test
public void testMetricsCache() {
MetricsSystem ms = new MetricsSystemImpl("cache");
try {
String p1 = "root1";
String leafQueueName = "root1.leaf";
<MASK>ms.start();</MASK>
QueueMetrics p1Metrics =
QueueMetrics.forQueue(ms, p1, null, true, conf);
Queue parentQueue1 = make(stub(Queue.class).returning(p1Metrics).
from.getMetrics());
QueueMetrics metrics =
QueueMetrics.forQueue(ms, leafQueueName, parentQueue1, true, conf);
Assert.assertNotNull("QueueMetrics for A shoudn't be null", metrics);
// Re-register to check for cache hit, shouldn't blow up metrics-system...
// also, verify parent-metrics
QueueMetrics alterMetrics =
QueueMetrics.forQueue(ms, leafQueueName, parentQueue1, true, conf);
Assert.assertNotNull("QueueMetrics for alterMetrics shoudn't be null",
alterMetrics);
} finally {
ms.shutdown();
}
}" |
Inversion-Mutation | megadiff | "public boolean act (float delta) {
if (!ran) {
ran = true;
run();
}
return true;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "act" | "public boolean act (float delta) {
if (!ran) {
<MASK>run();</MASK>
ran = true;
}
return true;
}" |
Inversion-Mutation | megadiff | "protected String convertViewIdIfNeed(FacesContext context) {
WebappConfig webappConfig = getWebappConfig(context);
ExternalContext externalContext = context.getExternalContext();
String viewId = context.getViewRoot().getViewId();
// PortletSupport
if (PortletUtil.isPortlet(context)) {
return viewId;
}
String urlPattern = getUrlPattern(webappConfig, context);
if (urlPattern != null && isExtensionMapping(urlPattern)) {
String defaultSuffix = externalContext
.getInitParameter(ViewHandler.DEFAULT_SUFFIX_PARAM_NAME);
String suffix = defaultSuffix != null ? defaultSuffix
: ViewHandler.DEFAULT_SUFFIX;
if (!viewId.endsWith(suffix)) {
int dot = viewId.lastIndexOf('.');
if (dot == -1) {
viewId = viewId + suffix;
} else {
viewId = viewId.substring(0, dot) + suffix;
}
}
}
return viewId;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "convertViewIdIfNeed" | "protected String convertViewIdIfNeed(FacesContext context) {
WebappConfig webappConfig = getWebappConfig(context);
ExternalContext externalContext = context.getExternalContext();
<MASK>String urlPattern = getUrlPattern(webappConfig, context);</MASK>
String viewId = context.getViewRoot().getViewId();
// PortletSupport
if (PortletUtil.isPortlet(context)) {
return viewId;
}
if (urlPattern != null && isExtensionMapping(urlPattern)) {
String defaultSuffix = externalContext
.getInitParameter(ViewHandler.DEFAULT_SUFFIX_PARAM_NAME);
String suffix = defaultSuffix != null ? defaultSuffix
: ViewHandler.DEFAULT_SUFFIX;
if (!viewId.endsWith(suffix)) {
int dot = viewId.lastIndexOf('.');
if (dot == -1) {
viewId = viewId + suffix;
} else {
viewId = viewId.substring(0, dot) + suffix;
}
}
}
return viewId;
}" |
Inversion-Mutation | megadiff | "@Override
public void onDestroy() {
synchronized(sSyncLock) {
alwaysLog("!!! EAS ExchangeService, onDestroy");
// Stop the sync manager thread and return
synchronized (sSyncLock) {
if (sServiceThread != null) {
sStop = true;
sServiceThread.interrupt();
}
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onDestroy" | "@Override
public void onDestroy() {
synchronized(sSyncLock) {
alwaysLog("!!! EAS ExchangeService, onDestroy");
// Stop the sync manager thread and return
synchronized (sSyncLock) {
<MASK>sStop = true;</MASK>
if (sServiceThread != null) {
sServiceThread.interrupt();
}
}
}
}" |
Inversion-Mutation | megadiff | "public PlayerManager(ChatCore instance) {
clean();
plugin = instance;
config = new File(plugin.getDataFolder(), "players.yml");
if (!config.exists()) {
getConfig().setDefaults(YamlConfiguration.loadConfiguration(plugin.getClass().getResourceAsStream("/defaults/players.yml")));
getConfig().options().copyDefaults(true);
saveConfig();
}
saveConfig();
persist = plugin.getConfig().getBoolean("plugin.persist_user_settings");
buildPlayerList();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "PlayerManager" | "public PlayerManager(ChatCore instance) {
clean();
plugin = instance;
<MASK>persist = plugin.getConfig().getBoolean("plugin.persist_user_settings");</MASK>
config = new File(plugin.getDataFolder(), "players.yml");
if (!config.exists()) {
getConfig().setDefaults(YamlConfiguration.loadConfiguration(plugin.getClass().getResourceAsStream("/defaults/players.yml")));
getConfig().options().copyDefaults(true);
saveConfig();
}
saveConfig();
buildPlayerList();
}" |
Inversion-Mutation | megadiff | "@Override
public void paintCollapsiblePanesBackground(JComponent c, Graphics g, Rectangle rect, int orientation, int state) {
if (!c.isOpaque()) {
return;
}
Boolean highContrast = UIManager.getBoolean("Theme.highContrast");
if (highContrast) {
super.paintCollapsiblePanesBackground(c, g, rect, orientation, state);
return;
}
Graphics2D g2d = (Graphics2D) g;
if (!(c.getBackground() instanceof UIResource)) {
JideSwingUtilities.fillGradient(g2d,
new Rectangle(rect.x, rect.y, rect.width, rect.height),
ColorUtils.getDerivedColor(c.getBackground(), 0.6f),
c.getBackground(),
orientation == SwingConstants.HORIZONTAL);
}
else {
JideSwingUtilities.fillGradient(g2d,
new Rectangle(rect.x, rect.y, rect.width, rect.height),
getCurrentTheme().getColor("CollapsiblePanes.backgroundLt"),
getCurrentTheme().getColor("CollapsiblePanes.backgroundDk"),
orientation == SwingConstants.HORIZONTAL);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "paintCollapsiblePanesBackground" | "@Override
public void paintCollapsiblePanesBackground(JComponent c, Graphics g, Rectangle rect, int orientation, int state) {
if (!c.isOpaque()) {
return;
}
Boolean highContrast = UIManager.getBoolean("Theme.highContrast");
if (highContrast) {
super.paintCollapsiblePanesBackground(c, g, rect, orientation, state);
return;
}
Graphics2D g2d = (Graphics2D) g;
if (!(c.getBackground() instanceof UIResource)) {
JideSwingUtilities.fillGradient(g2d,
new Rectangle(rect.x, rect.y, rect.width, rect.height),
<MASK>c.getBackground(),</MASK>
ColorUtils.getDerivedColor(<MASK>c.getBackground(),</MASK> 0.6f),
orientation == SwingConstants.HORIZONTAL);
}
else {
JideSwingUtilities.fillGradient(g2d,
new Rectangle(rect.x, rect.y, rect.width, rect.height),
getCurrentTheme().getColor("CollapsiblePanes.backgroundLt"),
getCurrentTheme().getColor("CollapsiblePanes.backgroundDk"),
orientation == SwingConstants.HORIZONTAL);
}
}" |
Inversion-Mutation | megadiff | "protected void undeployBeans(KernelController controller, KernelDeployment deployment)
{
Set<NamedAliasMetaData> aliases = deployment.getAliases();
if (aliases != null && aliases.isEmpty() == false)
{
for (NamedAliasMetaData alias : aliases)
controller.removeAlias(alias.getAliasValue());
}
super.undeployBeans(controller, deployment);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "undeployBeans" | "protected void undeployBeans(KernelController controller, KernelDeployment deployment)
{
<MASK>super.undeployBeans(controller, deployment);</MASK>
Set<NamedAliasMetaData> aliases = deployment.getAliases();
if (aliases != null && aliases.isEmpty() == false)
{
for (NamedAliasMetaData alias : aliases)
controller.removeAlias(alias.getAliasValue());
}
}" |
Inversion-Mutation | megadiff | "private static InputStream inflate(final InputStream in, final long size,
final ObjectId id) {
final Inflater inf = InflaterCache.get();
return new InflaterInputStream(in, inf) {
private long remaining = size;
@Override
public int read(byte[] b, int off, int cnt) throws IOException {
try {
int r = super.read(b, off, cnt);
if (r > 0)
remaining -= r;
return r;
} catch (ZipException badStream) {
throw new CorruptObjectException(id,
JGitText.get().corruptObjectBadStream);
}
}
@Override
public void close() throws IOException {
try {
if (remaining <= 0)
checkValidEndOfStream(in, inf, id, new byte[64]);
} finally {
InflaterCache.release(inf);
super.close();
}
}
};
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "inflate" | "private static InputStream inflate(final InputStream in, final long size,
final ObjectId id) {
final Inflater inf = InflaterCache.get();
return new InflaterInputStream(in, inf) {
private long remaining = size;
@Override
public int read(byte[] b, int off, int cnt) throws IOException {
try {
int r = super.read(b, off, cnt);
if (r > 0)
remaining -= r;
return r;
} catch (ZipException badStream) {
throw new CorruptObjectException(id,
JGitText.get().corruptObjectBadStream);
}
}
@Override
public void close() throws IOException {
try {
if (remaining <= 0)
checkValidEndOfStream(in, inf, id, new byte[64]);
<MASK>super.close();</MASK>
} finally {
InflaterCache.release(inf);
}
}
};
}" |
Inversion-Mutation | megadiff | "@Override
public void close() throws IOException {
try {
if (remaining <= 0)
checkValidEndOfStream(in, inf, id, new byte[64]);
} finally {
InflaterCache.release(inf);
super.close();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "close" | "@Override
public void close() throws IOException {
try {
if (remaining <= 0)
checkValidEndOfStream(in, inf, id, new byte[64]);
<MASK>super.close();</MASK>
} finally {
InflaterCache.release(inf);
}
}" |
Inversion-Mutation | megadiff | "protected ProgressMonitorDialog openProgress() {
progressDialog = new ProgressMonitorDialog(getShell());
progressDialog.setCancelable(true);
progressDialog.open();
return progressDialog;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "openProgress" | "protected ProgressMonitorDialog openProgress() {
progressDialog = new ProgressMonitorDialog(getShell());
<MASK>progressDialog.open();</MASK>
progressDialog.setCancelable(true);
return progressDialog;
}" |
Inversion-Mutation | megadiff | "@Override
public SqlScript createCleanScript(JdbcTemplate jdbcTemplate) {
final List<String> allDropStatements = new ArrayList<String>();
allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "SEQUENCE", ""));
allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "FUNCTION", ""));
allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "MATERIALIZED VIEW", ""));
allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "PACKAGE", ""));
allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "PROCEDURE", ""));
allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "SYNONYM", ""));
allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "VIEW", ""));
allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "TABLE", "CASCADE CONSTRAINTS PURGE"));
allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "TYPE", ""));
allDropStatements.addAll(generateDropStatementsForSpatialExtensions(jdbcTemplate));
List<SqlStatement> sqlStatements = new ArrayList<SqlStatement>();
int count = 0;
for (String dropStatement : allDropStatements) {
count++;
sqlStatements.add(new SqlStatement(count, dropStatement));
}
return new SqlScript(sqlStatements);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createCleanScript" | "@Override
public SqlScript createCleanScript(JdbcTemplate jdbcTemplate) {
final List<String> allDropStatements = new ArrayList<String>();
allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "SEQUENCE", ""));
allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "FUNCTION", ""));
allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "MATERIALIZED VIEW", ""));
allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "PACKAGE", ""));
allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "PROCEDURE", ""));
allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "SYNONYM", ""));
allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "TABLE", "CASCADE CONSTRAINTS PURGE"));
allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "TYPE", ""));
<MASK>allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "VIEW", ""));</MASK>
allDropStatements.addAll(generateDropStatementsForSpatialExtensions(jdbcTemplate));
List<SqlStatement> sqlStatements = new ArrayList<SqlStatement>();
int count = 0;
for (String dropStatement : allDropStatements) {
count++;
sqlStatements.add(new SqlStatement(count, dropStatement));
}
return new SqlScript(sqlStatements);
}" |
Inversion-Mutation | megadiff | "@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerInteract(PlayerInteractEvent event) {
if ((event.getAction() == Action.RIGHT_CLICK_BLOCK)
|| ((event.getAction() == Action.LEFT_CLICK_BLOCK))) {
BlockState state = event.getClickedBlock().getState();
Player player = event.getPlayer();
if ((state instanceof Sign)) {
Sign sign = (Sign) state;
if (sign.getLines()[0].equalsIgnoreCase("[ClickMe]")) {
if (has(event.getPlayer())) {
if (sign.getLines()[1].equalsIgnoreCase("console")) {
if (hasConsole(player))
getServer()
.dispatchCommand(
getServer().getConsoleSender(),
sign.getLines()[2].toString()
+ sign.getLines()[3]
.toString());
else
player.sendMessage("You don't have the required permissions for this...");
} else
getServer().dispatchCommand(
event.getPlayer(),
sign.getLines()[1].toString()
+ sign.getLines()[2].toString()
+ sign.getLines()[3].toString());
} else {
player.sendMessage("You don't have the required permissions for this...");
}
}
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onPlayerInteract" | "@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerInteract(PlayerInteractEvent event) {
if ((event.getAction() == Action.RIGHT_CLICK_BLOCK)
|| ((event.getAction() == Action.LEFT_CLICK_BLOCK))) {
BlockState state = event.getClickedBlock().getState();
Player player = event.getPlayer();
if ((state instanceof Sign)) {
Sign sign = (Sign) state;
if (sign.getLines()[0].equalsIgnoreCase("[ClickMe]")) {
if (has(event.getPlayer())) {
if (sign.getLines()[1].equalsIgnoreCase("console")) {
if (hasConsole(player))
getServer()
.dispatchCommand(
getServer().getConsoleSender(),
sign.getLines()[2].toString()
+ sign.getLines()[3]
.toString());
else
player.sendMessage("You don't have the required permissions for this...");
<MASK>}</MASK> else
getServer().dispatchCommand(
event.getPlayer(),
sign.getLines()[1].toString()
+ sign.getLines()[2].toString()
+ sign.getLines()[3].toString());
<MASK>}</MASK>
<MASK>}</MASK> else {
player.sendMessage("You don't have the required permissions for this...");
<MASK>}</MASK>
<MASK>}</MASK>
<MASK>}</MASK>
<MASK>}</MASK>" |
Inversion-Mutation | megadiff | "public void getDissemination(Context context, String PID, String bDefPID, String methodName,
Property[] userParms, Date asOfDateTime, HttpServletResponse response, HttpServletRequest request)
throws IOException, ServerException
{
ServletOutputStream out = null;
MIMETypedStream dissemination = null;
dissemination =
s_access.getDissemination(context, PID, bDefPID, methodName,
userParms, asOfDateTime);
out = response.getOutputStream();
if (dissemination != null)
{
// testing to see what's in request header that might be of interest
for (Enumeration e= request.getHeaderNames(); e.hasMoreElements();) {
String name = (String)e.nextElement();
Enumeration headerValues = request.getHeaders(name);
StringBuffer sb = new StringBuffer();
while (headerValues.hasMoreElements()) {
sb.append((String) headerValues.nextElement());
}
String value = sb.toString();
if (fedora.server.Debug.DEBUG) System.out.println("FEDORASERVLET REQUEST HEADER CONTAINED: "+name+" : "+value);
response.setHeader(name,value);
}
// Dissemination was successful;
// Return MIMETypedStream back to browser client
if (dissemination.MIMEType.equalsIgnoreCase("application/fedora-redirect"))
{
// A MIME type of application/fedora-redirect signals that the
// MIMETypedStream returned from the dissemination is a special
// Fedora-specific MIME type. In this case, the Fedora server will
// not proxy the datastream, but instead perform a simple redirect to
// the URL contained within the body of the MIMETypedStream. This
// special MIME type is used primarily for streaming media where it
// is more efficient to stream the data directly between the streaming
// server and the browser client rather than proxy it through the
// Fedora server.
BufferedReader br = new BufferedReader(
new InputStreamReader(dissemination.getStream()));
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = br.readLine()) != null)
{
sb.append(line);
}
response.sendRedirect(sb.toString());
} else
{
response.setContentType(dissemination.MIMEType);
Property[] headerArray = dissemination.header;
if(headerArray != null) {
for(int i=0; i<headerArray.length; i++) {
if(headerArray[i].name != null && !(headerArray[i].name.equalsIgnoreCase("content-type"))) {
response.addHeader(headerArray[i].name, headerArray[i].value);
if (fedora.server.Debug.DEBUG) System.out.println("THIS WAS ADDED TO FEDORASERVLET RESPONSE HEADER FROM ORIGINATING PROVIDER "+headerArray[i].name+" : "+headerArray[i].value);
}
}
}
long startTime = new Date().getTime();
int byteStream = 0;
InputStream dissemResult = dissemination.getStream();
byte[] buffer = new byte[255];
while ((byteStream = dissemResult.read(buffer)) != -1)
{
out.write(buffer, 0, byteStream);
}
buffer = null;
dissemResult.close();
dissemResult = null;
long stopTime = new Date().getTime();
long interval = stopTime - startTime;
logger.logFiner("[FedoraAccessServlet] Read InputStream "
+ interval + " milliseconds.");
}
} else
{
// Dissemination request failed; echo back request parameter.
String message = "[FedoraAccessServlet] No Dissemination Result "
+ " was returned.";
showURLParms(PID, bDefPID, methodName, asOfDateTime, userParms,
response, message);
logger.logInfo(message);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getDissemination" | "public void getDissemination(Context context, String PID, String bDefPID, String methodName,
Property[] userParms, Date asOfDateTime, HttpServletResponse response, HttpServletRequest request)
throws IOException, ServerException
{
ServletOutputStream out = null;
MIMETypedStream dissemination = null;
dissemination =
s_access.getDissemination(context, PID, bDefPID, methodName,
userParms, asOfDateTime);
if (dissemination != null)
{
// testing to see what's in request header that might be of interest
for (Enumeration e= request.getHeaderNames(); e.hasMoreElements();) {
String name = (String)e.nextElement();
Enumeration headerValues = request.getHeaders(name);
StringBuffer sb = new StringBuffer();
while (headerValues.hasMoreElements()) {
sb.append((String) headerValues.nextElement());
}
String value = sb.toString();
if (fedora.server.Debug.DEBUG) System.out.println("FEDORASERVLET REQUEST HEADER CONTAINED: "+name+" : "+value);
response.setHeader(name,value);
}
// Dissemination was successful;
// Return MIMETypedStream back to browser client
if (dissemination.MIMEType.equalsIgnoreCase("application/fedora-redirect"))
{
// A MIME type of application/fedora-redirect signals that the
// MIMETypedStream returned from the dissemination is a special
// Fedora-specific MIME type. In this case, the Fedora server will
// not proxy the datastream, but instead perform a simple redirect to
// the URL contained within the body of the MIMETypedStream. This
// special MIME type is used primarily for streaming media where it
// is more efficient to stream the data directly between the streaming
// server and the browser client rather than proxy it through the
// Fedora server.
BufferedReader br = new BufferedReader(
new InputStreamReader(dissemination.getStream()));
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = br.readLine()) != null)
{
sb.append(line);
}
response.sendRedirect(sb.toString());
} else
{
response.setContentType(dissemination.MIMEType);
Property[] headerArray = dissemination.header;
if(headerArray != null) {
for(int i=0; i<headerArray.length; i++) {
if(headerArray[i].name != null && !(headerArray[i].name.equalsIgnoreCase("content-type"))) {
response.addHeader(headerArray[i].name, headerArray[i].value);
if (fedora.server.Debug.DEBUG) System.out.println("THIS WAS ADDED TO FEDORASERVLET RESPONSE HEADER FROM ORIGINATING PROVIDER "+headerArray[i].name+" : "+headerArray[i].value);
}
}
}
<MASK>out = response.getOutputStream();</MASK>
long startTime = new Date().getTime();
int byteStream = 0;
InputStream dissemResult = dissemination.getStream();
byte[] buffer = new byte[255];
while ((byteStream = dissemResult.read(buffer)) != -1)
{
out.write(buffer, 0, byteStream);
}
buffer = null;
dissemResult.close();
dissemResult = null;
long stopTime = new Date().getTime();
long interval = stopTime - startTime;
logger.logFiner("[FedoraAccessServlet] Read InputStream "
+ interval + " milliseconds.");
}
} else
{
// Dissemination request failed; echo back request parameter.
String message = "[FedoraAccessServlet] No Dissemination Result "
+ " was returned.";
showURLParms(PID, bDefPID, methodName, asOfDateTime, userParms,
response, message);
logger.logInfo(message);
}
}" |
Inversion-Mutation | megadiff | "@Override
public void onAddImages(String model, String code, ScanRecord[] items) {
if (layout.getMembers().length != 0) {
layout.removeMember(tileGridLayout);
}
tileGridLayout = new VLayout();
tileGrid = new TileGrid();
tileGrid.setTileWidth(Constants.TILEGRID_ITEM_WIDTH);
tileGrid.setTileHeight(Constants.TILEGRID_ITEM_HEIGHT);
tileGrid.setHeight100();
tileGrid.setWidth100();
tileGrid.setCanDrag(true);
tileGrid.setCanAcceptDrop(true);
tileGrid.setShowAllRecords(true);
Menu menu = new Menu();
menu.setShowShadow(true);
menu.setShadowDepth(10);
MenuItem viewItem = new MenuItem(lang.menuView(), "icons/16/eye.png");
viewItem.setAttribute(ID_NAME, ID_VIEW);
viewItem.setEnableIfCondition(new MenuItemIfFunction() {
@Override
public boolean execute(Canvas target, Menu menu, MenuItem item) {
return tileGrid.getSelection() != null && tileGrid.getSelection().length == 1;
}
});
viewItem.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler() {
@Override
public void onClick(MenuItemClickEvent event) {
final String uuid = tileGrid.getSelection()[0].getAttribute(Constants.ATTR_PICTURE);
winModal = new Window();
// winModal.setWidth(1024);
// winModal.setHeight(768);
winModal.setWidth("95%");
winModal.setHeight("95%");
StringBuffer sb = new StringBuffer();
sb.append(lang.scan()).append(": ")
.append(tileGrid.getSelection()[0].getAttribute(Constants.ATTR_NAME));
winModal.setTitle(sb.toString());
winModal.setShowMinimizeButton(false);
winModal.setIsModal(true);
winModal.setShowModalMask(true);
winModal.centerInPage();
winModal.addCloseClickHandler(new CloseClickHandler() {
@Override
public void onCloseClick(CloseClientEvent event) {
escShortCut();
}
});
HTMLPane viewerPane = new HTMLPane();
viewerPane.setPadding(15);
// viewerPane.setContentsURL("http://editor.mzk.cz/meditor/viewer/viewer.html?rft_id=" + uuid);
viewerPane.setContentsURL("http://editor.mzk.cz/meditor/viewer/viewer.html");
viewerPane.setContentsURLParams(new java.util.HashMap<String, String>() {
{
put("rft_id", uuid);
}
});
viewerPane.setContentsType(ContentsType.PAGE);
winModal.addItem(viewerPane);
winModal.show();
}
});
MenuItem selectAllItem = new MenuItem(lang.menuSelectAll(), "icons/16/document_plain_new.png");
selectAllItem.setAttribute(ID_NAME, ID_SEL_ALL);
MenuItem deselectAllItem =
new MenuItem(lang.menuDeselectAll(), "icons/16/document_plain_new_Disabled.png");
deselectAllItem.setAttribute(ID_NAME, ID_SEL_NONE);
MenuItem invertSelectionItem = new MenuItem(lang.menuInvertSelection(), "icons/16/invert.png");
invertSelectionItem.setAttribute(ID_NAME, ID_SEL_INV);
MenuItemSeparator separator = new MenuItemSeparator();
separator.setAttribute(ID_NAME, ID_SEPARATOR);
MenuItem copyItem = new MenuItem(lang.menuCopySelected(), "icons/16/copy.png");
copyItem.setAttribute(ID_NAME, ID_COPY);
copyItem.setEnableIfCondition(new MenuItemIfFunction() {
@Override
public boolean execute(Canvas target, Menu menu, MenuItem item) {
return tileGrid.getSelection().length > 0;
}
});
MenuItem pasteItem = new MenuItem(lang.menuPaste(), "icons/16/paste.png");
pasteItem.setAttribute(ID_NAME, ID_PASTE);
pasteItem.setEnableIfCondition(new MenuItemIfFunction() {
@Override
public boolean execute(Canvas target, Menu menu, MenuItem item) {
return CreateStructureView.this.clipboard != null
&& CreateStructureView.this.clipboard.length > 0;
}
});
MenuItem removeSelectedItem = new MenuItem(lang.menuRemoveSelected(), "icons/16/close.png");
removeSelectedItem.setAttribute(ID_NAME, ID_DELETE);
removeSelectedItem.setEnableIfCondition(new MenuItemIfFunction() {
@Override
public boolean execute(Canvas target, Menu menu, MenuItem item) {
return tileGrid.getSelection().length > 0;
}
});
menu.setItems(viewItem,
separator,
selectAllItem,
deselectAllItem,
invertSelectionItem,
separator,
copyItem,
pasteItem,
removeSelectedItem);
tileGrid.setContextMenu(menu);
tileGrid.setDropTypes(model);
tileGrid.setDragType(model);
tileGrid.setDragAppearance(DragAppearance.TRACKER);
tileGrid.addRecordDoubleClickHandler(new RecordDoubleClickHandler() {
@Override
public void onRecordDoubleClick(final RecordDoubleClickEvent event) {
if (event.getRecord() != null) {
try {
final ModalWindow mw = new ModalWindow(layout);
mw.setLoadingIcon("loadingAnimation.gif");
mw.show(true);
StringBuffer sb = new StringBuffer();
sb.append(Constants.SERVLET_IMAGES_PREFIX).append(Constants.SERVLET_SCANS_PREFIX)
.append('/').append(event.getRecord().getAttribute(Constants.ATTR_PICTURE))
.append("?" + Constants.URL_PARAM_FULL + "=yes");
final Image full = new Image(sb.toString());
full.setHeight(Constants.IMAGE_FULL_WIDTH + "px");
full.addLoadHandler(new LoadHandler() {
@Override
public void onLoad(LoadEvent event) {
mw.hide();
getPopupPanel().setVisible(true);
getPopupPanel().center();
}
});
getPopupPanel().setWidget(full);
getPopupPanel().addCloseHandler(new CloseHandler<PopupPanel>() {
@Override
public void onClose(CloseEvent<PopupPanel> event) {
mw.hide();
getPopupPanel().setWidget(null);
}
});
getPopupPanel().center();
getPopupPanel().setVisible(false);
} catch (Throwable t) {
// TODO: handle
}
}
}
});
tileGrid.addRecordClickHandler(new RecordClickHandler() {
@Override
public void onRecordClick(RecordClickEvent event) {
if (detailPanelShown) {
showDetail(event.getRecord().getAttribute(Constants.ATTR_PICTURE), pageDetailHeight);
}
}
});
tileGrid.addSelectionChangedHandler(new SelectionChangedHandler() {
@Override
public void onSelectionChanged(SelectionChangedEvent event) {
if (tileGrid.getSelection() != null && tileGrid.getSelection().length == 1) {
specialPageItem.enable();
} else {
specialPageItem.disable();
}
}
});
final DetailViewerField pictureField = new DetailViewerField(Constants.ATTR_PICTURE);
pictureField.setType("image");
pictureField.setImageURLPrefix(Constants.SERVLET_SCANS_PREFIX + '/');
pictureField.setImageWidth(Constants.IMAGE_THUMBNAIL_WIDTH);
pictureField.setImageHeight(Constants.IMAGE_THUMBNAIL_HEIGHT);
DetailViewerField nameField = new DetailViewerField(Constants.ATTR_NAME);
nameField.setDetailFormatter(new DetailFormatter() {
@Override
public String format(Object value, Record record, DetailViewerField field) {
StringBuffer sb = new StringBuffer();
sb.append(lang.scan()).append(": ").append(value);
return sb.toString();
}
});
tileGrid.setFields(pictureField, nameField);
tileGrid.setData(items);
getUiHandlers().onAddImages(tileGrid, menu);
ToolStrip toolStrip = new ToolStrip();
toolStrip.setWidth100();
ToolStripMenuButton menuButton = getToolStripMenuButton();
toolStrip.addMenuButton(menuButton);
specialPageItem = new SelectItem();
specialPageItem.setShowTitle(false);
specialPageItem.setWidth(100);
specialPageItem.setTitle(lang.specialType());
LinkedHashMap<String, String> valueMap =
new LinkedHashMap<String, String>(Constants.SPECIAL_PAGE_TYPE_MAP);
specialPageItem.setValueMap(valueMap);
specialPageItem.addChangedHandler(new ChangedHandler() {
@Override
public void onChanged(ChangedEvent event) {
tileGrid.getSelectedRecord().setAttribute(Constants.ATTR_NAME, event.getValue());
}
});
toolStrip.addFormItem(specialPageItem);
toolStrip.addResizer();
SelectItem zoomItems = new SelectItem("pageDetail", lang.detailSize());
zoomItems.setName("selectName");
zoomItems.setShowTitle(true);
zoomItems.setWrapTitle(false);
zoomItems.setWidth(70);
zoomItems.setValueMap("75%", "100%", "125%", "150%");
zoomItems.addChangedHandler(new ChangedHandler() {
@Override
public void onChanged(ChangedEvent event) {
String percent = (String) event.getValue();
if ("75%".equals(percent)) {
pageDetailHeight = Constants.PAGE_PREVIEW_HEIGHT_SMALL;
} else if ("100%".equals(percent)) {
pageDetailHeight = Constants.PAGE_PREVIEW_HEIGHT_NORMAL;
} else if ("125%".equals(percent)) {
pageDetailHeight = Constants.PAGE_PREVIEW_HEIGHT_LARGE;
} else if ("150%".equals(percent)) {
pageDetailHeight = Constants.PAGE_PREVIEW_HEIGHT_XLARGE;
}
showDetail(pageDetailHeight);
}
});
zoomItems.setDefaultValue("100%");
toolStrip.addFormItem(zoomItems);
ToolStripButton zoomButton = new ToolStripButton();
zoomButton.setIcon("silk/zoom.png");
zoomButton.setTitle(lang.pageDetail());
zoomButton.setActionType(SelectionType.CHECKBOX);
zoomButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
if (detailPanel == null) {
detailPanel = new VLayout();
detailPanel.setPadding(5);
detailPanel.setAnimateMembers(true);
detailPanel.setAnimateHideTime(200);
detailPanel.setAnimateShowTime(200);
tileGridLayout.addMember(detailPanel);
detailPanelShown = true;
showDetail(pageDetailHeight);
} else if (detailPanelShown) {
detailPanelShown = false;
tileGridLayout.removeMember(detailPanel);
} else {
tileGridLayout.addMember(detailPanel);
detailPanelShown = true;
}
}
});
toolStrip.addButton(zoomButton);
ToolStripButton nextButton = new ToolStripButton();
nextButton.setIcon("silk/forward_green.png");
nextButton.setTitle("Next step");
toolStrip.addButton(nextButton);
tileGridLayout.addMember(toolStrip);
tileGridLayout.addMember(tileGrid);
layout.addMember(tileGridLayout);
specialPageItem.disable();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onAddImages" | "@Override
public void onAddImages(String model, String code, ScanRecord[] items) {
if (layout.getMembers().length != 0) {
layout.removeMember(tileGridLayout);
}
tileGridLayout = new VLayout();
tileGrid = new TileGrid();
tileGrid.setTileWidth(Constants.TILEGRID_ITEM_WIDTH);
tileGrid.setTileHeight(Constants.TILEGRID_ITEM_HEIGHT);
tileGrid.setHeight100();
tileGrid.setWidth100();
tileGrid.setCanDrag(true);
tileGrid.setCanAcceptDrop(true);
tileGrid.setShowAllRecords(true);
Menu menu = new Menu();
menu.setShowShadow(true);
menu.setShadowDepth(10);
MenuItem viewItem = new MenuItem(lang.menuView(), "icons/16/eye.png");
viewItem.setAttribute(ID_NAME, ID_VIEW);
viewItem.setEnableIfCondition(new MenuItemIfFunction() {
@Override
public boolean execute(Canvas target, Menu menu, MenuItem item) {
return tileGrid.getSelection() != null && tileGrid.getSelection().length == 1;
}
});
viewItem.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler() {
@Override
public void onClick(MenuItemClickEvent event) {
final String uuid = tileGrid.getSelection()[0].getAttribute(Constants.ATTR_PICTURE);
winModal = new Window();
// winModal.setWidth(1024);
// winModal.setHeight(768);
winModal.setWidth("95%");
winModal.setHeight("95%");
StringBuffer sb = new StringBuffer();
sb.append(lang.scan()).append(": ")
.append(tileGrid.getSelection()[0].getAttribute(Constants.ATTR_NAME));
winModal.setTitle(sb.toString());
winModal.setShowMinimizeButton(false);
winModal.setIsModal(true);
winModal.setShowModalMask(true);
winModal.centerInPage();
winModal.addCloseClickHandler(new CloseClickHandler() {
@Override
public void onCloseClick(CloseClientEvent event) {
escShortCut();
}
});
HTMLPane viewerPane = new HTMLPane();
viewerPane.setPadding(15);
// viewerPane.setContentsURL("http://editor.mzk.cz/meditor/viewer/viewer.html?rft_id=" + uuid);
viewerPane.setContentsURL("http://editor.mzk.cz/meditor/viewer/viewer.html");
viewerPane.setContentsURLParams(new java.util.HashMap<String, String>() {
{
put("rft_id", uuid);
}
});
viewerPane.setContentsType(ContentsType.PAGE);
winModal.addItem(viewerPane);
winModal.show();
}
});
MenuItem selectAllItem = new MenuItem(lang.menuSelectAll(), "icons/16/document_plain_new.png");
selectAllItem.setAttribute(ID_NAME, ID_SEL_ALL);
MenuItem deselectAllItem =
new MenuItem(lang.menuDeselectAll(), "icons/16/document_plain_new_Disabled.png");
deselectAllItem.setAttribute(ID_NAME, ID_SEL_NONE);
MenuItem invertSelectionItem = new MenuItem(lang.menuInvertSelection(), "icons/16/invert.png");
invertSelectionItem.setAttribute(ID_NAME, ID_SEL_INV);
MenuItemSeparator separator = new MenuItemSeparator();
separator.setAttribute(ID_NAME, ID_SEPARATOR);
MenuItem copyItem = new MenuItem(lang.menuCopySelected(), "icons/16/copy.png");
copyItem.setAttribute(ID_NAME, ID_COPY);
copyItem.setEnableIfCondition(new MenuItemIfFunction() {
@Override
public boolean execute(Canvas target, Menu menu, MenuItem item) {
return tileGrid.getSelection().length > 0;
}
});
MenuItem pasteItem = new MenuItem(lang.menuPaste(), "icons/16/paste.png");
pasteItem.setAttribute(ID_NAME, ID_PASTE);
pasteItem.setEnableIfCondition(new MenuItemIfFunction() {
@Override
public boolean execute(Canvas target, Menu menu, MenuItem item) {
return CreateStructureView.this.clipboard != null
&& CreateStructureView.this.clipboard.length > 0;
}
});
MenuItem removeSelectedItem = new MenuItem(lang.menuRemoveSelected(), "icons/16/close.png");
removeSelectedItem.setAttribute(ID_NAME, ID_DELETE);
removeSelectedItem.setEnableIfCondition(new MenuItemIfFunction() {
@Override
public boolean execute(Canvas target, Menu menu, MenuItem item) {
return tileGrid.getSelection().length > 0;
}
});
menu.setItems(viewItem,
separator,
selectAllItem,
deselectAllItem,
invertSelectionItem,
separator,
copyItem,
pasteItem,
removeSelectedItem);
tileGrid.setContextMenu(menu);
tileGrid.setDropTypes(model);
tileGrid.setDragType(model);
tileGrid.setDragAppearance(DragAppearance.TRACKER);
tileGrid.addRecordDoubleClickHandler(new RecordDoubleClickHandler() {
@Override
public void onRecordDoubleClick(final RecordDoubleClickEvent event) {
if (event.getRecord() != null) {
try {
final ModalWindow mw = new ModalWindow(layout);
mw.setLoadingIcon("loadingAnimation.gif");
mw.show(true);
StringBuffer sb = new StringBuffer();
sb.append(Constants.SERVLET_IMAGES_PREFIX).append(Constants.SERVLET_SCANS_PREFIX)
.append('/').append(event.getRecord().getAttribute(Constants.ATTR_PICTURE))
.append("?" + Constants.URL_PARAM_FULL + "=yes");
final Image full = new Image(sb.toString());
full.setHeight(Constants.IMAGE_FULL_WIDTH + "px");
full.addLoadHandler(new LoadHandler() {
@Override
public void onLoad(LoadEvent event) {
mw.hide();
getPopupPanel().setVisible(true);
getPopupPanel().center();
}
});
getPopupPanel().setWidget(full);
getPopupPanel().addCloseHandler(new CloseHandler<PopupPanel>() {
@Override
public void onClose(CloseEvent<PopupPanel> event) {
mw.hide();
getPopupPanel().setWidget(null);
}
});
getPopupPanel().center();
getPopupPanel().setVisible(false);
} catch (Throwable t) {
// TODO: handle
}
}
}
});
tileGrid.addRecordClickHandler(new RecordClickHandler() {
@Override
public void onRecordClick(RecordClickEvent event) {
if (detailPanelShown) {
showDetail(event.getRecord().getAttribute(Constants.ATTR_PICTURE), pageDetailHeight);
}
}
});
tileGrid.addSelectionChangedHandler(new SelectionChangedHandler() {
@Override
public void onSelectionChanged(SelectionChangedEvent event) {
if (tileGrid.getSelection() != null && tileGrid.getSelection().length == 1) {
specialPageItem.enable();
} else {
<MASK>specialPageItem.disable();</MASK>
}
}
});
final DetailViewerField pictureField = new DetailViewerField(Constants.ATTR_PICTURE);
pictureField.setType("image");
pictureField.setImageURLPrefix(Constants.SERVLET_SCANS_PREFIX + '/');
pictureField.setImageWidth(Constants.IMAGE_THUMBNAIL_WIDTH);
pictureField.setImageHeight(Constants.IMAGE_THUMBNAIL_HEIGHT);
DetailViewerField nameField = new DetailViewerField(Constants.ATTR_NAME);
nameField.setDetailFormatter(new DetailFormatter() {
@Override
public String format(Object value, Record record, DetailViewerField field) {
StringBuffer sb = new StringBuffer();
sb.append(lang.scan()).append(": ").append(value);
return sb.toString();
}
});
tileGrid.setFields(pictureField, nameField);
tileGrid.setData(items);
getUiHandlers().onAddImages(tileGrid, menu);
ToolStrip toolStrip = new ToolStrip();
toolStrip.setWidth100();
ToolStripMenuButton menuButton = getToolStripMenuButton();
toolStrip.addMenuButton(menuButton);
specialPageItem = new SelectItem();
specialPageItem.setShowTitle(false);
specialPageItem.setWidth(100);
specialPageItem.setTitle(lang.specialType());
<MASK>specialPageItem.disable();</MASK>
LinkedHashMap<String, String> valueMap =
new LinkedHashMap<String, String>(Constants.SPECIAL_PAGE_TYPE_MAP);
specialPageItem.setValueMap(valueMap);
specialPageItem.addChangedHandler(new ChangedHandler() {
@Override
public void onChanged(ChangedEvent event) {
tileGrid.getSelectedRecord().setAttribute(Constants.ATTR_NAME, event.getValue());
}
});
toolStrip.addFormItem(specialPageItem);
toolStrip.addResizer();
SelectItem zoomItems = new SelectItem("pageDetail", lang.detailSize());
zoomItems.setName("selectName");
zoomItems.setShowTitle(true);
zoomItems.setWrapTitle(false);
zoomItems.setWidth(70);
zoomItems.setValueMap("75%", "100%", "125%", "150%");
zoomItems.addChangedHandler(new ChangedHandler() {
@Override
public void onChanged(ChangedEvent event) {
String percent = (String) event.getValue();
if ("75%".equals(percent)) {
pageDetailHeight = Constants.PAGE_PREVIEW_HEIGHT_SMALL;
} else if ("100%".equals(percent)) {
pageDetailHeight = Constants.PAGE_PREVIEW_HEIGHT_NORMAL;
} else if ("125%".equals(percent)) {
pageDetailHeight = Constants.PAGE_PREVIEW_HEIGHT_LARGE;
} else if ("150%".equals(percent)) {
pageDetailHeight = Constants.PAGE_PREVIEW_HEIGHT_XLARGE;
}
showDetail(pageDetailHeight);
}
});
zoomItems.setDefaultValue("100%");
toolStrip.addFormItem(zoomItems);
ToolStripButton zoomButton = new ToolStripButton();
zoomButton.setIcon("silk/zoom.png");
zoomButton.setTitle(lang.pageDetail());
zoomButton.setActionType(SelectionType.CHECKBOX);
zoomButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
if (detailPanel == null) {
detailPanel = new VLayout();
detailPanel.setPadding(5);
detailPanel.setAnimateMembers(true);
detailPanel.setAnimateHideTime(200);
detailPanel.setAnimateShowTime(200);
tileGridLayout.addMember(detailPanel);
detailPanelShown = true;
showDetail(pageDetailHeight);
} else if (detailPanelShown) {
detailPanelShown = false;
tileGridLayout.removeMember(detailPanel);
} else {
tileGridLayout.addMember(detailPanel);
detailPanelShown = true;
}
}
});
toolStrip.addButton(zoomButton);
ToolStripButton nextButton = new ToolStripButton();
nextButton.setIcon("silk/forward_green.png");
nextButton.setTitle("Next step");
toolStrip.addButton(nextButton);
tileGridLayout.addMember(toolStrip);
tileGridLayout.addMember(tileGrid);
layout.addMember(tileGridLayout);
}" |
Inversion-Mutation | megadiff | "@Override
public void onStep(Actor actor) {
if(actor instanceof Player)
dropFlag((Player)actor);
actor.teleport(getDestination());
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onStep" | "@Override
public void onStep(Actor actor) {
<MASK>actor.teleport(getDestination());</MASK>
if(actor instanceof Player)
dropFlag((Player)actor);
}" |
Inversion-Mutation | megadiff | "public static StringBuilder buildMethodName(StringBuilder buf, Types types, ExecutableElement e) {
// use the full parameter list as a part of ID to handle overloading
buf.append(e.getSimpleName()).append('(');
boolean first=true;
List<? extends VariableElement> parameters = safeGetParameters(e);
for (VariableElement v : parameters) {
if(first) first=false;
else buf.append(',');
buf.append(types.erasure(v.asType()));
}
return buf.append(')');
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "buildMethodName" | "public static StringBuilder buildMethodName(StringBuilder buf, Types types, ExecutableElement e) {
// use the full parameter list as a part of ID to handle overloading
buf.append(e.getSimpleName()).append('(');
boolean first=true;
List<? extends VariableElement> parameters = safeGetParameters(e);
for (VariableElement v : parameters) {
<MASK>buf.append(types.erasure(v.asType()));</MASK>
if(first) first=false;
else buf.append(',');
}
return buf.append(')');
}" |
Inversion-Mutation | megadiff | "public void startGame(int numPlayers , int numDecks){
deckList = new ArrayList<Deck>();
playerList = new ArrayList<Player>();
for(int i = 0; i < numDecks; i ++){
Deck d = new Deck();
d.shuffle();
deckList.add(d);
}
for(int i = 0; i < numPlayers; i ++){
playerList.add(new Player("" + i, STARTINGCASH));
}
for(int i = 0; i < numPlayers; i ++){
ArrayList<Hand> handList = playerList.get(i).getHands();
for(int j = 0; j < handList.size(); j ++){
currHand = handList.get(j);
if(deckList.get(0).getNumCards() <= 0)
deckList.remove(0);
Card c = deckList.get(0).draw();
c.faceDown();
currHand.addCard(c);
currHand.addCard(deckList.get(0).draw());
}
}
currPlayerIndex = 0;
currPlayer = playerList.get(0);
currHandIndex = 0;
currHand = currPlayer.getHands().get(0);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "startGame" | "public void startGame(int numPlayers , int numDecks){
deckList = new ArrayList<Deck>();
playerList = new ArrayList<Player>();
for(int i = 0; i < numDecks; i ++){
Deck d = new Deck();
d.shuffle();
deckList.add(d);
}
for(int i = 0; i < numPlayers; i ++){
playerList.add(new Player("" + i, STARTINGCASH));
}
for(int i = 0; i < numPlayers; i ++){
ArrayList<Hand> handList = playerList.get(i).getHands();
for(int j = 0; j < handList.size(); j ++){
currHand = handList.get(j);
if(deckList.get(0).getNumCards() <= 0)
deckList.remove(0);
<MASK>currHand.addCard(deckList.get(0).draw());</MASK>
Card c = deckList.get(0).draw();
c.faceDown();
currHand.addCard(c);
}
}
currPlayerIndex = 0;
currPlayer = playerList.get(0);
currHandIndex = 0;
currHand = currPlayer.getHands().get(0);
}" |
Inversion-Mutation | megadiff | "protected void buildContentPanel() {
DefaultListSelectionModel selectionModel = new DefaultListSelectionModel();
model = new TodoListModel(selectionModel);
lstPrimitives = new JList(model);
lstPrimitives.setSelectionModel(selectionModel);
lstPrimitives.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
lstPrimitives.setCellRenderer(new OsmPrimitivRenderer());
lstPrimitives.setTransferHandler(null);
// the select action
SelectAction actSelect;
final SideButton selectButton = new SideButton(actSelect = new SelectAction(model));
lstPrimitives.getSelectionModel().addListSelectionListener(actSelect);
// the add button
final SideButton addButton = new SideButton(actAdd = new AddAction(model));
// the pass button
PassAction actPass;
final SideButton passButton = new SideButton(actPass = new PassAction(model));
lstPrimitives.getSelectionModel().addListSelectionListener(actPass);
Main.registerActionShortcut(actPass, Shortcut.registerShortcut("subwindow:todo:pass",
tr("Pass over element without marking it"), KeyEvent.VK_OPEN_BRACKET, Shortcut.DIRECT));
// the mark button
MarkAction actMark;
final SideButton markButton = new SideButton(actMark = new MarkAction(model));
lstPrimitives.getSelectionModel().addListSelectionListener(actMark);
Main.registerActionShortcut(actMark, Shortcut.registerShortcut("subwindow:todo:mark",
tr("Mark element done"), KeyEvent.VK_CLOSE_BRACKET, Shortcut.DIRECT));
createLayout(lstPrimitives, true, Arrays.asList(new SideButton[] {
selectButton, addButton, passButton, markButton
}));
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "buildContentPanel" | "protected void buildContentPanel() {
DefaultListSelectionModel selectionModel = new DefaultListSelectionModel();
model = new TodoListModel(selectionModel);
lstPrimitives = new JList(model);
<MASK>lstPrimitives.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);</MASK>
lstPrimitives.setSelectionModel(selectionModel);
lstPrimitives.setCellRenderer(new OsmPrimitivRenderer());
lstPrimitives.setTransferHandler(null);
// the select action
SelectAction actSelect;
final SideButton selectButton = new SideButton(actSelect = new SelectAction(model));
lstPrimitives.getSelectionModel().addListSelectionListener(actSelect);
// the add button
final SideButton addButton = new SideButton(actAdd = new AddAction(model));
// the pass button
PassAction actPass;
final SideButton passButton = new SideButton(actPass = new PassAction(model));
lstPrimitives.getSelectionModel().addListSelectionListener(actPass);
Main.registerActionShortcut(actPass, Shortcut.registerShortcut("subwindow:todo:pass",
tr("Pass over element without marking it"), KeyEvent.VK_OPEN_BRACKET, Shortcut.DIRECT));
// the mark button
MarkAction actMark;
final SideButton markButton = new SideButton(actMark = new MarkAction(model));
lstPrimitives.getSelectionModel().addListSelectionListener(actMark);
Main.registerActionShortcut(actMark, Shortcut.registerShortcut("subwindow:todo:mark",
tr("Mark element done"), KeyEvent.VK_CLOSE_BRACKET, Shortcut.DIRECT));
createLayout(lstPrimitives, true, Arrays.asList(new SideButton[] {
selectButton, addButton, passButton, markButton
}));
}" |
Inversion-Mutation | megadiff | "private void resetInternal() {
if (colorMap!=null) colorMap.clear();
if (xyGraph!=null) {
try {
for (Axis axis : xyGraph.getAxisList()) axis.setRange(0,100);
clearTraces();
} catch (Throwable e) {
logger.error("Cannot remove plots!", e);
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "resetInternal" | "private void resetInternal() {
if (colorMap!=null) colorMap.clear();
if (xyGraph!=null) {
try {
<MASK>clearTraces();</MASK>
for (Axis axis : xyGraph.getAxisList()) axis.setRange(0,100);
} catch (Throwable e) {
logger.error("Cannot remove plots!", e);
}
}
}" |
Inversion-Mutation | megadiff | "private Boolean CheckDB()
{
try
{
rhybuddCache = this.openOrCreateDatabase("rhybuddCache", MODE_PRIVATE, null);
dbResults = rhybuddCache.query("events",new String[]{"EVID","Count","lastTime","device","summary","eventState","firstTime","severity"},null, null, null, null, null);
}
catch(Exception e)
{
return false;
}
if(dbResults.getCount() != 0)
{
EventCount = dbResults.getCount();
return true;
}
else
{
rhybuddCache.close();
dbResults.close();
return false;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "CheckDB" | "private Boolean CheckDB()
{
<MASK>rhybuddCache = this.openOrCreateDatabase("rhybuddCache", MODE_PRIVATE, null);</MASK>
try
{
dbResults = rhybuddCache.query("events",new String[]{"EVID","Count","lastTime","device","summary","eventState","firstTime","severity"},null, null, null, null, null);
}
catch(Exception e)
{
return false;
}
if(dbResults.getCount() != 0)
{
EventCount = dbResults.getCount();
return true;
}
else
{
rhybuddCache.close();
dbResults.close();
return false;
}
}" |
Inversion-Mutation | megadiff | "public void bootPlayer (ClientObject caller, int tableId, int position,
TableService.InvocationListener listener)
throws InvocationException
{
BodyObject booter = (BodyObject) caller;
Table table = _tables.get(tableId);
if (table == null) {
throw new InvocationException(NO_SUCH_TABLE);
} else if (position == 0 || booter.getOid() != table.bodyOids[0]) {
// Must be head of the table, and can't self-boot
throw new InvocationException(INVALID_TABLE_POSITION);
} else if ( ! _allowBooting) {
throw new InvocationException(INTERNAL_ERROR);
}
// Remember to keep him banned
table.addBannedUser(table.players[position]);
// Remove the player from the table
if (notePlayerRemoved(table.bodyOids[position]) == null) {
log.warning("No body to table mapping to clear? [position=" + position +
", table=" + table + "].");
}
table.clearPlayerPos(position);
_tlobj.updateTables(table);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "bootPlayer" | "public void bootPlayer (ClientObject caller, int tableId, int position,
TableService.InvocationListener listener)
throws InvocationException
{
BodyObject booter = (BodyObject) caller;
Table table = _tables.get(tableId);
if (table == null) {
throw new InvocationException(NO_SUCH_TABLE);
} else if (position == 0 || booter.getOid() != table.bodyOids[0]) {
// Must be head of the table, and can't self-boot
throw new InvocationException(INVALID_TABLE_POSITION);
} else if ( ! _allowBooting) {
throw new InvocationException(INTERNAL_ERROR);
}
// Remember to keep him banned
table.addBannedUser(table.players[position]);
// Remove the player from the table
<MASK>table.clearPlayerPos(position);</MASK>
if (notePlayerRemoved(table.bodyOids[position]) == null) {
log.warning("No body to table mapping to clear? [position=" + position +
", table=" + table + "].");
}
_tlobj.updateTables(table);
}" |
Inversion-Mutation | megadiff | "private static AbstractValueType mapNumericType(SPSSVariable variable) {
switch(getSpssNumericDataType(variable)) {
case COMMA: // comma
case DOLLAR: // dollar
case DOT: // dot
case FIXED: // fixed format (default)
case SCIENTIFIC: // scientific notation
return variable.getDecimals() > 0 ? DecimalType.get() : IntegerType.get();
case ADATE: // Date in mm/dd/yy or mm/dd/yyyy
case EDATE: // Date in dd.mm.yy or dd.mm.yyyy
case SDATE: // Date in yyyy/mm/dd or yy/mm/dd (?)
return DateType.get();
case DATETIME: // DateTime in dd-mmm-yyyy hh:mm, dd-mmm-yyyy hh:mm:ss or dd-mmm-yyyy hh:mm:ss.ss
return DateTimeType.get();
case DATE: // Date dd-mmm-yyyy or dd-mmm-yy
case TIME: // Time in hh:mm, hh:mm:ss or hh:mm:ss.ss
case JDATE: // Date in yyyyddd or yyddd
case DTIME: // DateTime in ddd:hh:mm, ddd:hh:mm:ss or ddd:hh:mm:ss.ss
case WEEK_DAY: // Date as day of the week, full name or 3-letter
case MONTH: // Date 3-letter month
case MONTH_YEAR: // Date in mmm yyyy or mmm yy
case QUARTERLY_YEAR: // Date in q Q yyyy or q Q yy
case WEEK_YEAR: // Date in wk WK yyyy or wk WK yy
case CUSTOM_CURRENCY_A: // Custom currency A
case CUSTOM_CURRENCY_B: // Custom currency B
case CUSTOM_CURRENCY_C: // Custom currency C
case CUSTOM_CURRENCY_D: // Custom currency D
case CUSTOM_CURRENCY_E: // Custom currency E
default:
return TextType.get();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "mapNumericType" | "private static AbstractValueType mapNumericType(SPSSVariable variable) {
switch(getSpssNumericDataType(variable)) {
case COMMA: // comma
case DOLLAR: // dollar
case DOT: // dot
case FIXED: // fixed format (default)
case SCIENTIFIC: // scientific notation
return variable.getDecimals() > 0 ? DecimalType.get() : IntegerType.get();
<MASK>case DATE: // Date dd-mmm-yyyy or dd-mmm-yy</MASK>
case ADATE: // Date in mm/dd/yy or mm/dd/yyyy
case EDATE: // Date in dd.mm.yy or dd.mm.yyyy
case SDATE: // Date in yyyy/mm/dd or yy/mm/dd (?)
return DateType.get();
case DATETIME: // DateTime in dd-mmm-yyyy hh:mm, dd-mmm-yyyy hh:mm:ss or dd-mmm-yyyy hh:mm:ss.ss
return DateTimeType.get();
case TIME: // Time in hh:mm, hh:mm:ss or hh:mm:ss.ss
case JDATE: // Date in yyyyddd or yyddd
case DTIME: // DateTime in ddd:hh:mm, ddd:hh:mm:ss or ddd:hh:mm:ss.ss
case WEEK_DAY: // Date as day of the week, full name or 3-letter
case MONTH: // Date 3-letter month
case MONTH_YEAR: // Date in mmm yyyy or mmm yy
case QUARTERLY_YEAR: // Date in q Q yyyy or q Q yy
case WEEK_YEAR: // Date in wk WK yyyy or wk WK yy
case CUSTOM_CURRENCY_A: // Custom currency A
case CUSTOM_CURRENCY_B: // Custom currency B
case CUSTOM_CURRENCY_C: // Custom currency C
case CUSTOM_CURRENCY_D: // Custom currency D
case CUSTOM_CURRENCY_E: // Custom currency E
default:
return TextType.get();
}
}" |
Inversion-Mutation | megadiff | "@Override
public void accept(TaskData taskData) {
ITask task = taskList.getTask(taskData.getRepositoryUrl(), taskData.getTaskId());
if (task == null) {
task = tasksModel.createTask(repository, taskData.getTaskId());
((AbstractTask) task).setSynchronizationState(SynchronizationState.INCOMING_NEW);
if (taskData.isPartial() && connector.canSynchronizeTask(repository, task)) {
session.markStale(task);
}
} else {
removedQueryResults.remove(task);
}
taskList.addTask(task, repositoryQuery);
try {
session.putTaskData(task, taskData);
} catch (CoreException e) {
StatusHandler.log(new Status(IStatus.ERROR, ITasksCoreConstants.ID_PLUGIN, "Failed to save task", e)); //$NON-NLS-1$
}
resultCount++;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "accept" | "@Override
public void accept(TaskData taskData) {
ITask task = taskList.getTask(taskData.getRepositoryUrl(), taskData.getTaskId());
if (task == null) {
task = tasksModel.createTask(repository, taskData.getTaskId());
((AbstractTask) task).setSynchronizationState(SynchronizationState.INCOMING_NEW);
if (taskData.isPartial() && connector.canSynchronizeTask(repository, task)) {
session.markStale(task);
}
} else {
removedQueryResults.remove(task);
}
try {
session.putTaskData(task, taskData);
} catch (CoreException e) {
StatusHandler.log(new Status(IStatus.ERROR, ITasksCoreConstants.ID_PLUGIN, "Failed to save task", e)); //$NON-NLS-1$
}
<MASK>taskList.addTask(task, repositoryQuery);</MASK>
resultCount++;
}" |
Inversion-Mutation | megadiff | "public TileSet(TiledMap map, Element element, boolean loadImage) throws SlickException {
this.map = map;
firstGID = Integer.parseInt(element.getAttribute("firstgid"));
String source = element.getAttribute("source");
if ((source != null) && (!source.equals(""))) {
try {
InputStream in = ResourceLoader.getResourceAsStream(map.getTilesLocation() + "/" + source);
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(in);
Element docElement = doc.getDocumentElement();
element = docElement; //(Element) docElement.getElementsByTagName("tileset").item(0);
name = element.getAttribute("name");
} catch (Exception e) {
Log.error(e);
throw new SlickException("Unable to load or parse sourced tileset: "+this.map.tilesLocation+"/"+source);
}
}
String tileWidthString = element.getAttribute("tilewidth");
String tileHeightString = element.getAttribute("tileheight");
if(tileWidthString.length() == 0 || tileHeightString.length() == 0) {
throw new SlickException("TiledMap requires that the map be created with tilesets that use a " +
"single image. Check the WiKi for more complete information.");
}
tileWidth = Integer.parseInt(tileWidthString);
tileHeight = Integer.parseInt(tileHeightString);
String sv = element.getAttribute("spacing");
if ((sv != null) && (!sv.equals(""))) {
tileSpacing = Integer.parseInt(sv);
}
String mv = element.getAttribute("margin");
if ((mv != null) && (!mv.equals(""))) {
tileMargin = Integer.parseInt(mv);
}
NodeList list = element.getElementsByTagName("image");
Element imageNode = (Element) list.item(0);
String ref = imageNode.getAttribute("source");
Color trans = null;
String t = imageNode.getAttribute("trans");
if ((t != null) && (t.length() > 0)) {
int c = Integer.parseInt(t, 16);
trans = new Color(c);
}
if (loadImage) {
Image image = new Image(map.getTilesLocation()+"/"+ref,false,Image.FILTER_NEAREST,trans);
setTileSetImage(image);
}
NodeList pElements = element.getElementsByTagName("tile");
for (int i=0;i<pElements.getLength();i++) {
Element tileElement = (Element) pElements.item(i);
int id = Integer.parseInt(tileElement.getAttribute("id"));
id += firstGID;
Properties tileProps = new Properties();
Element propsElement = (Element) tileElement.getElementsByTagName("properties").item(0);
NodeList properties = propsElement.getElementsByTagName("property");
for (int p=0;p<properties.getLength();p++) {
Element propElement = (Element) properties.item(p);
String name = propElement.getAttribute("name");
String value = propElement.getAttribute("value");
tileProps.setProperty(name, value);
}
props.put(new Integer(id), tileProps);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "TileSet" | "public TileSet(TiledMap map, Element element, boolean loadImage) throws SlickException {
this.map = map;
<MASK>name = element.getAttribute("name");</MASK>
firstGID = Integer.parseInt(element.getAttribute("firstgid"));
String source = element.getAttribute("source");
if ((source != null) && (!source.equals(""))) {
try {
InputStream in = ResourceLoader.getResourceAsStream(map.getTilesLocation() + "/" + source);
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(in);
Element docElement = doc.getDocumentElement();
element = docElement; //(Element) docElement.getElementsByTagName("tileset").item(0);
} catch (Exception e) {
Log.error(e);
throw new SlickException("Unable to load or parse sourced tileset: "+this.map.tilesLocation+"/"+source);
}
}
String tileWidthString = element.getAttribute("tilewidth");
String tileHeightString = element.getAttribute("tileheight");
if(tileWidthString.length() == 0 || tileHeightString.length() == 0) {
throw new SlickException("TiledMap requires that the map be created with tilesets that use a " +
"single image. Check the WiKi for more complete information.");
}
tileWidth = Integer.parseInt(tileWidthString);
tileHeight = Integer.parseInt(tileHeightString);
String sv = element.getAttribute("spacing");
if ((sv != null) && (!sv.equals(""))) {
tileSpacing = Integer.parseInt(sv);
}
String mv = element.getAttribute("margin");
if ((mv != null) && (!mv.equals(""))) {
tileMargin = Integer.parseInt(mv);
}
NodeList list = element.getElementsByTagName("image");
Element imageNode = (Element) list.item(0);
String ref = imageNode.getAttribute("source");
Color trans = null;
String t = imageNode.getAttribute("trans");
if ((t != null) && (t.length() > 0)) {
int c = Integer.parseInt(t, 16);
trans = new Color(c);
}
if (loadImage) {
Image image = new Image(map.getTilesLocation()+"/"+ref,false,Image.FILTER_NEAREST,trans);
setTileSetImage(image);
}
NodeList pElements = element.getElementsByTagName("tile");
for (int i=0;i<pElements.getLength();i++) {
Element tileElement = (Element) pElements.item(i);
int id = Integer.parseInt(tileElement.getAttribute("id"));
id += firstGID;
Properties tileProps = new Properties();
Element propsElement = (Element) tileElement.getElementsByTagName("properties").item(0);
NodeList properties = propsElement.getElementsByTagName("property");
for (int p=0;p<properties.getLength();p++) {
Element propElement = (Element) properties.item(p);
String name = propElement.getAttribute("name");
String value = propElement.getAttribute("value");
tileProps.setProperty(name, value);
}
props.put(new Integer(id), tileProps);
}
}" |
Inversion-Mutation | megadiff | "public void popupDismissed(boolean topPopupOnly) {
initializePopup();
// if the 2nd level popup gets dismissed
if (mPopupStatus == POPUP_SECOND_LEVEL) {
mPopupStatus = POPUP_FIRST_LEVEL;
if (topPopupOnly) mUI.showPopup(mPopup);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "popupDismissed" | "public void popupDismissed(boolean topPopupOnly) {
// if the 2nd level popup gets dismissed
if (mPopupStatus == POPUP_SECOND_LEVEL) {
<MASK>initializePopup();</MASK>
mPopupStatus = POPUP_FIRST_LEVEL;
if (topPopupOnly) mUI.showPopup(mPopup);
}
}" |
Inversion-Mutation | megadiff | "public float[] getViewMatrix() {
if (mLookAt != null) {
Matrix.setLookAtM(mVMatrix, 0, mPosition.x, mPosition.y,
mPosition.z, mLookAt.x, mLookAt.y, mLookAt.z, mUpAxis.x, mUpAxis.y,
mUpAxis.z);
mLocalOrientation.fromEuler(mRotation.y, mRotation.z, mRotation.x);
mLocalOrientation.toRotationMatrix(mRotationMatrix);
Matrix.multiplyMM(mVMatrix, 0, mRotationMatrix, 0, mVMatrix, 0);
} else {
if (mUseRotationMatrix == false && mRotationDirty) {
setOrientation();
mRotationDirty = false;
}
mOrientation.toRotationMatrix(mRotationMatrix);
Matrix.setIdentityM(mTmpMatrix, 0);
Matrix.setIdentityM(mVMatrix, 0);
Matrix.translateM(mTmpMatrix, 0, -mPosition.x, -mPosition.y, -mPosition.z);
Matrix.multiplyMM(mVMatrix, 0, mRotationMatrix, 0, mTmpMatrix, 0);
}
return mVMatrix;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getViewMatrix" | "public float[] getViewMatrix() {
if (mLookAt != null) {
Matrix.setLookAtM(mVMatrix, 0, mPosition.x, mPosition.y,
mPosition.z, mLookAt.x, mLookAt.y, mLookAt.z, mUpAxis.x, mUpAxis.y,
mUpAxis.z);
mLocalOrientation.fromEuler(mRotation.y, mRotation.z, mRotation.x);
mLocalOrientation.toRotationMatrix(mRotationMatrix);
Matrix.multiplyMM(mVMatrix, 0, mRotationMatrix, 0, mVMatrix, 0);
} else {
if (mUseRotationMatrix == false && mRotationDirty) {
setOrientation();
<MASK>mOrientation.toRotationMatrix(mRotationMatrix);</MASK>
mRotationDirty = false;
}
Matrix.setIdentityM(mTmpMatrix, 0);
Matrix.setIdentityM(mVMatrix, 0);
Matrix.translateM(mTmpMatrix, 0, -mPosition.x, -mPosition.y, -mPosition.z);
Matrix.multiplyMM(mVMatrix, 0, mRotationMatrix, 0, mTmpMatrix, 0);
}
return mVMatrix;
}" |
Inversion-Mutation | megadiff | "@Override
public void execute(final EcBuildOrder s, final EcEvolver e)
{
s.minerals -= 50;
s.gas -= 100;
s.addFutureAction(17, new Runnable()
{
@Override
public void run()
{
if (e.debug)
e.obtained(s," Overseer+1");
s.overlords -= 1;
s.overseers += 1;
}
});
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "execute" | "@Override
public void execute(final EcBuildOrder s, final EcEvolver e)
{
s.minerals -= 50;
s.gas -= 100;
<MASK>s.overlords -= 1;</MASK>
s.addFutureAction(17, new Runnable()
{
@Override
public void run()
{
if (e.debug)
e.obtained(s," Overseer+1");
s.overseers += 1;
}
});
}" |
Inversion-Mutation | megadiff | "private boolean handleGet(HttpServletRequest request, HttpServletResponse response, String path) throws IOException, JSONException, ServletException, URISyntaxException, CoreException {
Path p = new Path(path);
// FIXME: what if a remote or branch is named "file"?
if (p.segment(0).equals("file")) { //$NON-NLS-1$
// /git/remote/file/{path}
File gitDir = GitUtils.getGitDir(p);
Repository db = new FileRepository(gitDir);
Set<String> configNames = db.getConfig().getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
JSONObject result = new JSONObject();
JSONArray children = new JSONArray();
URI baseLocation = getURI(request);
for (String configName : configNames) {
JSONObject o = new JSONObject();
o.put(ProtocolConstants.KEY_NAME, configName);
o.put(ProtocolConstants.KEY_TYPE, GitConstants.KEY_REMOTE_NAME);
o.put(ProtocolConstants.KEY_LOCATION, BaseToRemoteConverter.REMOVE_FIRST_2.baseToRemoteLocation(baseLocation, configName, "" /* no branch name */)); //$NON-NLS-1$
children.put(o);
}
result.put(ProtocolConstants.KEY_CHILDREN, children);
OrionServlet.writeJSONResponse(request, response, result);
return true;
} else if (p.segment(1).equals("file")) { //$NON-NLS-1$
// /git/remote/{remote}/file/{path}
File gitDir = GitUtils.getGitDir(p.removeFirstSegments(1));
Repository db = new FileRepository(gitDir);
Set<String> configNames = db.getConfig().getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
JSONObject result = new JSONObject();
URI baseLocation = getURI(request);
for (String configName : configNames) {
if (configName.equals(p.segment(0))) {
result.put(ProtocolConstants.KEY_NAME, configName);
result.put(ProtocolConstants.KEY_TYPE, GitConstants.KEY_REMOTE_NAME);
result.put(ProtocolConstants.KEY_LOCATION, BaseToRemoteConverter.REMOVE_FIRST_3.baseToRemoteLocation(baseLocation, p.segment(0), "" /* no branch name */)); //$NON-NLS-1$
JSONArray children = new JSONArray();
List<Ref> refs = new ArrayList<Ref>();
for (Entry<String, Ref> refEntry : db.getRefDatabase().getRefs(Constants.R_REMOTES + p.uptoSegment(1)).entrySet()) {
if (!refEntry.getValue().isSymbolic()) {
Ref ref = refEntry.getValue();
String name = ref.getName();
name = Repository.shortenRefName(name).substring(Constants.DEFAULT_REMOTE_NAME.length() + 1);
if (db.getBranch().equals(name)) {
refs.add(0, ref);
} else {
refs.add(ref);
}
}
}
for (Ref ref : refs) {
JSONObject o = new JSONObject();
String name = ref.getName();
o.put(ProtocolConstants.KEY_NAME, name);
o.put(ProtocolConstants.KEY_TYPE, GitConstants.REMOTE_TRACKING_BRANCH_TYPE);
o.put(ProtocolConstants.KEY_ID, ref.getObjectId().name());
// see bug 342602
// o.put(GitConstants.KEY_COMMIT, baseToCommitLocation(baseLocation, name));
o.put(ProtocolConstants.KEY_LOCATION, BaseToRemoteConverter.REMOVE_FIRST_3.baseToRemoteLocation(baseLocation, "" /*short name is {remote}/{branch}*/, Repository.shortenRefName(name))); //$NON-NLS-1$
o.put(GitConstants.KEY_COMMIT, BaseToCommitConverter.getCommitLocation(baseLocation, ref.getObjectId().name(), BaseToCommitConverter.REMOVE_FIRST_3));
o.put(GitConstants.KEY_HEAD, BaseToCommitConverter.getCommitLocation(baseLocation, Constants.HEAD, BaseToCommitConverter.REMOVE_FIRST_3));
o.put(GitConstants.KEY_CLONE, BaseToCloneConverter.getCloneLocation(baseLocation, BaseToCloneConverter.REMOTE));
o.put(GitConstants.KEY_BRANCH, BaseToBranchConverter.getBranchLocation(baseLocation, BaseToBranchConverter.REMOTE));
o.put(GitConstants.KEY_INDEX, BaseToIndexConverter.getIndexLocation(baseLocation, BaseToIndexConverter.REMOTE));
children.put(o);
}
result.put(ProtocolConstants.KEY_CHILDREN, children);
OrionServlet.writeJSONResponse(request, response, result);
return true;
}
}
String msg = NLS.bind("Couldn't find remote : {0}", p.segment(0));
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
} else if (p.segment(2).equals("file")) { //$NON-NLS-1$
// /git/remote/{remote}/{branch}/file/{path}
File gitDir = GitUtils.getGitDir(p.removeFirstSegments(2));
Repository db = new FileRepository(gitDir);
Set<String> configNames = db.getConfig().getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
URI baseLocation = getURI(request);
for (String configName : configNames) {
if (configName.equals(p.segment(0))) {
for (Entry<String, Ref> refEntry : db.getRefDatabase().getRefs(Constants.R_REMOTES).entrySet()) {
Ref ref = refEntry.getValue();
String name = ref.getName();
if (!ref.isSymbolic() && name.equals(Constants.R_REMOTES + p.uptoSegment(2).removeTrailingSeparator())) {
JSONObject result = new JSONObject();
result.put(ProtocolConstants.KEY_NAME, name);
result.put(ProtocolConstants.KEY_TYPE, GitConstants.REMOTE_TRACKING_BRANCH_TYPE);
result.put(ProtocolConstants.KEY_ID, ref.getObjectId().name());
// see bug 342602
// result.put(GitConstants.KEY_COMMIT, baseToCommitLocation(baseLocation, name));
result.put(ProtocolConstants.KEY_LOCATION, BaseToRemoteConverter.REMOVE_FIRST_4.baseToRemoteLocation(baseLocation, "" /*short name is {remote}/{branch}*/, Repository.shortenRefName(name))); //$NON-NLS-1$
result.put(GitConstants.KEY_COMMIT, BaseToCommitConverter.getCommitLocation(baseLocation, ref.getObjectId().name(), BaseToCommitConverter.REMOVE_FIRST_4));
result.put(GitConstants.KEY_HEAD, BaseToCommitConverter.getCommitLocation(baseLocation, Constants.HEAD, BaseToCommitConverter.REMOVE_FIRST_4));
result.put(GitConstants.KEY_CLONE, BaseToCloneConverter.getCloneLocation(baseLocation, BaseToCloneConverter.REMOTE_BRANCH));
OrionServlet.writeJSONResponse(request, response, result);
return true;
}
}
}
}
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, "No remote branch found: " + p.uptoSegment(2).removeTrailingSeparator(), null));
}
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Bad request, \"/git/remote/{remote}/{branch}/file/{path}\" expected", null));
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handleGet" | "private boolean handleGet(HttpServletRequest request, HttpServletResponse response, String path) throws IOException, JSONException, ServletException, URISyntaxException, CoreException {
Path p = new Path(path);
// FIXME: what if a remote or branch is named "file"?
if (p.segment(0).equals("file")) { //$NON-NLS-1$
// /git/remote/file/{path}
File gitDir = GitUtils.getGitDir(p);
Repository db = new FileRepository(gitDir);
Set<String> configNames = db.getConfig().getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
JSONObject result = new JSONObject();
JSONArray children = new JSONArray();
URI baseLocation = getURI(request);
for (String configName : configNames) {
JSONObject o = new JSONObject();
o.put(ProtocolConstants.KEY_NAME, configName);
o.put(ProtocolConstants.KEY_TYPE, GitConstants.KEY_REMOTE_NAME);
o.put(ProtocolConstants.KEY_LOCATION, BaseToRemoteConverter.REMOVE_FIRST_2.baseToRemoteLocation(baseLocation, configName, "" /* no branch name */)); //$NON-NLS-1$
children.put(o);
}
result.put(ProtocolConstants.KEY_CHILDREN, children);
OrionServlet.writeJSONResponse(request, response, result);
return true;
} else if (p.segment(1).equals("file")) { //$NON-NLS-1$
// /git/remote/{remote}/file/{path}
File gitDir = GitUtils.getGitDir(p.removeFirstSegments(1));
Repository db = new FileRepository(gitDir);
Set<String> configNames = db.getConfig().getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
JSONObject result = new JSONObject();
URI baseLocation = getURI(request);
for (String configName : configNames) {
if (configName.equals(p.segment(0))) {
result.put(ProtocolConstants.KEY_NAME, configName);
result.put(ProtocolConstants.KEY_TYPE, GitConstants.KEY_REMOTE_NAME);
result.put(ProtocolConstants.KEY_LOCATION, BaseToRemoteConverter.REMOVE_FIRST_3.baseToRemoteLocation(baseLocation, p.segment(0), "" /* no branch name */)); //$NON-NLS-1$
JSONArray children = new JSONArray();
List<Ref> refs = new ArrayList<Ref>();
for (Entry<String, Ref> refEntry : db.getRefDatabase().getRefs(Constants.R_REMOTES + p.uptoSegment(1)).entrySet()) {
if (!refEntry.getValue().isSymbolic()) {
Ref ref = refEntry.getValue();
String name = ref.getName();
name = Repository.shortenRefName(name).substring(Constants.DEFAULT_REMOTE_NAME.length() + 1);
if (db.getBranch().equals(name)) {
refs.add(0, ref);
} else {
refs.add(ref);
}
}
}
for (Ref ref : refs) {
JSONObject o = new JSONObject();
String name = ref.getName();
o.put(ProtocolConstants.KEY_NAME, name);
o.put(ProtocolConstants.KEY_TYPE, GitConstants.REMOTE_TRACKING_BRANCH_TYPE);
o.put(ProtocolConstants.KEY_ID, ref.getObjectId().name());
// see bug 342602
// o.put(GitConstants.KEY_COMMIT, baseToCommitLocation(baseLocation, name));
o.put(ProtocolConstants.KEY_LOCATION, BaseToRemoteConverter.REMOVE_FIRST_3.baseToRemoteLocation(baseLocation, "" /*short name is {remote}/{branch}*/, Repository.shortenRefName(name))); //$NON-NLS-1$
o.put(GitConstants.KEY_COMMIT, BaseToCommitConverter.getCommitLocation(baseLocation, ref.getObjectId().name(), BaseToCommitConverter.REMOVE_FIRST_3));
o.put(GitConstants.KEY_HEAD, BaseToCommitConverter.getCommitLocation(baseLocation, Constants.HEAD, BaseToCommitConverter.REMOVE_FIRST_3));
o.put(GitConstants.KEY_CLONE, BaseToCloneConverter.getCloneLocation(baseLocation, BaseToCloneConverter.REMOTE));
o.put(GitConstants.KEY_BRANCH, BaseToBranchConverter.getBranchLocation(baseLocation, BaseToBranchConverter.REMOTE));
o.put(GitConstants.KEY_INDEX, BaseToIndexConverter.getIndexLocation(baseLocation, BaseToIndexConverter.REMOTE));
children.put(o);
}
result.put(ProtocolConstants.KEY_CHILDREN, children);
OrionServlet.writeJSONResponse(request, response, result);
return true;
}
}
String msg = NLS.bind("Couldn't find remote : {0}", p.segment(0));
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
} else if (p.segment(2).equals("file")) { //$NON-NLS-1$
// /git/remote/{remote}/{branch}/file/{path}
File gitDir = GitUtils.getGitDir(p.removeFirstSegments(2));
Repository db = new FileRepository(gitDir);
Set<String> configNames = db.getConfig().getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
URI baseLocation = getURI(request);
for (String configName : configNames) {
if (configName.equals(p.segment(0))) {
for (Entry<String, Ref> refEntry : db.getRefDatabase().getRefs(Constants.R_REMOTES).entrySet()) {
Ref ref = refEntry.getValue();
String name = ref.getName();
if (!ref.isSymbolic() && name.equals(Constants.R_REMOTES + p.uptoSegment(2).removeTrailingSeparator())) {
JSONObject result = new JSONObject();
result.put(ProtocolConstants.KEY_NAME, name);
result.put(ProtocolConstants.KEY_TYPE, GitConstants.REMOTE_TRACKING_BRANCH_TYPE);
result.put(ProtocolConstants.KEY_ID, ref.getObjectId().name());
// see bug 342602
// result.put(GitConstants.KEY_COMMIT, baseToCommitLocation(baseLocation, name));
result.put(ProtocolConstants.KEY_LOCATION, BaseToRemoteConverter.REMOVE_FIRST_4.baseToRemoteLocation(baseLocation, "" /*short name is {remote}/{branch}*/, Repository.shortenRefName(name))); //$NON-NLS-1$
result.put(GitConstants.KEY_COMMIT, BaseToCommitConverter.getCommitLocation(baseLocation, ref.getObjectId().name(), BaseToCommitConverter.REMOVE_FIRST_4));
result.put(GitConstants.KEY_HEAD, BaseToCommitConverter.getCommitLocation(baseLocation, Constants.HEAD, BaseToCommitConverter.REMOVE_FIRST_4));
result.put(GitConstants.KEY_CLONE, BaseToCloneConverter.getCloneLocation(baseLocation, BaseToCloneConverter.REMOTE_BRANCH));
OrionServlet.writeJSONResponse(request, response, result);
return true;
}
}
}
<MASK>return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, "No remote branch found: " + p.uptoSegment(2).removeTrailingSeparator(), null));</MASK>
}
}
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Bad request, \"/git/remote/{remote}/{branch}/file/{path}\" expected", null));
}" |
Inversion-Mutation | megadiff | "@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
app = this;
StorageUtil.initialize();
AppData.getInstance().initialize();
DensityAdaptor.init(this);
StorageUtil.loadCachedBooks();
CloudAPI.CloudToken = "";
setContentView(initializeWithSlidingStyle());
tryAutoLogin();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCreate" | "@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
app = this;
AppData.getInstance().initialize();
DensityAdaptor.init(this);
<MASK>StorageUtil.initialize();</MASK>
StorageUtil.loadCachedBooks();
CloudAPI.CloudToken = "";
setContentView(initializeWithSlidingStyle());
tryAutoLogin();
}" |
Inversion-Mutation | megadiff | "public void updated( Dictionary configuration )
throws ConfigurationException
{
if( configuration == null )
{
configureDefaults();
return;
}
Properties extracted = extractKeys( configuration );
LogManager.resetConfiguration();
// If the updated() method is called without any log4j properties,
// then keep the default/previous configuration.
if( extracted.size() == 0 )
{
configureDefaults();
return;
}
PaxLoggingConfigurator configurator = new PaxLoggingConfigurator( m_appenderTracker );
configurator.doConfigure( extracted, LogManager.getLoggerRepository() );
setLevelToJavaLogging( configuration );
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "updated" | "public void updated( Dictionary configuration )
throws ConfigurationException
{
if( configuration == null )
{
configureDefaults();
return;
}
Properties extracted = extractKeys( configuration );
// If the updated() method is called without any log4j properties,
// then keep the default/previous configuration.
if( extracted.size() == 0 )
{
configureDefaults();
return;
}
PaxLoggingConfigurator configurator = new PaxLoggingConfigurator( m_appenderTracker );
<MASK>LogManager.resetConfiguration();</MASK>
configurator.doConfigure( extracted, LogManager.getLoggerRepository() );
setLevelToJavaLogging( configuration );
}" |
Inversion-Mutation | megadiff | "public static <T> String join(Collection<T> collection, String separator) {
String out = "";
Boolean firstElement = true;
for (T t : collection) {
if (!firstElement)
out += separator;
out += t;
firstElement = false;
}
return out;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "join" | "public static <T> String join(Collection<T> collection, String separator) {
String out = "";
Boolean firstElement = true;
for (T t : collection) {
<MASK>out += t;</MASK>
if (!firstElement)
out += separator;
firstElement = false;
}
return out;
}" |
Inversion-Mutation | megadiff | "@Override
public void doCrawl(HttpServletRequest req) throws WebCrawlException {
int i = 0;
int j = 0;
int k = 0;
String msg = null;
String urlStr = null;
try {
for (k=0; k<URL_LIST.length; k++) {
urlStr = URL_LIST[k];
logger.info("Processing URL: " + urlStr);
URL url = new URL(urlStr);
InputStream is = url.openStream();
String res = null;
try {
res = convertStreamToString(is);
}
catch (Exception e) {
}
Tidy tidy = new Tidy();
tidy.setMakeClean(true);
tidy.setQuiet(false);
tidy.setBreakBeforeBR(true);
tidy.setOutputEncoding("latin1");
tidy.setXmlOut(false);
tidy.setNumEntities(true);
tidy.setDropFontTags(true);
tidy.setSpaces(2);
tidy.setIndentAttributes(false);
tidy.setHideComments(true);
tidy.setShowWarnings(false);
OutputStream os = null;
StringReader r = new StringReader(res);
StringWriter w = new StringWriter();
Document doc = tidy.parseDOM(r, w);
Date reportDate = null;
// 05/10/2010
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
//
// try parsing out the reports
//
NodeList spanList = doc.getElementsByTagName("span");
if (spanList != null && spanList.getLength() > 0) {
logger.info("Found expected span tag(s) on the page");
}
else {
throw new WebCrawlException("Unexpected number of <table> tags", urlStr);
}
ReportDO report = null;
Node tdTag = null;
ReportDao reportDao = new ReportDao();
String keyword = null;
String dateStr = null;
String reportStr = null;
List<String> textList = null;
NamedNodeMap attribMap = null;
//
// traverse span tags
//
for (i=0; i<spanList.getLength(); i++) {
Node node = spanList.item(i);
if (node != null) {
attribMap = node.getAttributes();
Node id = attribMap.getNamedItem("id");
if (id != null) {
if (id.getNodeValue().equalsIgnoreCase("ctl00_ContentPlaceHolder1_FormView1_NameLabel")) {
keyword = getNodeContents(node);
logger.info("Found keyword: " + keyword);
}
else if (id.getNodeValue().equalsIgnoreCase("ctl00_ContentPlaceHolder1_FormView1_Label1")) {
dateStr = getNodeContents(node);
logger.info("Found dateStr: " + dateStr);
try {
reportDate = formatter.parse(dateStr);
}
catch (Exception e) {
throw new WebCrawlException(e.getMessage(), urlStr);
}
}
else if (id.getNodeValue().equalsIgnoreCase("ctl00_ContentPlaceHolder1_FormView1_FishingReportLabel")) {
reportStr = getNodeContents(node);
logger.info("Using report text: " + reportStr);
//
// create report object
//
report = new ReportDO();
report.setReportedBy(PROVIDER);
report.setKeyword(keyword);
report.setReportDate(reportDate);
report.setReportBody(reportStr);
report.setState(STATE);
StringBuilder sb = new StringBuilder();
sb.append(STATE);
sb.append(":");
String uniqueKey = report.getKeyword();
uniqueKey= uniqueKey.toUpperCase();
uniqueKey = EscapeChars.forXML(uniqueKey);
sb.append(uniqueKey);
report.setReportKey(sb.toString());
reportDao.addOrUpdateReport(report);
break;
}
else {
throw new WebCrawlException("Unknown <span id='" + id.getNodeValue() + "'> tag; page might have changed.", urlStr);
}
}
}
}
}
}
catch (MalformedURLException e) {
logger.severe(Util.getStackTrace(e));
throw new WebCrawlException(e.getMessage(), urlStr);
}
catch (IOException e) {
logger.severe(Util.getStackTrace(e));
throw new WebCrawlException(e.getMessage(), urlStr);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doCrawl" | "@Override
public void doCrawl(HttpServletRequest req) throws WebCrawlException {
int i = 0;
int j = 0;
int k = 0;
String msg = null;
String urlStr = null;
try {
for (k=0; k<URL_LIST.length; k++) {
urlStr = URL_LIST[k];
logger.info("Processing URL: " + urlStr);
URL url = new URL(urlStr);
InputStream is = url.openStream();
String res = null;
try {
res = convertStreamToString(is);
}
catch (Exception e) {
}
Tidy tidy = new Tidy();
tidy.setMakeClean(true);
tidy.setQuiet(false);
tidy.setBreakBeforeBR(true);
tidy.setOutputEncoding("latin1");
tidy.setXmlOut(false);
tidy.setNumEntities(true);
tidy.setDropFontTags(true);
tidy.setSpaces(2);
tidy.setIndentAttributes(false);
tidy.setHideComments(true);
tidy.setShowWarnings(false);
OutputStream os = null;
StringReader r = new StringReader(res);
StringWriter w = new StringWriter();
Document doc = tidy.parseDOM(r, w);
Date reportDate = null;
// 05/10/2010
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
//
// try parsing out the reports
//
NodeList spanList = doc.getElementsByTagName("span");
if (spanList != null && spanList.getLength() > 0) {
logger.info("Found expected span tag(s) on the page");
}
else {
throw new WebCrawlException("Unexpected number of <table> tags", urlStr);
}
ReportDO report = null;
Node tdTag = null;
ReportDao reportDao = new ReportDao();
<MASK>report.setReportedBy(PROVIDER);</MASK>
String keyword = null;
String dateStr = null;
String reportStr = null;
List<String> textList = null;
NamedNodeMap attribMap = null;
//
// traverse span tags
//
for (i=0; i<spanList.getLength(); i++) {
Node node = spanList.item(i);
if (node != null) {
attribMap = node.getAttributes();
Node id = attribMap.getNamedItem("id");
if (id != null) {
if (id.getNodeValue().equalsIgnoreCase("ctl00_ContentPlaceHolder1_FormView1_NameLabel")) {
keyword = getNodeContents(node);
logger.info("Found keyword: " + keyword);
}
else if (id.getNodeValue().equalsIgnoreCase("ctl00_ContentPlaceHolder1_FormView1_Label1")) {
dateStr = getNodeContents(node);
logger.info("Found dateStr: " + dateStr);
try {
reportDate = formatter.parse(dateStr);
}
catch (Exception e) {
throw new WebCrawlException(e.getMessage(), urlStr);
}
}
else if (id.getNodeValue().equalsIgnoreCase("ctl00_ContentPlaceHolder1_FormView1_FishingReportLabel")) {
reportStr = getNodeContents(node);
logger.info("Using report text: " + reportStr);
//
// create report object
//
report = new ReportDO();
report.setKeyword(keyword);
report.setReportDate(reportDate);
report.setReportBody(reportStr);
report.setState(STATE);
StringBuilder sb = new StringBuilder();
sb.append(STATE);
sb.append(":");
String uniqueKey = report.getKeyword();
uniqueKey= uniqueKey.toUpperCase();
uniqueKey = EscapeChars.forXML(uniqueKey);
sb.append(uniqueKey);
report.setReportKey(sb.toString());
reportDao.addOrUpdateReport(report);
break;
}
else {
throw new WebCrawlException("Unknown <span id='" + id.getNodeValue() + "'> tag; page might have changed.", urlStr);
}
}
}
}
}
}
catch (MalformedURLException e) {
logger.severe(Util.getStackTrace(e));
throw new WebCrawlException(e.getMessage(), urlStr);
}
catch (IOException e) {
logger.severe(Util.getStackTrace(e));
throw new WebCrawlException(e.getMessage(), urlStr);
}
}" |
Inversion-Mutation | megadiff | "private void showAddressField() {
dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_searchaddress);
final TextView message = (TextView) dialog.findViewById(R.id.message);
message.setText(R.string.searchAddressTask);
final EditText searchEdit = (EditText) dialog.findViewById(R.id.search);
searchEdit.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() != KeyEvent.ACTION_DOWN) {
return false;
}
switch (keyCode) {
case KeyEvent.KEYCODE_ENTER:
case KeyEvent.KEYCODE_DPAD_CENTER:
dialog.dismiss();
geoMap(searchEdit.getText().toString());
return true;
}
return false;
}
});
/*
* Handler onCancel
*/
dialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
handler.onCanceled();
}
});
dialog.show();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "showAddressField" | "private void showAddressField() {
dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_searchaddress);
final TextView message = (TextView) dialog.findViewById(R.id.message);
message.setText(R.string.searchAddressTask);
final EditText searchEdit = (EditText) dialog.findViewById(R.id.search);
searchEdit.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() != KeyEvent.ACTION_DOWN) {
return false;
}
switch (keyCode) {
case KeyEvent.KEYCODE_ENTER:
case KeyEvent.KEYCODE_DPAD_CENTER:
<MASK>geoMap(searchEdit.getText().toString());</MASK>
dialog.dismiss();
return true;
}
return false;
}
});
/*
* Handler onCancel
*/
dialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
handler.onCanceled();
}
});
dialog.show();
}" |
Inversion-Mutation | megadiff | "public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() != KeyEvent.ACTION_DOWN) {
return false;
}
switch (keyCode) {
case KeyEvent.KEYCODE_ENTER:
case KeyEvent.KEYCODE_DPAD_CENTER:
dialog.dismiss();
geoMap(searchEdit.getText().toString());
return true;
}
return false;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onKey" | "public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() != KeyEvent.ACTION_DOWN) {
return false;
}
switch (keyCode) {
case KeyEvent.KEYCODE_ENTER:
case KeyEvent.KEYCODE_DPAD_CENTER:
<MASK>geoMap(searchEdit.getText().toString());</MASK>
dialog.dismiss();
return true;
}
return false;
}" |
Inversion-Mutation | megadiff | "protected void fillDialogMenu(IMenuManager dialogMenu) {
dialogMenu.add(new GroupMarker("SystemMenuStart")); //$NON-NLS-1$
dialogMenu.add(new MoveAction());
dialogMenu.add(new ResizeAction());
if (showPersistActions) {
dialogMenu.add(new PersistLocationAction());
dialogMenu.add(new PersistSizeAction());
}
dialogMenu.add(new Separator("SystemMenuEnd")); //$NON-NLS-1$
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "fillDialogMenu" | "protected void fillDialogMenu(IMenuManager dialogMenu) {
dialogMenu.add(new GroupMarker("SystemMenuStart")); //$NON-NLS-1$
dialogMenu.add(new MoveAction());
dialogMenu.add(new ResizeAction());
if (showPersistActions) {
<MASK>dialogMenu.add(new PersistSizeAction());</MASK>
dialogMenu.add(new PersistLocationAction());
}
dialogMenu.add(new Separator("SystemMenuEnd")); //$NON-NLS-1$
}" |
Inversion-Mutation | megadiff | "private void createJREComposite(Composite main) {
// Create our composite
jreComposite = new Composite(main, SWT.NONE);
FormData cData = new FormData();
cData.left = new FormAttachment(0, 5);
cData.right = new FormAttachment(100, -5);
cData.top = new FormAttachment(homeDirComposite, 10);
jreComposite.setLayoutData(cData);
jreComposite.setLayout(new FormLayout());
// Create Internal Widgets
installedJRELabel = new Label(jreComposite, SWT.NONE);
installedJRELabel.setText(Messages.wf_JRELabel);
jreCombo = new Combo(jreComposite, SWT.DROP_DOWN | SWT.READ_ONLY);
jreCombo.setItems(jreNames);
if( defaultVMIndex != -1 )
jreCombo.select(defaultVMIndex);
jreButton = new Button(jreComposite, SWT.NONE);
jreButton.setText(Messages.wf_JRELabel);
// Add action listeners
jreButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
String currentVM = jreCombo.getText();
if (showPreferencePage()) {
updateJREs();
jreCombo.setItems(jreNames);
jreCombo.setText(currentVM);
if (jreCombo.getSelectionIndex() == -1)
jreCombo.select(defaultVMIndex);
jreComboIndex = jreCombo.getSelectionIndex();
updateErrorMessage();
}
}
});
jreCombo.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
updatePage();
}
public void widgetSelected(SelectionEvent e) {
updatePage();
}
});
// Set Layout Data
FormData labelData = new FormData();
FormData comboData = new FormData();
FormData buttonData = new FormData();
labelData.left = new FormAttachment(0, 0);
installedJRELabel.setLayoutData(labelData);
comboData.left = new FormAttachment(0, 5);
comboData.right = new FormAttachment(jreButton, -5);
comboData.top = new FormAttachment(installedJRELabel, 5);
jreCombo.setLayoutData(comboData);
buttonData.top = new FormAttachment(installedJRELabel, 5);
buttonData.right = new FormAttachment(100, 0);
jreButton.setLayoutData(buttonData);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createJREComposite" | "private void createJREComposite(Composite main) {
// Create our composite
jreComposite = new Composite(main, SWT.NONE);
FormData cData = new FormData();
cData.left = new FormAttachment(0, 5);
cData.right = new FormAttachment(100, -5);
cData.top = new FormAttachment(homeDirComposite, 10);
jreComposite.setLayoutData(cData);
jreComposite.setLayout(new FormLayout());
// Create Internal Widgets
installedJRELabel = new Label(jreComposite, SWT.NONE);
installedJRELabel.setText(Messages.wf_JRELabel);
jreCombo = new Combo(jreComposite, SWT.DROP_DOWN | SWT.READ_ONLY);
jreCombo.setItems(jreNames);
if( defaultVMIndex != -1 )
jreCombo.select(defaultVMIndex);
jreButton = new Button(jreComposite, SWT.NONE);
jreButton.setText(Messages.wf_JRELabel);
// Add action listeners
jreButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
String currentVM = jreCombo.getText();
if (showPreferencePage()) {
updateJREs();
<MASK>updateErrorMessage();</MASK>
jreCombo.setItems(jreNames);
jreCombo.setText(currentVM);
if (jreCombo.getSelectionIndex() == -1)
jreCombo.select(defaultVMIndex);
jreComboIndex = jreCombo.getSelectionIndex();
}
}
});
jreCombo.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
updatePage();
}
public void widgetSelected(SelectionEvent e) {
updatePage();
}
});
// Set Layout Data
FormData labelData = new FormData();
FormData comboData = new FormData();
FormData buttonData = new FormData();
labelData.left = new FormAttachment(0, 0);
installedJRELabel.setLayoutData(labelData);
comboData.left = new FormAttachment(0, 5);
comboData.right = new FormAttachment(jreButton, -5);
comboData.top = new FormAttachment(installedJRELabel, 5);
jreCombo.setLayoutData(comboData);
buttonData.top = new FormAttachment(installedJRELabel, 5);
buttonData.right = new FormAttachment(100, 0);
jreButton.setLayoutData(buttonData);
}" |
Inversion-Mutation | megadiff | "public void widgetSelected(SelectionEvent e) {
String currentVM = jreCombo.getText();
if (showPreferencePage()) {
updateJREs();
jreCombo.setItems(jreNames);
jreCombo.setText(currentVM);
if (jreCombo.getSelectionIndex() == -1)
jreCombo.select(defaultVMIndex);
jreComboIndex = jreCombo.getSelectionIndex();
updateErrorMessage();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "widgetSelected" | "public void widgetSelected(SelectionEvent e) {
String currentVM = jreCombo.getText();
if (showPreferencePage()) {
updateJREs();
<MASK>updateErrorMessage();</MASK>
jreCombo.setItems(jreNames);
jreCombo.setText(currentVM);
if (jreCombo.getSelectionIndex() == -1)
jreCombo.select(defaultVMIndex);
jreComboIndex = jreCombo.getSelectionIndex();
}
}" |
Inversion-Mutation | megadiff | "@Override
public boolean insertActions(ReconfigurationPlan plan) {
if (cSlice.getHoster().getVal() != dSlice.getHoster().getVal()) {
plan.add(new MigrateVM(vm,
rp.getNode(cSlice.getHoster().getVal()),
rp.getNode(dSlice.getHoster().getVal()),
getStart().getVal(),
getEnd().getVal()));
}
rp.insertAllocates(plan, vm, rp.getNode(dSlice.getHoster().getVal()), getEnd().getVal(), getEnd().getVal() + 1);
return true;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "insertActions" | "@Override
public boolean insertActions(ReconfigurationPlan plan) {
if (cSlice.getHoster().getVal() != dSlice.getHoster().getVal()) {
plan.add(new MigrateVM(vm,
rp.getNode(cSlice.getHoster().getVal()),
rp.getNode(dSlice.getHoster().getVal()),
getStart().getVal(),
getEnd().getVal()));
<MASK>rp.insertAllocates(plan, vm, rp.getNode(dSlice.getHoster().getVal()), getEnd().getVal(), getEnd().getVal() + 1);</MASK>
}
return true;
}" |
Inversion-Mutation | megadiff | "@Override
public Map<AbstractMetaDataWrapper, XMLFilter> getMetaDataWrappers() {
Map<AbstractMetaDataWrapper, XMLFilter> wrapperMap = new LinkedHashMap<AbstractMetaDataWrapper, XMLFilter>();
wrapperMap.put(new NaaSignedAipWrapNormaliser(), new NaaSignedAipUnwrapFilter());
wrapperMap.put(new NaaPackageWrapNormaliser(), new NaaPackageUnwrapFilter());
return wrapperMap;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getMetaDataWrappers" | "@Override
public Map<AbstractMetaDataWrapper, XMLFilter> getMetaDataWrappers() {
Map<AbstractMetaDataWrapper, XMLFilter> wrapperMap = new LinkedHashMap<AbstractMetaDataWrapper, XMLFilter>();
<MASK>wrapperMap.put(new NaaPackageWrapNormaliser(), new NaaPackageUnwrapFilter());</MASK>
wrapperMap.put(new NaaSignedAipWrapNormaliser(), new NaaSignedAipUnwrapFilter());
return wrapperMap;
}" |
Inversion-Mutation | megadiff | "public boolean changePassword(final String username, final String password) {
final Login loginUser = this.getLoginUser(username);
if (loginUser != null) {
this.em.getTransaction().begin();
loginUser.setPassword(password);
this.em.persist(loginUser);
this.em.getTransaction().commit();
return true;
} else {
return false;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "changePassword" | "public boolean changePassword(final String username, final String password) {
<MASK>this.em.getTransaction().begin();</MASK>
final Login loginUser = this.getLoginUser(username);
if (loginUser != null) {
loginUser.setPassword(password);
this.em.persist(loginUser);
this.em.getTransaction().commit();
return true;
} else {
return false;
}
}" |
Inversion-Mutation | megadiff | "public void internalRun() throws InterruptedException {
response.setRequestId(request.getRequestId());
Service service = services.get(request.getFullServiceName());
if (service == null) {
response.setError(Data.Response.RpcError.UNKNOWN_SERVICE);
output.put(response.build());
return;
}
Descriptors.MethodDescriptor method =
service.getDescriptorForType()
.findMethodByName(request.getMethodName());
if (method == null) {
response.setError(Data.Response.RpcError.UNKNOWN_METHOD);
output.put(response.build());
return;
}
Message requestMessage = null;
try {
requestMessage = service.getRequestPrototype(method)
.toBuilder().mergeFrom(request.getRequestProto()).build();
} catch (InvalidProtocolBufferException e) {
response.setError(Data.Response.RpcError.INVALID_PROTOBUF);
output.put(response.build());
return;
}
if (logger.isLoggable(Level.FINER)) {
logger.fine(String.format("I(%d) => %s(%s)",
request.getRequestId(),
method.getFullName(),
requestMessage));
}
service.callMethod(method, rpc, requestMessage, callback);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "internalRun" | "public void internalRun() throws InterruptedException {
Service service = services.get(request.getFullServiceName());
if (service == null) {
response.setError(Data.Response.RpcError.UNKNOWN_SERVICE);
output.put(response.build());
return;
}
Descriptors.MethodDescriptor method =
service.getDescriptorForType()
.findMethodByName(request.getMethodName());
if (method == null) {
response.setError(Data.Response.RpcError.UNKNOWN_METHOD);
output.put(response.build());
return;
}
Message requestMessage = null;
try {
requestMessage = service.getRequestPrototype(method)
.toBuilder().mergeFrom(request.getRequestProto()).build();
} catch (InvalidProtocolBufferException e) {
response.setError(Data.Response.RpcError.INVALID_PROTOBUF);
output.put(response.build());
return;
}
if (logger.isLoggable(Level.FINER)) {
logger.fine(String.format("I(%d) => %s(%s)",
request.getRequestId(),
method.getFullName(),
requestMessage));
}
<MASK>response.setRequestId(request.getRequestId());</MASK>
service.callMethod(method, rpc, requestMessage, callback);
}" |
Inversion-Mutation | megadiff | "private void adjustStatusBarLocked() {
if (mStatusBarManager == null) {
mStatusBarManager = (StatusBarManager)
mContext.getSystemService(Context.STATUS_BAR_SERVICE);
}
if (mStatusBarManager == null) {
Log.w(TAG, "Could not get status bar manager");
} else {
if (mShowLockIcon) {
// Give feedback to user when secure keyguard is active and engaged
if (mShowing && isSecure()) {
if (!mShowingLockIcon) {
mStatusBarManager.setIcon("secure",
com.android.internal.R.drawable.stat_sys_secure, 0);
mShowingLockIcon = true;
}
} else {
if (mShowingLockIcon) {
mStatusBarManager.removeIcon("secure");
mShowingLockIcon = false;
}
}
}
// Disable aspects of the system/status/navigation bars that must not be re-enabled by
// windows that appear on top, ever
int flags = StatusBarManager.DISABLE_NONE;
if (mShowing) {
flags |= StatusBarManager.DISABLE_NAVIGATION;
if (!mHidden) {
// showing lockscreen exclusively; disable various extra
// statusbar components.
flags |= StatusBarManager.DISABLE_CLOCK;
}
if (isSecure()) {
// showing secure lockscreen; disable expanding.
flags |= StatusBarManager.DISABLE_EXPAND;
}
}
mStatusBarManager.disable(flags);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "adjustStatusBarLocked" | "private void adjustStatusBarLocked() {
if (mStatusBarManager == null) {
mStatusBarManager = (StatusBarManager)
mContext.getSystemService(Context.STATUS_BAR_SERVICE);
}
if (mStatusBarManager == null) {
Log.w(TAG, "Could not get status bar manager");
} else {
if (mShowLockIcon) {
// Give feedback to user when secure keyguard is active and engaged
if (mShowing && isSecure()) {
if (!mShowingLockIcon) {
mStatusBarManager.setIcon("secure",
com.android.internal.R.drawable.stat_sys_secure, 0);
mShowingLockIcon = true;
}
} else {
if (mShowingLockIcon) {
mStatusBarManager.removeIcon("secure");
mShowingLockIcon = false;
}
}
}
// Disable aspects of the system/status/navigation bars that must not be re-enabled by
// windows that appear on top, ever
int flags = StatusBarManager.DISABLE_NONE;
if (mShowing) {
if (!mHidden) {
// showing lockscreen exclusively; disable various extra
// statusbar components.
<MASK>flags |= StatusBarManager.DISABLE_NAVIGATION;</MASK>
flags |= StatusBarManager.DISABLE_CLOCK;
}
if (isSecure()) {
// showing secure lockscreen; disable expanding.
flags |= StatusBarManager.DISABLE_EXPAND;
}
}
mStatusBarManager.disable(flags);
}
}" |
Inversion-Mutation | megadiff | "public static String nameDiscriminator(ViewElement element) {
String baseName = element.getName();
StringBuffer buffer = new StringBuffer();
EObject container = element.eContainer();
while (container instanceof ViewElement) {
if (((ViewElement)container).getName().equals(baseName)) {
buffer.append('_');
}
container = container.eContainer();
}
ViewsRepository repository = repository(container);
if (repository != null) {
if (repository.getName().equals(baseName)) {
buffer.append('_');
}
}
return buffer.toString();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "nameDiscriminator" | "public static String nameDiscriminator(ViewElement element) {
String baseName = element.getName();
StringBuffer buffer = new StringBuffer();
EObject container = element.eContainer();
while (container instanceof ViewElement) {
if (((ViewElement)container).getName().equals(baseName)) {
buffer.append('_');
<MASK>container = container.eContainer();</MASK>
}
}
ViewsRepository repository = repository(container);
if (repository != null) {
if (repository.getName().equals(baseName)) {
buffer.append('_');
}
}
return buffer.toString();
}" |
Inversion-Mutation | megadiff | "public void parse() throws IOException {
while (this.recognizer.hasNext()) {
this.read();
// System.out.println(this.current + " : " + this.lexeme);
// try {
// Thread.sleep(1);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
if (this.current == TEXT) {
while (this.current != CLOSEDTEXT) {
this.label = null;
this.read();
// System.out.println(this.current + " : " + this.lexeme);
// try {
// Thread.sleep(20);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// Remove lines at the beginning of text starting with # or
// _
if (this.current == OTHER && this.previous == TEXT) {
if (this.lexeme.equals("#") || this.lexeme.equals("_")) {
while (this.recognizer.hasNext()
&& this.current != CLOSEDTEXT
&& this.current != LINESEPARATOR) {
this.read();
}
}
}
// Remove headlines and listings
if (this.previous == LINESEPARATOR
&& (this.current == EQUALITYSIGN
|| this.current == COLON
|| this.current == ASTERISK
|| this.current == SEMICOLON
|| this.current == UNDERSCORE
|| this.current == EXCLAMATIONMARK || this.current == VERTICALBAR)) {
// equality sign or semicolon-->headline, colon or
// asterisk-->listing
while (this.current != CLOSEDTEXT
&& this.current != LINESEPARATOR) {
this.read();
}
}
if (this.previous == FULLSTOP
&& this.current == LINESEPARATOR) {
this.write(" ");
}
if (this.current == STRING) {
this.write(this.lexeme);
}
if (this.current == WS) {
this.write(" ");
}
if (this.current == QUESTIONMARK) {
this.write(this.lexeme);
}
if (this.current == EXCLAMATIONMARK) {
this.write(this.lexeme);
}
if (this.current == FULLSTOP) {
this.write(this.lexeme);
}
if (this.current == COMMA) {
this.write(this.lexeme);
}
if (this.current == SEMICOLON) {
this.write(this.lexeme);
}
if (this.current == COLON) {
this.write(": ");
}
if (this.current == QUOTATIONMARK) {
this.write("'");
}
if (this.current == HYPHEN) {
this.write("-");
}
if (this.current == AUDIO) {
this.write(this.lexeme);
}
if (this.current == LINESEPARATOR) {
this.write(" ");
}
// Recognize <ref>...</ref> inside a text block
if (this.current == REF) {
while (this.current != CLOSEDREF
&& this.current != CLOSEDTEXT) {
this.read();
}
}
// Recognize <...>...</...> inside a text block
if (this.current == ELEMENT) {
while (this.current != CLOSEDELEMENT
&& this.current != CLOSEDTEXT) {
this.read();
}
}
// Recognize <!--...--> inside a text block
if (this.current == EHH) {
while (this.current != GREATERTHAN
&& this.previous != HH
&& this.current != CLOSEDTEXT) {
this.read();
}
}
// Recognize (...)
if (this.current == BRACKET) {
this.bracketCount = 1;
while (this.bracketCount != 0
&& this.current != CLOSEDTEXT) {
this.read();
if (this.current == BRACKET) {
this.bracketCount++;
}
if (this.current == CLOSEDBRACKET) {
this.bracketCount--;
}
}
}
// Recognize {...}
if (this.current == CURLYBRACKET) {
this.linkLabel = "";
this.bracketCount = 1;
while (this.bracketCount != 0
&& this.current != CLOSEDTEXT) {
this.read();
if (this.current == CURLYBRACKET) {
this.bracketCount++;
}
if (this.current == CLOSEDCURLYBRACKET) {
this.bracketCount--;
}
if (this.current == STRING
&& this.disambiguations
.contains(this.lexeme)) {
this.writer.write("<DISAMBIGUATION>");
}
if (this.previous == CURLYBRACKET
&& this.current == STRING
&& this.lexeme.contains("TOC")) {
this.writer.write("<TOC>");
}
if (this.previous == CURLYBRACKET
&& this.current == STRING
&& this.lexeme.contains("Wikipedia")) {
this.writer.write("<DISAMBIGUATION>");
}
if (this.current == STRING) {
this.linkLabel += this.lexeme;
}
if (this.current == WS) {
this.linkLabel += " ";
}
if (this.current == QUESTIONMARK) {
this.linkLabel += "?";
}
if (this.current == EXCLAMATIONMARK) {
this.linkLabel += "!";
}
if (this.current == HYPHEN) {
this.linkLabel += "-";
}
// Recognize {{Audio|...}}
if (this.previous == CURLYBRACKET
&& this.lexeme.equals("Audio")) {
this.label = AUDIO;
}
if (this.label == AUDIO
&& this.current == VERTICALBAR) {
this.linkLabel = "";
}
}
if (this.bracketCount == 0) {
if (this.label == AUDIO) {
this.writer.write(this.linkLabel);
}
}
}
// Recognize [...]
if (this.current == SQUAREDBRACKET) {
this.bracketCount = 1;
this.verticalBarCount = 0;
// this.link = "";
this.linkLabel = "";
while (this.bracketCount != 0
&& this.current != CLOSEDTEXT) {
this.read();
if (this.current == SQUAREDBRACKET) {
this.bracketCount++;
}
if (this.current == CLOSEDSQUAREDBRACKET) {
this.bracketCount--;
}
if (this.bracketCount > 2) {
this.label = OTHER;
}
if (this.bracketCount == 2 && this.label != OTHER) {
this.label = LINK;
// inside a valid link
if (this.current == STRING) {
this.linkLabel += this.lexeme;
}
if (this.current == WS) {
this.linkLabel += " ";
}
if (this.current == HYPHEN) {
this.linkLabel += "-";
}
if (this.current == VERTICALBAR) {
this.verticalBarCount++;
// this.link = this.lexeme.substring(2,
// this.lexeme.length() - 1);
this.linkLabel = "";
}
if (this.current == COLON) {
// Recognize [[lang:language]]
this.label = OTHER;
}
}
}
if (this.label == LINK && this.bracketCount == 0
&& this.verticalBarCount < 2) {
this.write(this.linkLabel);
// this could be usefull for building the
// WikipediaLinkExtractor
// if (this.label == LINK) {
// if (this.verticalBarCount == 1) {
// LABELEDLINK;
// } else {
// LINK;
// }
// }
}
}
}
this.write("\n");// new line after page
}
}
this.recognizer.close();
this.writer.close();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "parse" | "public void parse() throws IOException {
while (this.recognizer.hasNext()) {
this.read();
// System.out.println(this.current + " : " + this.lexeme);
// try {
// Thread.sleep(1);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
if (this.current == TEXT) {
while (this.current != CLOSEDTEXT) {
this.label = null;
this.read();
// System.out.println(this.current + " : " + this.lexeme);
// try {
// Thread.sleep(20);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// Remove lines at the beginning of text starting with # or
// _
if (this.current == OTHER && this.previous == TEXT) {
if (this.lexeme.equals("#") || this.lexeme.equals("_")) {
while (this.recognizer.hasNext()
&& this.current != CLOSEDTEXT
&& this.current != LINESEPARATOR) {
this.read();
}
}
}
// Remove headlines and listings
if (this.previous == LINESEPARATOR
&& (this.current == EQUALITYSIGN
|| this.current == COLON
|| this.current == ASTERISK
|| this.current == SEMICOLON
|| this.current == UNDERSCORE
|| this.current == EXCLAMATIONMARK || this.current == VERTICALBAR)) {
// equality sign or semicolon-->headline, colon or
// asterisk-->listing
while (this.current != CLOSEDTEXT
&& this.current != LINESEPARATOR) {
this.read();
}
}
if (this.previous == FULLSTOP
&& this.current == LINESEPARATOR) {
this.write(" ");
}
if (this.current == STRING) {
this.write(this.lexeme);
}
if (this.current == WS) {
this.write(" ");
}
if (this.current == QUESTIONMARK) {
this.write(this.lexeme);
}
if (this.current == EXCLAMATIONMARK) {
this.write(this.lexeme);
}
if (this.current == FULLSTOP) {
this.write(this.lexeme);
}
if (this.current == COMMA) {
this.write(this.lexeme);
}
if (this.current == SEMICOLON) {
this.write(this.lexeme);
}
if (this.current == COLON) {
this.write(": ");
}
if (this.current == QUOTATIONMARK) {
this.write("'");
}
if (this.current == HYPHEN) {
this.write("-");
}
if (this.current == AUDIO) {
this.write(this.lexeme);
}
if (this.current == LINESEPARATOR) {
this.write(" ");
}
// Recognize <ref>...</ref> inside a text block
if (this.current == REF) {
while (this.current != CLOSEDREF
&& this.current != CLOSEDTEXT) {
this.read();
}
}
// Recognize <...>...</...> inside a text block
if (this.current == ELEMENT) {
while (this.current != CLOSEDELEMENT
&& this.current != CLOSEDTEXT) {
this.read();
}
}
// Recognize <!--...--> inside a text block
if (this.current == EHH) {
while (this.current != GREATERTHAN
&& this.previous != HH
&& this.current != CLOSEDTEXT) {
this.read();
}
}
// Recognize (...)
if (this.current == BRACKET) {
this.bracketCount = 1;
while (this.bracketCount != 0
&& this.current != CLOSEDTEXT) {
this.read();
if (this.current == BRACKET) {
this.bracketCount++;
}
if (this.current == CLOSEDBRACKET) {
this.bracketCount--;
}
}
}
// Recognize {...}
if (this.current == CURLYBRACKET) {
this.linkLabel = "";
this.bracketCount = 1;
while (this.bracketCount != 0
&& this.current != CLOSEDTEXT) {
this.read();
if (this.current == CURLYBRACKET) {
this.bracketCount++;
}
if (this.current == CLOSEDCURLYBRACKET) {
this.bracketCount--;
}
if (this.current == STRING
&& this.disambiguations
.contains(this.lexeme)) {
this.writer.write("<DISAMBIGUATION>");
}
if (this.previous == CURLYBRACKET
&& this.current == STRING
&& this.lexeme.contains("TOC")) {
this.writer.write("<TOC>");
}
if (this.previous == CURLYBRACKET
&& this.current == STRING
&& this.lexeme.contains("Wikipedia")) {
this.writer.write("<DISAMBIGUATION>");
}
if (this.current == STRING) {
this.linkLabel += this.lexeme;
}
if (this.current == WS) {
this.linkLabel += " ";
}
if (this.current == QUESTIONMARK) {
this.linkLabel += "?";
}
if (this.current == EXCLAMATIONMARK) {
this.linkLabel += "!";
}
if (this.current == HYPHEN) {
this.linkLabel += "-";
}
// Recognize {{Audio|...}}
if (this.previous == CURLYBRACKET
&& this.lexeme.equals("Audio")) {
this.label = AUDIO;
}
if (this.label == AUDIO
&& this.current == VERTICALBAR) {
this.linkLabel = "";
}
}
if (this.bracketCount == 0) {
if (this.label == AUDIO) {
this.writer.write(this.linkLabel);
}
}
}
// Recognize [...]
if (this.current == SQUAREDBRACKET) {
this.bracketCount = 1;
this.verticalBarCount = 0;
// this.link = "";
this.linkLabel = "";
while (this.bracketCount != 0
&& this.current != CLOSEDTEXT) {
this.read();
if (this.current == SQUAREDBRACKET) {
this.bracketCount++;
}
if (this.current == CLOSEDSQUAREDBRACKET) {
this.bracketCount--;
}
if (this.bracketCount > 2) {
this.label = OTHER;
}
if (this.bracketCount == 2 && this.label != OTHER) {
this.label = LINK;
// inside a valid link
if (this.current == STRING) {
this.linkLabel += this.lexeme;
}
if (this.current == WS) {
this.linkLabel += " ";
}
if (this.current == HYPHEN) {
this.linkLabel += "-";
}
if (this.current == VERTICALBAR) {
this.verticalBarCount++;
// this.link = this.lexeme.substring(2,
// this.lexeme.length() - 1);
this.linkLabel = "";
}
if (this.current == COLON) {
// Recognize [[lang:language]]
this.label = OTHER;
}
}
}
if (this.label == LINK && this.bracketCount == 0
&& this.verticalBarCount < 2) {
this.write(this.linkLabel);
// this could be usefull for building the
// WikipediaLinkExtractor
// if (this.label == LINK) {
// if (this.verticalBarCount == 1) {
// LABELEDLINK;
// } else {
// LINK;
// }
// }
}
}
}
this.write("\n");// new line after page
<MASK>this.recognizer.close();</MASK>
}
}
this.writer.close();
}" |
Inversion-Mutation | megadiff | "public ClientHub(String ip, int port, long id) throws IOException {
super(id);
cmdChain = new Commands.CmdConnect(this);
cmdChain.append(
new Commands.CmdDisconnect(this)).append(
new Commands.CmdMsg(this));
comm = new ClientComm(ip, port, this);
addConnection(new BroadcastConnection(this));
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "ClientHub" | "public ClientHub(String ip, int port, long id) throws IOException {
super(id);
<MASK>comm = new ClientComm(ip, port, this);</MASK>
cmdChain = new Commands.CmdConnect(this);
cmdChain.append(
new Commands.CmdDisconnect(this)).append(
new Commands.CmdMsg(this));
addConnection(new BroadcastConnection(this));
}" |
Inversion-Mutation | megadiff | "public MainDonateEvent() {
super(null, 0, 0,
FreeDonateEvent.instance(),
LifeDonateEvent.instance(),
AuthDonateEvent.instance(),
PaidDonateEvent.instance(),
CadpageDonateEvent.instance(),
SponsorDonateEvent.instance(),
DonateExemptEvent.instance(),
PaidWarnDonateEvent.instance(),
PaidExpireDonateEvent.instance(),
DemoDonateEvent.instance(),
DemoExpireDonateEvent.instance());
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "MainDonateEvent" | "public MainDonateEvent() {
super(null, 0, 0,
FreeDonateEvent.instance(),
LifeDonateEvent.instance(),
AuthDonateEvent.instance(),
CadpageDonateEvent.instance(),
SponsorDonateEvent.instance(),
<MASK>PaidDonateEvent.instance(),</MASK>
DonateExemptEvent.instance(),
PaidWarnDonateEvent.instance(),
PaidExpireDonateEvent.instance(),
DemoDonateEvent.instance(),
DemoExpireDonateEvent.instance());
}" |
Inversion-Mutation | megadiff | "private RelTypeElement( String type, NodeImpl node, IntArray src,
IntArray add, IntArray remove )
{
super( type, node );
if ( src == null )
{
src = IntArray.EMPTY;
srcTraversed = true;
}
this.src = src;
if ( add == null )
{
addTraversed = true;
}
this.add = add;
if ( remove != null )
{
for ( int i = 0; i < remove.length(); i++ )
{
this.remove.add( remove.get( i ) );
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "RelTypeElement" | "private RelTypeElement( String type, NodeImpl node, IntArray src,
IntArray add, IntArray remove )
{
super( type, node );
<MASK>this.src = src;</MASK>
if ( src == null )
{
src = IntArray.EMPTY;
srcTraversed = true;
}
if ( add == null )
{
addTraversed = true;
}
this.add = add;
if ( remove != null )
{
for ( int i = 0; i < remove.length(); i++ )
{
this.remove.add( remove.get( i ) );
}
}
}" |
Inversion-Mutation | megadiff | "public static void startAgents(IThreadContext threadContext)
throws ManifoldCFException
{
// Get agent manager
IAgentManager manager = AgentManagerFactory.make(threadContext);
ManifoldCFException problem = null;
synchronized (runningHash)
{
// DO NOT permit this method to do anything if stopAgents() has ever been called for this JVM!
// (If it has, it means that the JVM is trying to shut down.)
if (stopAgentsRun)
return;
String[] classes = manager.getAllAgents();
int i = 0;
while (i < classes.length)
{
String className = classes[i++];
if (runningHash.get(className) == null)
{
// Start this agent
IAgent agent = AgentFactory.make(threadContext,className);
try
{
// There is a potential race condition where the agent has been started but hasn't yet appeared in runningHash.
// But having runningHash be the synchronizer for this activity will prevent any problems.
// There is ANOTHER potential race condition, however, that can occur if the process is shut down just before startAgents() is called.
// We avoid that problem by means of a flag, which prevents startAgents() from doing anything once stopAgents() has been called.
agent.startAgent();
// Successful!
runningHash.put(className,agent);
}
catch (ManifoldCFException e)
{
problem = e;
}
}
}
}
if (problem != null)
throw problem;
// Done.
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "startAgents" | "public static void startAgents(IThreadContext threadContext)
throws ManifoldCFException
{
// Get agent manager
IAgentManager manager = AgentManagerFactory.make(threadContext);
<MASK>String[] classes = manager.getAllAgents();</MASK>
ManifoldCFException problem = null;
synchronized (runningHash)
{
// DO NOT permit this method to do anything if stopAgents() has ever been called for this JVM!
// (If it has, it means that the JVM is trying to shut down.)
if (stopAgentsRun)
return;
int i = 0;
while (i < classes.length)
{
String className = classes[i++];
if (runningHash.get(className) == null)
{
// Start this agent
IAgent agent = AgentFactory.make(threadContext,className);
try
{
// There is a potential race condition where the agent has been started but hasn't yet appeared in runningHash.
// But having runningHash be the synchronizer for this activity will prevent any problems.
// There is ANOTHER potential race condition, however, that can occur if the process is shut down just before startAgents() is called.
// We avoid that problem by means of a flag, which prevents startAgents() from doing anything once stopAgents() has been called.
agent.startAgent();
// Successful!
runningHash.put(className,agent);
}
catch (ManifoldCFException e)
{
problem = e;
}
}
}
}
if (problem != null)
throw problem;
// Done.
}" |
Inversion-Mutation | megadiff | "@Override
public void storeRepresentation(Representation entity)
throws ResourceException {
final Form form = new Form(entity);
final List<String> mailAddresses = new ArrayList<String>();
for (final Parameter parameter : form.subList("recipients")) {
mailAddresses.add(parameter.getValue());
}
List<String> tags = null;
if (form.getFirstValue("tags") != null) {
tags = new ArrayList<String>(Arrays.asList(form.getFirstValue(
"tags").split(" ")));
}
getObjectsFacade().updateMail(this.mailbox, this.mail,
form.getFirstValue("status"), form.getFirstValue("subject"),
form.getFirstValue("message"), mailAddresses, tags);
// Detect if the mail is to be sent.
if (Mail.STATUS_SENDING.equalsIgnoreCase(this.mail.getStatus())) {
this.mail.setSendingDate(new Date());
// Loop on the list of recipients and post to their mailbox.
boolean success = true;
if (this.mail.getRecipients() != null) {
final Client client = new Client(Protocol.HTTP);
final Form form2 = new Form();
form2.add("status", Mail.STATUS_RECEIVING);
form2.add("senderAddress", getRequest().getRootRef()
+ "/mailboxes/" + this.mailbox.getId());
form2.add("senderName", this.mailbox.getSenderName());
form2.add("subject", this.mail.getSubject());
form2.add("message", this.mail.getMessage());
form2.add("sendingDate", this.mail.getSendingDate().toString());
for (final Contact recipient : this.mail.getRecipients()) {
form2.add("recipient", recipient.getMailAddress() + "$"
+ recipient.getName());
}
// Send the mail to every recipient
final StringBuilder builder = new StringBuilder();
Response response;
final Request request = new Request();
request.setMethod(Method.POST);
for (final Contact contact : this.mail.getRecipients()) {
request.setResourceRef(contact.getMailAddress());
request.setEntity(form2.getWebRepresentation());
response = client.handle(request);
// Error when sending the mail.
if (!response.getStatus().isSuccess()) {
success = false;
builder.append(contact.getName());
builder.append("\t");
builder.append(response.getStatus());
}
}
if (success) {
// if the mail has been successfully sent to every
// recipient.
this.mail.setStatus(Mail.STATUS_SENT);
getObjectsFacade().updateMail(this.mailbox, this.mail);
getResponse().redirectSeeOther(
getRequest().getResourceRef());
} else {
// At least one error has been encountered.
final Map<String, Object> dataModel = new TreeMap<String, Object>();
dataModel.put("currentUser", getCurrentUser());
dataModel.put("mailbox", this.mailbox);
dataModel.put("mail", this.mail);
dataModel.put("resourceRef", getRequest().getResourceRef());
dataModel.put("rootRef", getRequest().getRootRef());
dataModel.put("message", builder.toString());
getResponse().setEntity(
getHTMLTemplateRepresentation("mail_"
+ this.mail.getStatus() + ".html",
dataModel));
}
} else {
// Still a draft
this.mail.setStatus(Mail.STATUS_DRAFT);
getObjectsFacade().updateMail(this.mailbox, this.mail);
getResponse().redirectSeeOther(getRequest().getResourceRef());
}
} else {
getResponse().redirectSeeOther(getRequest().getResourceRef());
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "storeRepresentation" | "@Override
public void storeRepresentation(Representation entity)
throws ResourceException {
final Form form = new Form(entity);
final List<String> mailAddresses = new ArrayList<String>();
for (final Parameter parameter : form.subList("recipients")) {
mailAddresses.add(parameter.getValue());
}
List<String> tags = null;
if (form.getFirstValue("tags") != null) {
tags = new ArrayList<String>(Arrays.asList(form.getFirstValue(
"tags").split(" ")));
}
getObjectsFacade().updateMail(this.mailbox, this.mail,
form.getFirstValue("status"), form.getFirstValue("subject"),
form.getFirstValue("message"), mailAddresses, tags);
// Detect if the mail is to be sent.
if (Mail.STATUS_SENDING.equalsIgnoreCase(this.mail.getStatus())) {
this.mail.setSendingDate(new Date());
// Loop on the list of recipients and post to their mailbox.
boolean success = true;
if (this.mail.getRecipients() != null) {
final Client client = new Client(Protocol.HTTP);
final Form form2 = new Form();
form2.add("status", Mail.STATUS_RECEIVING);
form2.add("senderAddress", getRequest().getRootRef()
+ "/mailboxes/" + this.mailbox.getId());
form2.add("senderName", this.mailbox.getSenderName());
form2.add("subject", this.mail.getSubject());
form2.add("message", this.mail.getMessage());
form2.add("sendingDate", this.mail.getSendingDate().toString());
for (final Contact recipient : this.mail.getRecipients()) {
form2.add("recipient", recipient.getMailAddress() + "$"
+ recipient.getName());
}
// Send the mail to every recipient
final StringBuilder builder = new StringBuilder();
Response response;
final Request request = new Request();
request.setMethod(Method.POST);
<MASK>request.setEntity(form2.getWebRepresentation());</MASK>
for (final Contact contact : this.mail.getRecipients()) {
request.setResourceRef(contact.getMailAddress());
response = client.handle(request);
// Error when sending the mail.
if (!response.getStatus().isSuccess()) {
success = false;
builder.append(contact.getName());
builder.append("\t");
builder.append(response.getStatus());
}
}
if (success) {
// if the mail has been successfully sent to every
// recipient.
this.mail.setStatus(Mail.STATUS_SENT);
getObjectsFacade().updateMail(this.mailbox, this.mail);
getResponse().redirectSeeOther(
getRequest().getResourceRef());
} else {
// At least one error has been encountered.
final Map<String, Object> dataModel = new TreeMap<String, Object>();
dataModel.put("currentUser", getCurrentUser());
dataModel.put("mailbox", this.mailbox);
dataModel.put("mail", this.mail);
dataModel.put("resourceRef", getRequest().getResourceRef());
dataModel.put("rootRef", getRequest().getRootRef());
dataModel.put("message", builder.toString());
getResponse().setEntity(
getHTMLTemplateRepresentation("mail_"
+ this.mail.getStatus() + ".html",
dataModel));
}
} else {
// Still a draft
this.mail.setStatus(Mail.STATUS_DRAFT);
getObjectsFacade().updateMail(this.mailbox, this.mail);
getResponse().redirectSeeOther(getRequest().getResourceRef());
}
} else {
getResponse().redirectSeeOther(getRequest().getResourceRef());
}
}" |
Inversion-Mutation | megadiff | "@Override
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
super.run(monitor);
}
finally {
// Once upload is successful, synchronize the modified time.
for (int i = 0; i < nodes.length; i++) {
final FSTreeNode node = nodes[i];
SafeRunner.run(new ISafeRunnable() {
@Override
public void handleException(Throwable e) {
// Ignore exception
}
@Override
public void run() throws Exception {
StateManager.getInstance().refreshState(node);
PersistenceManager.getInstance().setBaseTimestamp(node.getLocationURI(), node.attr.mtime);
if (sync) {
File file = CacheManager.getInstance().getCacheFile(node);
setLastModifiedChecked(file, node.attr.mtime);
}
}
});
}
monitor.done();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run" | "@Override
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
super.run(monitor);
}
finally {
// Once upload is successful, synchronize the modified time.
for (int i = 0; i < nodes.length; i++) {
final FSTreeNode node = nodes[i];
SafeRunner.run(new ISafeRunnable() {
@Override
public void handleException(Throwable e) {
// Ignore exception
}
@Override
public void run() throws Exception {
PersistenceManager.getInstance().setBaseTimestamp(node.getLocationURI(), node.attr.mtime);
if (sync) {
File file = CacheManager.getInstance().getCacheFile(node);
setLastModifiedChecked(file, node.attr.mtime);
}
<MASK>StateManager.getInstance().refreshState(node);</MASK>
}
});
}
monitor.done();
}
}" |
Inversion-Mutation | megadiff | "@Override
public void run() throws Exception {
StateManager.getInstance().refreshState(node);
PersistenceManager.getInstance().setBaseTimestamp(node.getLocationURI(), node.attr.mtime);
if (sync) {
File file = CacheManager.getInstance().getCacheFile(node);
setLastModifiedChecked(file, node.attr.mtime);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run" | "@Override
public void run() throws Exception {
PersistenceManager.getInstance().setBaseTimestamp(node.getLocationURI(), node.attr.mtime);
if (sync) {
File file = CacheManager.getInstance().getCacheFile(node);
setLastModifiedChecked(file, node.attr.mtime);
}
<MASK>StateManager.getInstance().refreshState(node);</MASK>
}" |
Inversion-Mutation | megadiff | "protected void addField(String name, JsonNode elementNode, ServiceTask task) {
FieldExtension field = new FieldExtension();
field.setFieldName(name.substring(8));
String value = getPropertyValueAsString(name, elementNode);
if (StringUtils.isNotEmpty(value)) {
if ((value.contains("${") || value.contains("#{")) && value.contains("}")) {
field.setExpression(value);
} else {
field.setStringValue(value);
}
task.getFieldExtensions().add(field);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addField" | "protected void addField(String name, JsonNode elementNode, ServiceTask task) {
FieldExtension field = new FieldExtension();
field.setFieldName(name.substring(8));
String value = getPropertyValueAsString(name, elementNode);
if (StringUtils.isNotEmpty(value)) {
if ((value.contains("${") || value.contains("#{")) && value.contains("}")) {
field.setExpression(value);
} else {
field.setStringValue(value);
}
}
<MASK>task.getFieldExtensions().add(field);</MASK>
}" |
Inversion-Mutation | megadiff | "private void processTagStart(XmlPullParser parser, boolean isempty) {
if (justended) {
// avoid the pathological case where we have for example
// <td class="tmiblock1" rsf:id="tmiblock:"></td><td> which makes it
// hard to spot run ends on the basis of recursion uncession.
justended = false;
XMLLump backlump = newLump(parser);
backlump.nestingdepth--;
setLumpChars(backlump, null, 0, 0);
}
XMLLump headlump = newLump(parser);
if (roottagindex == -1)
roottagindex = headlump.lumpindex;
String tagname = parser.getName();
// standard text of |<tagname | to allow easy identification.
setLumpString(headlump, XMLLump.tagToText(tagname));
// HashMap forwardmap = new HashMap();
// headlump.forwardmap = forwardmap;
// current policy - every open tag gets a forwardmap, and separate lumps.
// eventually we only want a lump where there is an rsf:id.
int attrs = parser.getAttributeCount();
if (attrs > 0) {
headlump.attributemap = new HashMap(attrs < 3? (attrs + 1)*2 : attrs * 2);
for (int i = 0; i < attrs; ++i) {
String attrname = parser.getAttributeName(i);
String attrvalue = parser.getAttributeValue(i);
headlump.attributemap.put(attrname, attrvalue);
}
if (parseinterceptors != null) {
for (int i = 0; i < parseinterceptors.size(); ++i) {
TemplateParseInterceptor parseinterceptor = (TemplateParseInterceptor) parseinterceptors
.get(i);
parseinterceptor.adjustAttributes(tagname, headlump.attributemap);
}
}
boolean firstattr = true;
for (Iterator keyit = headlump.attributemap.keySet().iterator(); keyit
.hasNext();) {
String attrname = (String) keyit.next();
String attrvalue = (String) headlump.attributemap.get(attrname);
XMLLump frontlump = newLump(parser);
CharWrap lumpac = new CharWrap();
if (!firstattr) {
lumpac.append("\" ");
}
firstattr = false;
lumpac.append(attrname).append("=\"");
setLumpChars(frontlump, lumpac.storage, 0, lumpac.size);
// frontlump holds |" name="|
// valuelump just holds the value.
XMLLump valuelump = newLump(parser);
setLumpString(valuelump, attrvalue);
if (attrname.equals(XMLLump.ID_ATTRIBUTE)) {
String ID = attrvalue;
if (ID.startsWith(XMLLump.FORID_PREFIX)
&& ID.endsWith(XMLLump.FORID_SUFFIX)) {
ID = ID.substring(0, ID.length() - XMLLump.FORID_SUFFIX.length());
}
headlump.rsfID = ID;
XMLLump stacktop = findTopContainer();
stacktop.downmap.addLump(ID, headlump);
globalmap.addLump(ID, headlump);
SplitID split = new SplitID(ID);
if (split.prefix.equals(XMLLump.FORID_PREFIX)) {
// no special note, just prevent suffix logic.
}
// we need really to be able to locate 3 levels of id -
// for-message:message:to
// ideally we would also like to be able to locate repetition
// constructs too, hopefully the standard suffix-based computation
// will allow this. However we previously never allowed BOTH
// repetitious and non-repetitious constructs to share the same
// prefix, so revisit this to solve.
// }
else if (split.suffix != null) {
// a repetitive tag is found.
headlump.downmap = new XMLLumpMMap();
// Repetitions within a SCOPE should be UNIQUE and CONTIGUOUS.
XMLLump prevlast = stacktop.downmap.getFinal(split.prefix);
stacktop.downmap.setFinal(split.prefix, headlump);
if (prevlast != null) {
// only store transitions from non-initial state -
// TODO: see if transition system will ever be needed.
String prevsuffix = SplitID.getSuffix(prevlast.rsfID);
String transitionkey = split.prefix + SplitID.SEPARATOR
+ prevsuffix + XMLLump.TRANSITION_SEPARATOR + split.suffix;
stacktop.downmap.addLump(transitionkey, prevlast);
globalmap.addLump(transitionkey, prevlast);
}
}
} // end if rsf:id attribute
} // end for each attribute
}
XMLLump finallump = newLump(parser);
String closetext = attrs == 0 ? (isempty ? "/>"
: ">")
: (isempty ? "\"/>"
: "\">");
setLumpString(finallump, closetext);
headlump.open_end = finallump;
tagstack.add(nestingdepth, headlump);
if (isempty) {
processTagEnd(parser);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "processTagStart" | "private void processTagStart(XmlPullParser parser, boolean isempty) {
if (justended) {
// avoid the pathological case where we have for example
// <td class="tmiblock1" rsf:id="tmiblock:"></td><td> which makes it
// hard to spot run ends on the basis of recursion uncession.
justended = false;
XMLLump backlump = newLump(parser);
backlump.nestingdepth--;
setLumpChars(backlump, null, 0, 0);
}
XMLLump headlump = newLump(parser);
if (roottagindex == -1)
roottagindex = headlump.lumpindex;
String tagname = parser.getName();
// standard text of |<tagname | to allow easy identification.
setLumpString(headlump, XMLLump.tagToText(tagname));
// HashMap forwardmap = new HashMap();
// headlump.forwardmap = forwardmap;
// current policy - every open tag gets a forwardmap, and separate lumps.
// eventually we only want a lump where there is an rsf:id.
int attrs = parser.getAttributeCount();
if (attrs > 0) {
headlump.attributemap = new HashMap(attrs < 3? (attrs + 1)*2 : attrs * 2);
for (int i = 0; i < attrs; ++i) {
String attrname = parser.getAttributeName(i);
String attrvalue = parser.getAttributeValue(i);
headlump.attributemap.put(attrname, attrvalue);
}
if (parseinterceptors != null) {
for (int i = 0; i < parseinterceptors.size(); ++i) {
TemplateParseInterceptor parseinterceptor = (TemplateParseInterceptor) parseinterceptors
.get(i);
parseinterceptor.adjustAttributes(tagname, headlump.attributemap);
}
}
boolean firstattr = true;
for (Iterator keyit = headlump.attributemap.keySet().iterator(); keyit
.hasNext();) {
String attrname = (String) keyit.next();
String attrvalue = (String) headlump.attributemap.get(attrname);
XMLLump frontlump = newLump(parser);
CharWrap lumpac = new CharWrap();
if (!firstattr) {
lumpac.append("\" ");
<MASK>firstattr = false;</MASK>
}
lumpac.append(attrname).append("=\"");
setLumpChars(frontlump, lumpac.storage, 0, lumpac.size);
// frontlump holds |" name="|
// valuelump just holds the value.
XMLLump valuelump = newLump(parser);
setLumpString(valuelump, attrvalue);
if (attrname.equals(XMLLump.ID_ATTRIBUTE)) {
String ID = attrvalue;
if (ID.startsWith(XMLLump.FORID_PREFIX)
&& ID.endsWith(XMLLump.FORID_SUFFIX)) {
ID = ID.substring(0, ID.length() - XMLLump.FORID_SUFFIX.length());
}
headlump.rsfID = ID;
XMLLump stacktop = findTopContainer();
stacktop.downmap.addLump(ID, headlump);
globalmap.addLump(ID, headlump);
SplitID split = new SplitID(ID);
if (split.prefix.equals(XMLLump.FORID_PREFIX)) {
// no special note, just prevent suffix logic.
}
// we need really to be able to locate 3 levels of id -
// for-message:message:to
// ideally we would also like to be able to locate repetition
// constructs too, hopefully the standard suffix-based computation
// will allow this. However we previously never allowed BOTH
// repetitious and non-repetitious constructs to share the same
// prefix, so revisit this to solve.
// }
else if (split.suffix != null) {
// a repetitive tag is found.
headlump.downmap = new XMLLumpMMap();
// Repetitions within a SCOPE should be UNIQUE and CONTIGUOUS.
XMLLump prevlast = stacktop.downmap.getFinal(split.prefix);
stacktop.downmap.setFinal(split.prefix, headlump);
if (prevlast != null) {
// only store transitions from non-initial state -
// TODO: see if transition system will ever be needed.
String prevsuffix = SplitID.getSuffix(prevlast.rsfID);
String transitionkey = split.prefix + SplitID.SEPARATOR
+ prevsuffix + XMLLump.TRANSITION_SEPARATOR + split.suffix;
stacktop.downmap.addLump(transitionkey, prevlast);
globalmap.addLump(transitionkey, prevlast);
}
}
} // end if rsf:id attribute
} // end for each attribute
}
XMLLump finallump = newLump(parser);
String closetext = attrs == 0 ? (isempty ? "/>"
: ">")
: (isempty ? "\"/>"
: "\">");
setLumpString(finallump, closetext);
headlump.open_end = finallump;
tagstack.add(nestingdepth, headlump);
if (isempty) {
processTagEnd(parser);
}
}" |