merge all into single repo

This commit is contained in:
fixminer
2020-04-06 20:40:32 +02:00
parent 9dcdb6aafc
commit 3c91dd7ea3
524 changed files with 1272301 additions and 1531 deletions
+163
View File
@@ -0,0 +1,163 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>edu.lu.uni.serval</groupId>
<artifactId>RichEdit</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<name>RichEdit</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<akka.version>2.4.17</akka.version>
<logback.version>1.1.2</logback.version>
<slf4j-api.version>1.7.7</slf4j-api.version>
<gumtree.version>2.0.0-SNAPSHOT</gumtree.version>
<junit.version>4.12</junit.version>
<redis.version>2.8.1</redis.version>
<commons.version>1.3</commons.version>
<commons-io.version>2.4</commons-io.version>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.javatuples/javatuples -->
<dependency>
<groupId>org.javatuples</groupId>
<artifactId>javatuples</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>me.tongfei</groupId>
<artifactId>progressbar</artifactId>
<version>0.8.1</version>
</dependency>
<!-- akka -->
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-actor_2.11</artifactId>
<version>${akka.version}</version>
</dependency>
<dependency>
<groupId>com.github.gumtreediff</groupId>
<artifactId>core</artifactId>
<scope>compile</scope>
<version>${gumtree.version}</version>
</dependency>
<dependency>
<groupId>com.github.gumtreediff</groupId>
<artifactId>gen.jdt</artifactId>
<scope>compile</scope>
<version>${gumtree.version}</version>
</dependency>
<dependency>
<groupId>com.github.gumtreediff</groupId>
<artifactId>gen.srcml</artifactId>
<scope>compile</scope>
<version>${gumtree.version}</version>
</dependency>
<!-- SLF4J - API -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j-api.version}</version>
</dependency>
<!-- logback -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<!-- <scope>test</scope>-->
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>${redis.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-text -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>${commons.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<archive>
<manifest>
<mainClass>
<!--edu.lu.uni.serval.fixminer.jobs.CompareTrees-->
edu.lu.uni.serval.fixminer.Launcher
</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
<!--edu.lu.uni.serval.fixminer.Launcher
edu.lu.uni.serval.fixminer.jobs.CompareTrees
edu.lu.uni.serval.utils.ClusterToPattern
-->
@@ -0,0 +1,134 @@
package edu.lu.uni.serval.fixminer;
import edu.lu.uni.serval.fixminer.jobs.CompareTrees;
import edu.lu.uni.serval.fixminer.jobs.EnhancedASTDiff;
import edu.lu.uni.serval.utils.ClusterToPattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Properties;
/**
* Created by anilkoyuncu on 14/04/2018.
*/
public class Launcher {
private static Logger log = LoggerFactory.getLogger(Launcher.class);
public static void main(String[] args) throws IOException {
Properties appProps = new Properties();
String hostname = "Unknown";
try
{
InetAddress addr;
addr = InetAddress.getLocalHost();
hostname = addr.getHostName();
}
catch (UnknownHostException ex)
{
System.out.println("Hostname can not be resolved");
}
String appConfigPath;
if (hostname.equals("Unknown")){
appConfigPath = "src/main/resource/app.properties";
}
else{
appConfigPath = "src/main/resource/"+hostname+".app.properties";
}
// String appConfigPath = args[0];
appProps.load(new FileInputStream(appConfigPath));
String numOfWorkers = appProps.getProperty("numOfWorkers", "10");
String portDumps = appProps.getProperty("portDumps","6399");
String projectType = appProps.getProperty("projectType","java");
String hunkLimit = appProps.getProperty("hunkLimit","10");
String patchSize = appProps.getProperty("patchSize","50");
String projectL = appProps.getProperty("projectList","");
String[] projectList = projectL.split(",");
String input = appProps.getProperty("inputPath","FORKJOIN");
String redisPath = appProps.getProperty("redisPath","FORKJOIN");
String srcMLPath = appProps.getProperty("srcMLPath","FORKJOIN");
// String parameter = args[2];
String parameter = "L1";
// String jobType = args[1];
// String jobType = "RICHEDITSCRIPT";
String jobType = "COMPARE";
mainLaunch( numOfWorkers, jobType, portDumps,projectType,input,redisPath,parameter, srcMLPath,hunkLimit,projectList,patchSize);
}
public static void mainLaunch(String numOfWorkers, String jobType, String portDumps, String projectType, String input, String redisPath,String parameter,String srcMLPath,String hunkLimit,String[] projectList,String patchSize){
String dbDir;
String dumpsName;
String gumInput;
dumpsName = "dumps-"+projectType+".rdb";
gumInput = input;
dbDir = redisPath;
try {
switch (jobType) {
case "RICHEDITSCRIPT":
EnhancedASTDiff.main(gumInput, portDumps, dbDir, dumpsName, srcMLPath,parameter,hunkLimit,projectList,patchSize,projectType);
break;
case "COMPARE":
String job;
String compareDBName;
switch (parameter){
case "L1":
// job = "shape";
job = "single";
compareDBName = "clusterl0-gumInputALL.rdb";
break;
case "L2":
job = "action";
compareDBName = "clusterl1-gumInputALL.rdb";
break;
case "L3":
job = "token";
compareDBName = "clusterl2-gumInputALL.rdb";
break;
default:
throw new Error("unknown level please specify L1,L2,L3");
}
CompareTrees.main(redisPath, portDumps,dumpsName, job,numOfWorkers);
break;
case "PATTERN":
ClusterToPattern.main(portDumps,redisPath, dumpsName, parameter);
break;
default:
throw new Error("unknown Job");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,46 @@
package edu.lu.uni.serval.fixminer.ediff;
/**
* Created by anilkoyuncu on 18/09/2018.
*/
public class BaseMessage {
private long SECONDS_TO_WAIT;
private int id;
private int threadPoolSize;
public BaseMessage(int id,Long timeout) {
this.id = id;
this.SECONDS_TO_WAIT = timeout;
// this.threadPoolSize = threadPoolSize;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public long getSECONDS_TO_WAIT() {
return SECONDS_TO_WAIT;
}
public void setSECONDS_TO_WAIT(long SECONDS_TO_WAIT) {
this.SECONDS_TO_WAIT = SECONDS_TO_WAIT;
}
public int getThreadPoolSize() {
return threadPoolSize;
}
public void setThreadPoolSize(int threadPoolSize) {
this.threadPoolSize = threadPoolSize;
}
}
@@ -0,0 +1,75 @@
package edu.lu.uni.serval.fixminer.ediff;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.japi.Creator;
import akka.routing.RoundRobinPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
public class EDiffActor extends UntypedActor {
private static Logger logger = LoggerFactory.getLogger(EDiffActor.class);
private ActorRef mineRouter;
private final int numberOfWorkers;
private int counter = 0;
public EDiffActor(int numberOfWorkers, String project) {
mineRouter = this.getContext().actorOf(new RoundRobinPool(numberOfWorkers)
.props(EDiffWorker.props(project)), "mine-fix-pattern-router");
this.numberOfWorkers = numberOfWorkers;
}
public static Props props(final int numberOfWorkers, final String project) {
return Props.create(new Creator<EDiffActor>() {
private static final long serialVersionUID = 9207427376110704705L;
@Override
public EDiffActor create() throws Exception {
return new EDiffActor(numberOfWorkers, project);
}
});
}
@SuppressWarnings("deprecation")
@Override
public void onReceive(Object message) throws Exception {
if (message instanceof EDiffMessage) {
List<MessageFile> files = ((EDiffMessage) message).getMsgFiles();
int size = files.size();
int average = size / numberOfWorkers;
int reminder = size % numberOfWorkers;
int counter = 0;
for (int i = 0; i < numberOfWorkers; i ++) {
int fromIndex = i * average + counter;
if (counter < reminder) counter ++;
int toIndex = (i + 1) * average + counter;
List<MessageFile> filesOfWorkers = files.subList(fromIndex, toIndex);
final EDiffMessage workMsg = new EDiffMessage(i + 1, filesOfWorkers,((EDiffMessage) message).getSECONDS_TO_WAIT(),((EDiffMessage) message).getInnerPool(),((EDiffMessage) message).getSrcMLPath(),((EDiffMessage) message).getRootType());
mineRouter.tell(workMsg, getSelf());
logger.info("Assign {} task to worker #" + (i + 1) ,filesOfWorkers.size());
}
} else if ("STOP".equals(message.toString())) {
counter ++;
logger.info(counter + " workers finalized their work...");
if (counter >= numberOfWorkers) {
logger.info("All workers finalized their work...");
this.getContext().stop(mineRouter);
this.getContext().stop(getSelf());
this.getContext().system().shutdown();
}
} else {
unhandled(message);
}
}
}
@@ -0,0 +1,103 @@
package edu.lu.uni.serval.fixminer.ediff;
import com.github.gumtreediff.tree.ITree;
import edu.lu.uni.serval.utils.EDiffHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.io.File;
import java.util.List;
/**
* Parse fix violations with GumTree in terms of multiple statements.
*
* @author kui.liu
*
*/
public class EDiffHunkParser extends EDiffParser {
private static Logger logger = LoggerFactory.getLogger(EDiffHunkParser.class);
@Override
public void parseFixPatterns(File prevFile, File revFile, File diffentryFile, String project, JedisPool innerPool,String srcMLPath,String hunkLimit,boolean isJava) {
String datasetName = project;
String[] split1 = diffentryFile.getParent().split(datasetName);
String root = split1[0];
String pj = split1[1].split("/")[1];
List<HierarchicalActionSet> actionSets = parseChangedSourceCodeWithGumTree2(prevFile, revFile, srcMLPath,isJava);
if (actionSets != null && actionSets.size() != 0) {
boolean processActionSet = true;
if (actionSets.size() > Integer.valueOf(hunkLimit)) {
processActionSet = false;
logger.debug("Skipping {} set size {}", diffentryFile.getName(), hunkLimit);
}
int hunkSet = 0;
if (processActionSet) {
for (HierarchicalActionSet actionSet : actionSets) {
// FileOutputStream f = null;
try {
String astNodeType = actionSet.getAstNodeType();
// if (astNodeType.equals(rootType)){
//
// }
actionSet.toString();
int size = actionSet.getActionSize();
String key = astNodeType + "/" + String.valueOf(size) + "/" + pj + "_" + diffentryFile.getName() + "_" + String.valueOf(hunkSet);
ITree targetTree = EDiffHelper.getTargets(actionSet,isJava);
ITree actionTree = EDiffHelper.getActionTrees(actionSet);
ITree shapeTree = EDiffHelper.getShapeTree(actionSet,isJava);
try (Jedis inner = innerPool.getResource()) {
inner.hset("dump", key, actionSet.toString());
inner.hset(key, "actionTree", actionTree.toStaticHashString());
inner.hset(key, "targetTree", targetTree.toStaticHashString());
inner.hset(key, "shapeTree", shapeTree.toStaticHashString());
}
// File f = new File(root+"dumps/"+astNodeType+"/"+String.valueOf(size)+"/");
// f.mkdirs();
// f = new File(root+"dumps/"+key);
//
// FileUtils.writeByteArrayToFile(f,EDiffHelper.kryoSerialize(actionSet));
// FileUtils.writeByteArrayToFile(f,EDiffHelper.commonsSerialize(actionSet));
// FileUtils.writeByteArrayToFile(f,actionSet.toString().getBytes());
// FileOutputStream fos = new FileOutputStream(f);
// ObjectOutputStream oos = new ObjectOutputStream(fos);
// oos.writeObject(EDiffHelper.kryoSerialize(actionSet));
// oos.flush();
// oos.close();
} catch (Exception e) {
logger.error("error", e);
// e.printStackTrace();
}
hunkSet++;
}
try (Jedis inner = innerPool.getResource()) {
inner.hset("diffEntry", pj + "_" + diffentryFile.getName(), "1");
}
}
}
}
}
@@ -0,0 +1,66 @@
package edu.lu.uni.serval.fixminer.ediff;
import redis.clients.jedis.JedisPool;
import java.util.List;
public class EDiffMessage extends BaseMessage{
private List<MessageFile> msgFiles;
public JedisPool getInnerPool() {
return innerPool;
}
public void setInnerPool(JedisPool innerPool) {
this.innerPool = innerPool;
}
private JedisPool innerPool;
public String getSrcMLPath() {
return srcMLPath;
}
private String srcMLPath;
public String getRootType() {
return rootType;
}
private String rootType;
public EDiffMessage(int id, List<MessageFile> msgFiles,String eDiffTimeout,JedisPool pool,String srcMLPath,String rootType) {
super(id,new Long(eDiffTimeout));
this.msgFiles = msgFiles;
this.innerPool = pool;
this.srcMLPath = srcMLPath;
this.rootType = rootType;
}
public EDiffMessage(int id, List<MessageFile> msgFiles,Long eDiffTimeout,JedisPool pool) {
super(id,eDiffTimeout);
this.msgFiles = msgFiles;
this.innerPool = pool;
}
public EDiffMessage(int id, List<MessageFile> filesOfWorkers, long seconds_to_wait, JedisPool innerPool, String srcMLPath,String rootType) {
super(id,seconds_to_wait);
this.msgFiles = filesOfWorkers;
this.innerPool = innerPool;
this.srcMLPath = srcMLPath;
this.rootType = rootType;
}
public List<MessageFile> getMsgFiles() {
return msgFiles;
}
}
@@ -0,0 +1,104 @@
package edu.lu.uni.serval.fixminer.ediff;
import com.github.gumtreediff.actions.model.Action;
import com.github.gumtreediff.gen.srcml.GumTreeCComparer;
import edu.lu.uni.serval.gumtree.GumTreeComparer;
import edu.lu.uni.serval.utils.ListSorter;
import redis.clients.jedis.JedisPool;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
/**
* Parse fix patterns with GumTree.
*
* @author kui.liu
*
*/
public class EDiffParser extends Parser {
/*
* ResultType:
* 0: normal GumTree results.
* 1: null GumTree result.
* 2: No source code changes.
* 3: No Statement Change.
* 4: useless violations
*/
public int resultType = 0;
/**
* Regroup GumTree results without remove the modification of variable names.
*
* @param prevFile
* @param revFile
* @return
*/
public List<HierarchicalActionSet> parseChangedSourceCodeWithGumTree2(File prevFile, File revFile,String srcMLPath,boolean isJava) {
List<HierarchicalActionSet> actionSets = new ArrayList<>();
// GumTree results
// boolean isJava =false;
List<Action> gumTreeResults = null;
if (isJava){
// if (revFile.getName().endsWith(".c") & prevFile.getName().endsWith(".c") || revFile.getName().endsWith(".h") & prevFile.getName().endsWith(".h")){
// gumTreeResults = new GumTreeComparer().compareCFilesWithGumTree(prevFile, revFile);
gumTreeResults = new GumTreeComparer().compareTwoFilesWithGumTree(prevFile, revFile);
}else{
gumTreeResults = new GumTreeCComparer().compareCFilesWithGumTree(prevFile, revFile,srcMLPath);
}
if (gumTreeResults == null) {
this.resultType = 1;
return null;
} else if (gumTreeResults.size() == 0){
this.resultType = 2;
return actionSets;
} else {
// Regroup GumTre results.
List<HierarchicalActionSet> allActionSets = null;
if (isJava){
allActionSets = new HierarchicalRegrouper().regroupGumTreeResults(gumTreeResults);
}else{
HashSet<Integer> removeType = new HashSet<Integer>(Arrays.asList(171,172,99,100,101,102));
boolean b = gumTreeResults.stream().anyMatch(p -> removeType.contains(p.getNode().getType()));
if(b){
return actionSets;
}
allActionSets = new HierarchicalRegrouperForC().regroupGumTreeResults(gumTreeResults);
}
ListSorter<HierarchicalActionSet> sorter = new ListSorter<>(allActionSets);
actionSets = sorter.sortAscending();
if (actionSets.size() == 0) {
this.resultType = 3;
}
return actionSets;
}
}
@Override
public void parseFixPatterns(File prevFile, File revFile, File diffEntryFile, String project, JedisPool innerPool, String srcMLPath,String rootType,boolean isJava) {
}
// @Override
// public void parseFixPatterns(File prevFile, File revFile, File diffEntryFile, String project, JedisPool innerPool) {
//
// }
}
@@ -0,0 +1,92 @@
package edu.lu.uni.serval.fixminer.ediff;
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.japi.Creator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.JedisPool;
import java.io.File;
import java.util.List;
import java.util.concurrent.*;
public class EDiffWorker extends UntypedActor {
private static Logger log = LoggerFactory.getLogger(EDiffActor.class);
private String project;
public EDiffWorker(String project) {
this.project = project;
}
public static Props props(final String project) {
return Props.create(new Creator<EDiffWorker>() {
private static final long serialVersionUID = -7615153844097275009L;
@Override
public EDiffWorker create() throws Exception {
return new EDiffWorker(project);
}
});
}
@Override
public void onReceive(Object message) throws Exception {
if (message instanceof EDiffMessage) {
EDiffMessage msg = (EDiffMessage) message;
List<MessageFile> files = msg.getMsgFiles();
int id = msg.getId();
int counter = 0;
JedisPool innerPool = msg.getInnerPool();
String srcMLPath = msg.getSrcMLPath();
String rootType = msg.getRootType();
for (MessageFile msgFile : files) {
File revFile = msgFile.getRevFile();
File prevFile = msgFile.getPrevFile();
File diffentryFile = msgFile.getDiffEntryFile();
EDiffHunkParser parser = new EDiffHunkParser();
final ExecutorService executor = Executors.newSingleThreadExecutor();
// schedule the work
final Future<?> future = executor.submit(new RunnableParser(prevFile, revFile, diffentryFile, parser,project,msg.getInnerPool(),srcMLPath,rootType,false));
try {
// wait for task to complete
future.get(msg.getSECONDS_TO_WAIT(), TimeUnit.SECONDS);
counter ++;
if (counter % 1000 == 0) {
log.info("Worker #" + id +" finalized parsing " + counter + " files... remaing "+ (files.size() - counter));
}
} catch (TimeoutException e) {
future.cancel(true);
System.err.println("#Timeout: " + revFile.getName());
} catch (InterruptedException e) {
System.err.println("#TimeInterrupted: " + revFile.getName());
e.printStackTrace();
} catch (ExecutionException e) {
System.err.println("#TimeAborted: " + revFile.getName());
e.printStackTrace();
} finally {
executor.shutdownNow();
}
}
log.info("Worker #" + id + " finalized the work...");
this.getSender().tell("STOP", getSelf());
} else {
unhandled(message);
}
}
}
@@ -0,0 +1,211 @@
package edu.lu.uni.serval.fixminer.ediff;
import com.github.gumtreediff.actions.model.Action;
import com.github.gumtreediff.tree.ITree;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Hierarchical-level results of GumTree results
*
* @author kui.liu
*
*/
public class HierarchicalActionSet implements Comparable<HierarchicalActionSet>,Serializable {
private String astNodeType;
private Action action;
private Action parentAction;
private String actionString;
private Integer startPosition;
private Integer length;
private int bugStartLineNum = 0;
private int bugEndLineNum;
private int fixStartLineNum;
private int fixEndLineNum;
private HierarchicalActionSet parent = null;
private List<HierarchicalActionSet> subActions = new ArrayList<>();
private ITree node;
// source code tree.
public int getBugEndPosition() {
return bugEndPosition;
}
public int getFixEndPosition() {
return fixEndPosition;
}
private int bugEndPosition;
private int fixEndPosition;
public ITree getNode() {
return node;
}
public void setNode(ITree node) {
this.node = node;
}
public void setAstNodeType(String astNodeType) {
this.astNodeType = astNodeType;
}
public String getAstNodeType() {
return astNodeType;
}
public Action getAction() {
return action;
}
public void setAction(Action action) {
this.action = action;
}
public Action getParentAction() {
return parentAction;
}
public void setParentAction(Action parentAction) {
this.parentAction = parentAction;
}
public String getActionString() {
return actionString;
}
public void setActionString(String actionString) {
this.actionString = actionString;
int atIndex = actionString.indexOf("@AT@") + 4;
int lengthIndex = actionString.indexOf("@LENGTH@");
if (lengthIndex == -1) {
this.startPosition = Integer.parseInt(actionString.substring(atIndex).trim());
this.length = 0;
} else {
this.startPosition = Integer.parseInt(actionString.substring(atIndex, lengthIndex).trim());
this.length = Integer.parseInt(actionString.substring(lengthIndex + 8).trim());
}
String nodeType = actionString.substring(0, actionString.indexOf("@@"));
nodeType = nodeType.substring(nodeType.indexOf(" ") + 1);
this.astNodeType = nodeType;
}
public int getStartPosition() {
return startPosition;
}
public int getLength() {
return length;
}
public int getBugStartLineNum() {
return bugStartLineNum;
}
public void setBugStartLineNum(int bugStartLineNum) {
this.bugStartLineNum = bugStartLineNum;
}
public int getBugEndLineNum() {
return bugEndLineNum;
}
public void setBugEndLineNum(int bugEndLineNum) {
this.bugEndLineNum = bugEndLineNum;
}
public int getFixStartLineNum() {
return fixStartLineNum;
}
public void setFixStartLineNum(int fixStartLineNum) {
this.fixStartLineNum = fixStartLineNum;
}
public int getFixEndLineNum() {
return fixEndLineNum;
}
public void setFixEndLineNum(int fixEndLineNum) {
this.fixEndLineNum = fixEndLineNum;
}
public HierarchicalActionSet getParent() {
return parent;
}
public void setParent(HierarchicalActionSet parent) {
this.parent = parent;
}
public List<HierarchicalActionSet> getSubActions() {
return subActions;
}
public void setSubActions(List<HierarchicalActionSet> subActions) {
this.subActions = subActions;
}
public void setBugEndPosition(int bugEndPosition) {
this.bugEndPosition = bugEndPosition;
}
public void setFixEndPosition(int fixEndPosition) {
this.fixEndPosition = fixEndPosition;
}
@Override
public int compareTo(HierarchicalActionSet o) {
return this.startPosition.compareTo(o.startPosition);//this.action.compareTo(o.action);
}
private List<String> strList = new ArrayList<>();
public int getActionSize(){
return strList.size();
}
@Override
public String toString() {
String str = actionString;
if (strList.size() == 0) {
strList.add(str);
for (HierarchicalActionSet actionSet : subActions) {
actionSet.toString();
List<String> strList1 = actionSet.strList;
for (String str1 : strList1) {
strList.add("---" + str1);
}
}
} else {
strList.clear();
strList.add(str);
for (HierarchicalActionSet actionSet : subActions) {
actionSet.toString();
List<String> strList1 = actionSet.strList;
for (String str1 : strList1) {
strList.add("---" + str1);
}
}
}
str = "";
for (String str1 : strList) {
str += str1 + "\n";
}
return str;
}
}
@@ -0,0 +1,228 @@
package edu.lu.uni.serval.fixminer.ediff;
import com.github.gumtreediff.actions.model.*;
import com.github.gumtreediff.tree.ITree;
import edu.lu.uni.serval.utils.ASTNodeMap;
import edu.lu.uni.serval.utils.ListSorter;
import java.util.ArrayList;
import java.util.List;
/**
* Regroup GumTree results to a hierarchical construction.
*
* @author kui.liu
*
*/
public class HierarchicalRegrouper {
public List<HierarchicalActionSet> regroupGumTreeResults(List<Action> actions) {
/*
* First, sort actions by their positions.
*/
// List<Action> actions = new ListSorter<Action>(actionsArgu).sortAscending();
// if (actions == null) {
// actions = actionsArgu;
// }
/*
* Second, group actions by their positions.
*/
List<HierarchicalActionSet> actionSets = new ArrayList<>();
HierarchicalActionSet actionSet = null;
for(Action act : actions){
Action parentAct = findParentAction(act, actions);
if (parentAct == null) {
actionSet = createActionSet(act, parentAct, null);
actionSets.add(actionSet);
} else {
if (!addToAactionSet(act, parentAct, actionSets)) {
// The index of the parent action in the actions' list is larger than the index of this action.
actionSet = createActionSet(act, parentAct, null);
actionSets.add(actionSet);
}
}
}
/*
* Third, add the subActionSet to its parent ActionSet.
*/
List<HierarchicalActionSet> reActionSets = new ArrayList<>();
for (HierarchicalActionSet actSet : actionSets) {
Action parentAct = actSet.getParentAction();
if (parentAct != null) {
addToActionSets(actSet, parentAct, actionSets);
} else {
// TypeDeclaration, FieldDeclaration, MethodDeclaration, Statement.
// CatchClause, ConstructorInvocation, SuperConstructorInvocation, SwitchCase
String astNodeType = actSet.getAstNodeType();
if (astNodeType.endsWith("TypeDeclaration") || astNodeType.endsWith("FieldDeclaration") || astNodeType.endsWith("EnumDeclaration") ||
astNodeType.endsWith("MethodDeclaration") || astNodeType.endsWith("Statement") ||
astNodeType.endsWith("ConstructorInvocation") || astNodeType.endsWith("CatchClause") || astNodeType.endsWith("SwitchCase")) {
reActionSets.add(actSet);
}
}
}
return reActionSets;
}
private HierarchicalActionSet createActionSet(Action act, Action parentAct, HierarchicalActionSet parent) {
HierarchicalActionSet actionSet = new HierarchicalActionSet();
actionSet.setAction(act);
actionSet.setActionString(parseAction(act.toString()));
actionSet.setParentAction(parentAct);
actionSet.setNode(act.getNode());
actionSet.setParent(parent);
return actionSet;
}
private String parseAction(String actStr1) {
// UPD 25@@!a from !a to isTrue(a) at 69
String[] actStrArrays = actStr1.split("@@");
String actStr = "";
int length = actStrArrays.length;
for (int i =0; i < length - 1; i ++) {
String actStrFrag = actStrArrays[i];
int index = actStrFrag.lastIndexOf(" ") + 1;
String nodeType = actStrFrag.substring(index);
if (!"".equals(nodeType)) {
if (Character.isDigit(nodeType.charAt(0)) || (nodeType.startsWith("-") && Character.isDigit(nodeType.charAt(1)))) {
try {
int typeInt = Integer.parseInt(nodeType);
if (ASTNodeMap.map.containsKey(typeInt)) {
String type = ASTNodeMap.map.get(Integer.parseInt(nodeType));
nodeType = type;
}
} catch (NumberFormatException e) {
nodeType = actStrFrag.substring(index);
}
}
}
actStrFrag = actStrFrag.substring(0, index) + nodeType + "@@";
actStr += actStrFrag;
}
actStr += actStrArrays[length - 1];
return actStr;
}
private void addToActionSets(HierarchicalActionSet actionSet, Action parentAct, List<HierarchicalActionSet> actionSets) {
Action act = actionSet.getAction();
for (HierarchicalActionSet actSet : actionSets) {
if (actSet.equals(actionSet)) continue;
Action action = actSet.getAction();
if (!areRelatedActions(action, act)) continue;
if (action.equals(parentAct)) { // actSet is the parent of actionSet.
actionSet.setParent(actSet);
actSet.getSubActions().add(actionSet);
sortSubActions(actSet);
break;
} else {
if (isPossibileSubAction(action, act)) {
// SubAction range startPosition2 <= startPosition && startPosition + length <= startPosition2 + length2
addToActionSets(actionSet, parentAct, actSet.getSubActions());
}
}
}
}
private boolean isPossibileSubAction(Action parent, Action child) {
if ((parent instanceof Update && !(child instanceof Addition))
|| (parent instanceof Delete && child instanceof Delete)
|| (parent instanceof Insert && (child instanceof Insert))) {
int startPosition = child.getPosition();
int length = child.getLength();
int startPosition2 = parent.getPosition();
int length2 = parent.getLength();
if (!(startPosition2 <= startPosition && startPosition + length <= startPosition2 + length2)) {
// when act is not the sub-set of action.
return false;
}
}
return true;
}
private void sortSubActions(HierarchicalActionSet actionSet) {
ListSorter<HierarchicalActionSet> sorter = new ListSorter<HierarchicalActionSet>(actionSet.getSubActions());
List<HierarchicalActionSet> subActions = sorter.sortAscending();
if (subActions != null) {
actionSet.setSubActions(subActions);
}
}
private boolean addToAactionSet(Action act, Action parentAct, List<HierarchicalActionSet> actionSets) {
for(HierarchicalActionSet actionSet : actionSets) {
Action action = actionSet.getAction();
if (!areRelatedActions(action, act)) continue;
if (action.equals(parentAct)) { // actionSet is the parent of actSet.
HierarchicalActionSet actSet = createActionSet(act, actionSet.getAction(), actionSet);
actionSet.getSubActions().add(actSet);
sortSubActions(actionSet);
return true;
} else {
if (isPossibileSubAction(action, act)) {
// SubAction range startPosition2 <= startPosition && startPosition + length <= startP + length2
List<HierarchicalActionSet> subActionSets = actionSet.getSubActions();
if (subActionSets.size() > 0) {
boolean added = addToAactionSet(act, parentAct, subActionSets);
if (added) {
return true;
} else {
continue;
}
}
}
}
}
return false;
}
private Action findParentAction(Action action, List<Action> actions) {
ITree parent = action.getNode().getParent();
if (action instanceof Addition) {
parent = ((Addition) action).getParent(); // parent in the fixed source code tree
}
if (parent.getType() == 55) {
int type = action.getNode().getType();
// Modifier, NormalAnnotation, MarkerAnnotation, SingleMemberAnnotation
if (type != 83 && type != 77 && type != 78 && type != 79
&& type != 5 && type != 39 && type != 43 && type != 74 && type != 75
&& type != 76 && type != 84 && type != 87 && type != 88 && type != 42) {
// ArrayType, PrimitiveType, SimpleType, ParameterizedType,
// QualifiedType, WildcardType, UnionType, IntersectionType, NameQualifiedType, SimpleName
return null;
}
}
for (Action act : actions) {
if (act.getNode().equals(parent)) {
if (areRelatedActions(act, action)) {
return act;
}
}
}
return null;
}
private boolean areRelatedActions(Action parent, Action child) {
if (parent instanceof Move && !(child instanceof Move)) {// If action is MOV, its children must be MOV.
return false;
}
if (parent instanceof Delete && !(child instanceof Delete)) {// If action is INS, its children must be MOV or INS.
return false;
}
if (parent instanceof Insert && !(child instanceof Addition)) {// If action is DEL, its children must be DEL.
return false;
}
return true;
}
}
@@ -0,0 +1,534 @@
package edu.lu.uni.serval.fixminer.ediff;
import com.github.gumtreediff.actions.model.Action;
import com.github.gumtreediff.actions.model.*;
import com.github.gumtreediff.gen.srcml.NodeMap_new;
import com.github.gumtreediff.tree.ITree;
import edu.lu.uni.serval.utils.ListSorter;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Regroup GumTree results to a hierarchical construction.
*
* @author kui.liu
*
*/
public class HierarchicalRegrouperForC {
// public static void main(String[] args) {
// GumTreeComparer com = new GumTreeComparer();
// File cFile1 = new File("/Users/anilkoyuncu/bugStudy/dataset/GumTreeInput/linux-stable/prevFiles/prev_0a3d00_b404bc_drivers#pci#iov.c");
// File cFile2 = new File("/Users/anilkoyuncu/bugStudy/dataset/GumTreeInput/linux-stable/revFiles/0a3d00_b404bc_drivers#pci#iov.c");
// List<Action> action = com.compareTwoFilesWithGumTreeForCCode(cFile1, cFile2);
// List<HierarchicalActionSet> actionSet = new HierarchicalRegrouperForC().regroupGumTreeResults(action);
// System.out.println(actionSet);
// }
List<HierarchicalActionSet> actionSets = new ArrayList<>();
public List<HierarchicalActionSet> regroupGumTreeResults(List<Action> actions) {
/*
* First, sort actions by their positions.
*/
// List<Action> actions = new ListSorter<Action>(actionsArgu).sortAscending();
// if (actions == null) {
// actions = actionsArgu;
// }
/*
* Second, group actions by their positions.
*/
HierarchicalActionSet actionSet = null;
for(Action act : actions){
// if(act.getNode().getType() == 19 && act.getNode().getLabel().equals("")){
// continue;
// }
Action parentAct = findParentAction(act, actions);
if (parentAct == null) {
actionSet = createActionSet(act, parentAct, null);
actionSets.add(actionSet);
} else {
if (!addToAactionSet(act, parentAct, actionSets)) {
// The index of the parent action in the actions' list is larger than the index of this action.
actionSet = createActionSet(act, parentAct, null);
actionSets.add(actionSet);
}
}
}
/*
* Third, add the subActionSet to its parent ActionSet.
*/
List<HierarchicalActionSet> reActionSets = new ArrayList<>();
for (HierarchicalActionSet actSet : actionSets) {
Action parentAct = actSet.getParentAction();
if (parentAct != null) {
addToActionSets(actSet, parentAct, actionSets);
} else {
// TypeDeclaration, FieldDeclaration, MethodDeclaration, Statement.
// CatchClause, ConstructorInvocation, SuperConstructorInvocation, SwitchCase
// String astNodeType = actSet.getAstNodeType();
// if (astNodeType.endsWith("TypeDeclaration") || astNodeType.endsWith("FieldDeclaration") || astNodeType.endsWith("EnumDeclaration") ||
// astNodeType.endsWith("MethodDeclaration") || astNodeType.endsWith("Statement") ||
// astNodeType.endsWith("ConstructorInvocation") || astNodeType.endsWith("CatchClause") || astNodeType.endsWith("SwitchCase")) {
if (isStatement(actSet.getNode())) {
reActionSets.add(actSet);
}
// }
}
}
List<HierarchicalActionSet> reActionSets1 = new ArrayList<>();
for(HierarchicalActionSet a:reActionSets){
HierarchicalActionSet hierarchicalActionSet = purifyActionSet(a);
List<HierarchicalActionSet> hierarchicalActionSets = divideBlocks(hierarchicalActionSet);
if(hierarchicalActionSets != null){
reActionSets1.addAll(hierarchicalActionSets);
}else{
reActionSets1.add(hierarchicalActionSet);
}
}
return reActionSets1;
// return reActionSets;
}
private HierarchicalActionSet purifyActionSet(HierarchicalActionSet actionSet){
HierarchicalActionSet hierarchicalActionSet = removeBlocks(actionSet);
// hierarchicalActionSet = removeIFthenBlocks(hierarchicalActionSet);
// hierarchicalActionSet = removeParentForSingle(hierarchicalActionSet);
// hierarchicalActionSet = removeParentNode(hierarchicalActionSet);
return hierarchicalActionSet;
// return actionSet;
}
private List<HierarchicalActionSet> divideBlocks(HierarchicalActionSet actionSet){
if (actionSet.getAstNodeType().equals("block") || actionSet.getAstNodeType().equals("function")){
List<HierarchicalActionSet> subActions = actionSet.getSubActions();
if (subActions.size() > 1) {
boolean b = subActions.stream().allMatch(p -> NodeMap_new.getKeysByValue(NodeMap_new.StatementMap, p.getAstNodeType()).size() == 1 && p.getAstNodeType().equals(subActions.get(0).getAstNodeType()) && p.getAction().getName().equals(subActions.get(0).getAction().getName()));
if (b ) {
subActions.stream().forEach(p -> p.setParent(null));
List<HierarchicalActionSet> collect = subActions.stream().map(p -> purifyActionSet(p)).collect(Collectors.toList());
return collect;
}
}
}
return null;
}
public List<HierarchicalActionSet> postOrder(HierarchicalActionSet a) {
List<HierarchicalActionSet> trees = new ArrayList<>();
getAllSubActions(a, trees);
return trees;
}
private void getAllSubActions(HierarchicalActionSet a,List<HierarchicalActionSet> as) {
List<HierarchicalActionSet> subActions = a.getSubActions();
if (subActions.size() != 0){
for (HierarchicalActionSet s : subActions) {
getAllSubActions(s, as);
}
}
as.add(a);
// List<HierarchicalActionSet> b = new ArrayList<HierarchicalActionSet>();
// for (HierarchicalActionSet child: this.getSubActions())
// b.add(child);
// return b;
}
Predicate<HierarchicalActionSet> predicate = x->NodeMap_new.getKeysByValue(NodeMap_new.StatementMap,x.getAstNodeType()).size() == 1 ;
Predicate<HierarchicalActionSet> predicate1 = x->!x.getAstNodeType().equals("block");
Predicate<HierarchicalActionSet> predicate2 = x->!x.getAstNodeType().equals("then");
// Predicate<HierarchicalActionSet> predicate3 = p->p.getAction().getName().equals(subActions.get(0).getAction().getName()));
private HierarchicalActionSet removeBlocks(HierarchicalActionSet actionSet){
List<HierarchicalActionSet> subActions = actionSet.getSubActions();
Action action = actionSet.getAction();
if (subActions.size() == 1){
HierarchicalActionSet subaction = subActions.get(0);
// if(!postOrder(subaction).stream().anyMatch(predicate.and(predicate1.and(predicate2)))){
// return actionSet;
// }
List<HierarchicalActionSet> collect = postOrder(subaction).stream().filter(predicate.and(predicate1.and(predicate2))).collect(Collectors.toList());
if(collect.size() == 0){
return actionSet;
}
boolean b = collect.stream().anyMatch(p -> p.getAction().getName().equals(subActions.get(0).getAction().getName()));
if(!b){
return actionSet;
}
Action action1 = subaction.getAction();
//else,then,block
if(action.getClass().equals(action1.getClass()) && action.getName().equals("UPD")) {
// List<Integer> keysByValue = NodeMap_new.getKeysByValue(NodeMap_new.StatementMap, subaction.getAstNodeType());
// if (keysByValue != null && keysByValue.size() == 1) {
subaction.setParent(null);
return removeBlocks(subaction);
// }
// if(areRelatedActions(action,action1)) {
// if (subaction.getAstNodeType().equals("block")) {//|| subaction.getAstNodeType().equals("then") || subaction.getAstNodeType().equals("else")){
// List<HierarchicalActionSet> subSubActions = subaction.getSubActions();
// if (subSubActions.size() == 1) {
//
// HierarchicalActionSet subsubsubAction = subSubActions.get(0);
// List<Integer> keysByValue = NodeMap_new.getKeysByValue(NodeMap_new.StatementMap, subsubsubAction.getAstNodeType());
// if (keysByValue != null && keysByValue.size() == 1) {
//
// subsubsubAction.setParent(null);
// return removeBlocks(subsubsubAction);
//
// }
// }
// }
}
}
return actionSet;
}
private HierarchicalActionSet removeParentNode(HierarchicalActionSet actionSet){
List<HierarchicalActionSet> subActions = actionSet.getSubActions();
Action action = actionSet.getAction();
if (subActions.size() == 1) {
HierarchicalActionSet subaction = subActions.get(0);
if(!postOrder(subaction).stream().anyMatch(predicate.and(predicate1.and(predicate2)))){
return actionSet;
}
Action action1 = subaction.getAction();
if (!action.getClass().equals(action1.getClass())) {
List<Integer> keysByValue = NodeMap_new.getKeysByValue(NodeMap_new.StatementMap, subaction.getAstNodeType());
if (keysByValue != null && keysByValue.size() == 1) {
subaction.setParent(null);
return removeParentNode(subaction);
}
}
}
return actionSet;
}
private HierarchicalActionSet removeParentForSingle(HierarchicalActionSet actionSet){
List<HierarchicalActionSet> subActions = actionSet.getSubActions();
Action action = actionSet.getAction();
if (subActions.size() == 1){
HierarchicalActionSet subaction = subActions.get(0);
if(!postOrder(subaction).stream().anyMatch(predicate.and(predicate1.and(predicate2)))){
return actionSet;
}
//else,then,block
Action action1 = subaction.getAction();
//else,then,block
if(action.getClass().equals(action1.getClass()) && action.getName().equals("UPD")) {
// if(areRelatedActions(action,action1)) {
if(!(subaction.getAstNodeType().equals("condition") || subaction.getAstNodeType().equals("init"))){
List<Integer> keysByValue = NodeMap_new.getKeysByValue(NodeMap_new.StatementMap, subaction.getAstNodeType());
if(keysByValue != null && keysByValue.size() ==1){
subaction.setParent(null);
return removeParentForSingle(subaction);
}
}
}
}
return actionSet;
}
private HierarchicalActionSet removeIFthenBlocks(HierarchicalActionSet actionSet){
List<HierarchicalActionSet> subActions = actionSet.getSubActions();
Action action = actionSet.getAction();
if (subActions.size() == 1){
HierarchicalActionSet subaction = subActions.get(0);
//else,then,block
Action action1 = subaction.getAction();
//else,then,block
if(action.getClass().equals(action1.getClass())) {
// if(areRelatedActions(action,action1)) {
if (subaction.getAstNodeType().equals("then") || subaction.getAstNodeType().equals("else")) {//|| subaction.getAstNodeType().equals("then") || subaction.getAstNodeType().equals("else")){
List<HierarchicalActionSet> subSubActions = subaction.getSubActions();
if (subSubActions.size() == 1) {
HierarchicalActionSet subsubsubAction = subSubActions.get(0);
if(!postOrder(subsubsubAction).stream().anyMatch(predicate.and(predicate1.and(predicate2)))){
return actionSet;
}
if (subsubsubAction.getAstNodeType().equals("block")) {
List<HierarchicalActionSet> subActions1 = subsubsubAction.getSubActions();
if (subActions1.size() == 1) {
HierarchicalActionSet hierarchicalActionSet = subActions1.get(0);
List<Integer> keysByValue = NodeMap_new.getKeysByValue(NodeMap_new.StatementMap, hierarchicalActionSet.getAstNodeType());
if (keysByValue != null && keysByValue.size() == 1) {
hierarchicalActionSet.setParent(null);
return removeBlocks(hierarchicalActionSet);
}
}
}
}
}
}
}
return actionSet;
}
private HierarchicalActionSet createActionSet(Action act, Action parentAct, HierarchicalActionSet parent) {
HierarchicalActionSet actionSet = new HierarchicalActionSet();
actionSet.setAction(act);
actionSet.setActionString(parseAction(act.toString()));
actionSet.setParentAction(parentAct);
actionSet.setNode(act.getNode());
actionSet.setParent(parent);
return actionSet;
}
private String parseAction(String actStr1) {
// UPD 25@@!a from !a to isTrue(a) at 69
String[] actStrArrays = actStr1.split("@@");
String actStr = "";
int length = actStrArrays.length;
for (int i =0; i < length - 1; i ++) {
String actStrFrag = actStrArrays[i];
int index = actStrFrag.lastIndexOf(" ") + 1;
String nodeType = actStrFrag.substring(index);
if (!"".equals(nodeType)) {
if (Character.isDigit(nodeType.charAt(0)) || (nodeType.startsWith("-") && Character.isDigit(nodeType.charAt(1)))) {
try {
int typeInt = Integer.parseInt(nodeType);
if (NodeMap_new.map.containsKey(typeInt)) {
String type = NodeMap_new.map.get(Integer.parseInt(nodeType));
nodeType = type;
}
} catch (NumberFormatException e) {
nodeType = actStrFrag.substring(index);
}
}
}
actStrFrag = actStrFrag.substring(0, index) + nodeType + "@@";
actStr += actStrFrag;
}
actStr += actStrArrays[length - 1];
return actStr;
}
private void addToActionSets(HierarchicalActionSet actionSet, Action parentAct, List<HierarchicalActionSet> actionSets) {
Action act = actionSet.getAction();
for (HierarchicalActionSet actSet : actionSets) {
if (actSet.equals(actionSet)) continue;
Action action = actSet.getAction();
if (!areRelatedActions(action, act)) continue;
if (action.equals(parentAct)) { // actSet is the parent of actionSet.
actionSet.setParent(actSet);
actSet.getSubActions().add(actionSet);
sortSubActions(actSet);
break;
} else {
if (isPossibileSubAction(action, act)) {
// SubAction range startPosition2 <= startPosition && startPosition + length <= startPosition2 + length2
addToActionSets(actionSet, parentAct, actSet.getSubActions());
}
}
}
}
private boolean isPossibileSubAction(Action parent, Action child) {
// if ((parent instanceof Update && !(child instanceof Addition))
// || (parent instanceof Delete && child instanceof Delete)
// || (parent instanceof Insert && (child instanceof Insert))) {
// int startPosition = child.getPosition();
// int length = child.getLength();
// int startPosition2 = parent.getPosition();
// int length2 = parent.getLength();
//
// if (!(startPosition2 <= startPosition && startPosition + length <= startPosition2 + length2)) {
// // when act is not the sub-set of action.
// return false;
// }
// }
return true;
}
private void sortSubActions(HierarchicalActionSet actionSet) {
ListSorter<HierarchicalActionSet> sorter = new ListSorter<HierarchicalActionSet>(actionSet.getSubActions());
List<HierarchicalActionSet> subActions = sorter.sortAscending();
if (subActions != null) {
actionSet.setSubActions(subActions);
}
}
private boolean addToAactionSet(Action act, Action parentAct, List<HierarchicalActionSet> actionSets) {
for(HierarchicalActionSet actionSet : actionSets) {
Action action = actionSet.getAction();
if (!areRelatedActions(action, act)) continue;
if (action.equals(parentAct)) { // actionSet is the parent of actSet.
HierarchicalActionSet actSet = createActionSet(act, actionSet.getAction(), actionSet);
actionSet.getSubActions().add(actSet);
sortSubActions(actionSet);
return true;
} else {
if (isPossibileSubAction(action, act)) {
// SubAction range startPosition2 <= startPosition && startPosition + length <= startP + length2
List<HierarchicalActionSet> subActionSets = actionSet.getSubActions();
if (subActionSets.size() > 0) {
boolean added = addToAactionSet(act, parentAct, subActionSets);
if (added) {
return true;
} else {
continue;
}
}
}
}
}
return false;
}
private Action findParentAction(Action action, List<Action> actions) {
ITree parent = action.getNode().getParent();
if (action instanceof Addition) {
parent = ((Addition) action).getParent(); // parent in the fixed source code tree
}
// if (parent.getType() == 55) {
// int type = action.getNode().getType();
// // Modifier, NormalAnnotation, MarkerAnnotation, SingleMemberAnnotation
// if (type != 83 && type != 77 && type != 78 && type != 79
// && type != 5 && type != 39 && type != 43 && type != 74 && type != 75
// && type != 76 && type != 84 && type != 87 && type != 88 && type != 42) {
// // ArrayType, PrimitiveType, SimpleType, ParameterizedType,
// // QualifiedType, WildcardType, UnionType, IntersectionType, NameQualifiedType, SimpleName
// return null;
// }
//
//
// }
for (Action act : actions) {
if (act instanceof Move){
if(act.getNode().equals(action.getNode())){
return act;
}
}
else if (act.getNode().equals(parent)) {
if (areRelatedActions(act, action)) {
return act;
}
}
}
return null;
}
// List<Action> newParentActions = new ArrayList<>();
// //TODO
// private Action findParentAction(Action action, List<Action> actions) {
//
// ITree parent = action.getNode().getParent();
// if (parent == null) return null;
// if (action instanceof Addition) {
// parent = ((Addition) action).getParent(); // parent in the fixed source code tree
// }
//
// for (Action act : actions) {
// if (act.getNode().equals(parent)) {
// if (areRelatedActions(act, action)) {
// return act;
// }
// }
// }
// for (Action act : newParentActions) {
// if (act.getNode().equals(parent)) {
// if (areRelatedActions(act, action)) {
// return act;
// }
// }
// }
//
// ITree tree = action.getNode();
// Action parentAction = null;
// if (!isStatement(tree)) {
// parentAction = new Update(parent, action.getNode().getParent());
// newParentActions.add(parentAction);
//
// Action higherParentAct = findParentAction(parentAction, actions);
// HierarchicalActionSet actionSet = null;
// if (higherParentAct == null) {
// actionSet = createActionSet(parentAction, higherParentAct, null);
// actionSets.add(actionSet);
// } else {
// if (!addToAactionSet(parentAction, higherParentAct, actionSets)) {
// // The index of the parent action in the actions' list is larger than the index of this action.
// actionSet = createActionSet(parentAction, higherParentAct, null);
// actionSets.add(actionSet);
// }
// }
// }
// return parentAction;
// }
private boolean isStatement(ITree tree) {
int nodeType = tree.getType();
// List<ITree> collect = tree.getChildren().stream().filter(m -> m.getType() == 6).collect(Collectors.toList());
// if (collect.size() > 0){
// return true;
// }
if (NodeMap_new.StatementMap.containsKey(nodeType)){
return true;
}
// else{
// if((nodeType ==6) && tree.getParent().getType() == 1){
// return true;
// }
// }
// if (nodeType == 11 || nodeType == 16 || nodeType == 18 || nodeType == 21
// || nodeType == 22 || nodeType == 23 || nodeType == 24 || nodeType == 84
// || 30 == nodeType || nodeType == 31 || nodeType == 32 || nodeType == 33
// || nodeType == 34 || nodeType == 35 || nodeType == 36 || nodeType == 40
// || nodeType == 41 || nodeType == 49 || nodeType == 73 || nodeType == 81 || nodeType == 80 || nodeType == 46 || nodeType == 60
// ||nodeType == 62 || nodeType == 64 || nodeType == 45 || nodeType == 85 || nodeType == 86 || nodeType == 59 || nodeType == 27 || nodeType == 25
// || nodeType == 26 || nodeType ==93 || nodeType == 37 || nodeType == 38 || nodeType == 39 || nodeType == 89) {// TODO
// return true;
// }
return false;
}
private boolean areRelatedActions(Action parent, Action child) {
// if (parent instanceof Move && !(child instanceof Move)) {// If action is MOV, its children must be MOV.
// return false;
// }
if (parent instanceof Delete && !(child instanceof Delete)) {// If action is DEL, its children must be DEL.
return false;
}
if (parent instanceof Insert && !(child instanceof Addition)) {// If action is INS, its children must be MOV or INS.
return false;
}
return true;
}
}
@@ -0,0 +1,47 @@
package edu.lu.uni.serval.fixminer.ediff;
import java.io.File;
public class MessageFile {
private File revFile;
private File prevFile;
private File diffEntryFile;
private File positionFile;
private String project;
public MessageFile(File revFile, File prevFile, File diffEntryFile,String project) {
super();
this.revFile = revFile;
this.prevFile = prevFile;
this.diffEntryFile = diffEntryFile;
this.project = project;
}
public String getProject() { return project;}
public void setProject(String project) { this.project = project;}
public File getRevFile() {
return revFile;
}
public File getPrevFile() {
return prevFile;
}
public File getDiffEntryFile() {
return diffEntryFile;
}
public File getPositionFile() {
return positionFile;
}
public void setPositionFile(File positionFile) {
this.positionFile = positionFile;
}
}
@@ -0,0 +1,60 @@
package edu.lu.uni.serval.fixminer.ediff;
import redis.clients.jedis.JedisPool;
import java.io.File;
/**
* Parse fix patterns with GumTree.
*
* @author kui.liu
*
*/
public abstract class Parser implements ParserInterface {
protected String astEditScripts = ""; // it will be used for fix patterns mining.
protected String patchesSourceCode = ""; // testing
protected String buggyTrees = ""; // Compute similarity for bug localization.
protected String sizes = ""; // fix patterns' selection before mining.
protected String tokensOfSourceCode = ""; // Compute similarity for bug localization.
protected String originalTree = ""; // Guide of generating patches.
protected String actionSets = ""; // Guide of generating patches.
public abstract void parseFixPatterns(File prevFile, File revFile, File diffEntryFile, String project, JedisPool innerPool, String srcMLPath,String rootType,boolean isJava);
@Override
public String getAstEditScripts() {
return astEditScripts;
}
@Override
public String getPatchesSourceCode() {
return patchesSourceCode;
}
// @Override
// public String getBuggyTrees() {
// return buggyTrees;
// }
@Override
public String getSizes() {
return sizes;
}
@Override
public String getTokensOfSourceCode() {
return tokensOfSourceCode;
}
// @Override
// public String getOriginalTree() {
// return originalTree;
// }
//
// @Override
// public String getActionSets() {
// return actionSets;
// }
}
@@ -0,0 +1,21 @@
package edu.lu.uni.serval.fixminer.ediff;
public interface ParserInterface {
// public void parseFixPatterns(File prevFile, File revFile, File diffEntryFile);
public String getAstEditScripts();
public String getPatchesSourceCode();
// public String getBuggyTrees();
public String getSizes();
public String getTokensOfSourceCode();
// public String getOriginalTree();
// public String getActionSets();
}
@@ -0,0 +1,51 @@
package edu.lu.uni.serval.fixminer.ediff;
import redis.clients.jedis.JedisPool;
import java.io.File;
public class RunnableParser implements Runnable {
private File prevFile;
private File revFile;
private File diffEntryFile;
private Parser parser;
private String project;
private JedisPool pool;
private String srcMLPath;
private String rootType;
boolean isJava;
public RunnableParser(File prevFile, File revFile, File diffEntryFile, Parser parser) {
this.prevFile = prevFile;
this.revFile = revFile;
this.diffEntryFile = diffEntryFile;
this.parser = parser;
}
public RunnableParser(File prevFile, File revFile, File diffEntryFile, Parser parser, String project, JedisPool innerPool) {
this.prevFile = prevFile;
this.revFile = revFile;
this.diffEntryFile = diffEntryFile;
this.parser = parser;
this.project = project;
this.pool = innerPool;
}
public RunnableParser(File prevFile, File revFile, File diffEntryFile, Parser parser, String project, JedisPool innerPool,String srcMLPath,String rootType,boolean isJava) {
this.prevFile = prevFile;
this.revFile = revFile;
this.diffEntryFile = diffEntryFile;
this.parser = parser;
this.project = project;
this.pool = innerPool;
this.srcMLPath = srcMLPath;
this.rootType = rootType;
this.isJava = isJava;
}
@Override
public void run() {
parser.parseFixPatterns(prevFile, revFile, diffEntryFile,project,pool,srcMLPath,rootType,isJava);
}
}
@@ -0,0 +1,248 @@
package edu.lu.uni.serval.fixminer.jobs;
import edu.lu.uni.serval.fixminer.ediff.EDiffHunkParser;
import edu.lu.uni.serval.utils.CallShell;
import edu.lu.uni.serval.utils.EDiffHelper;
import edu.lu.uni.serval.utils.PoolBuilder;
import me.tongfei.progressbar.ProgressBar;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* Created by anilkoyuncu on 03/04/2018.
*/
public class CompareTrees {
private static Logger log = LoggerFactory.getLogger(CompareTrees.class);
public static void main(String redisPath, String portDumps, String dumpsName, String job,String numOfWorkers) throws Exception {
// shape /Users/anil.koyuncu/projects/test/fixminer-core/python/data/redis ALLdumps-gumInput.rdb clusterl0-gumInputALL.rdb /Users/anil.koyuncu/projects/test/fixminer-core/python/data/richEditScript
// String portInner = "6380";
String port = portDumps; //"6399";
CallShell cs = new CallShell();
String cmd = "bash "+redisPath + "/" + "startServer.sh" +" %s %s %s";
cmd = String.format(cmd, redisPath,dumpsName,Integer.valueOf(port));
log.info(cmd);
cs.runShell(cmd, port);
// String cmdInner = "bash "+redisPath + "/" + "startServer.sh" +" %s %s %s";
// cmdInner = String.format(cmdInner, redisPath,compareDBName,Integer.valueOf(portInner));
// log.info(cmdInner);
// cs.runShell(cmdInner, portInner);
// String numOfWorkers = "100000000";//args[4];
// String host = "localhost";//args[5];
// -Djava.util.concurrent.ForkJoinPool.common.parallelism=256
// final JedisPool innerPool = new JedisPool(PoolBuilder.getPoolConfig(), host,Integer.valueOf(portInner),20000000);
final JedisPool outerPool = new JedisPool(PoolBuilder.getPoolConfig(), "localhost",Integer.valueOf(port),20000000);
// List<String> listOfPairs = AkkaTreeParser.getMessages(innerPool,Integer.valueOf(numOfWorkers));
HashMap<String, String> filenames = getFilenames(outerPool);
// List<String> listOfPairs = AkkaTreeParser.files2compare(outerPool);
// ArrayList<String> samePairs = new ArrayList<>();
ArrayList<String> errorPairs = new ArrayList<>();
// Integer numberOfWorkers = Integer.valueOf(numOfWorkers);
// final ExecutorService executor = Executors.newWorkStealingPool(numberOfWorkers);
Long compare;
try (Jedis inner = outerPool.getResource()) {
compare = inner.scard("compare");
}
IntStream stream = IntStream.range(0, compare.intValue());
ProgressBar.wrap(stream.
parallel(),"Task").
forEach(m ->
{
newCoreCompare(job, errorPairs, filenames, outerPool);
}
);
//
// ArrayList<Future<?>> results = new ArrayList<Future<?>>();
// for (int i = 0; i <numberOfWorkers ; i++) {
//
//
// // schedule the work
// log.info("Starting job {}",i);
// final Future<?> future = executor.submit(new RunnableCompare(job, errorPairs, filenames, outerPool, i));
// results.add(future);
// }
// for (Future<?> future : ProgressBar.wrap(results, "Comparing")){
//// for (Future<?> future:results){
// try {
// // wait for task to complete
// future.get();
//
// } catch (InterruptedException e) {
//
// e.printStackTrace();
// } catch (ExecutionException e) {
//
// e.printStackTrace();
// }
//// finally {
//// executor.shutdownNow();
//// }
// }
// executor.shutdownNow();
log.info("End process");
}
// public static class RunnableCompare implements Runnable {
// String job;
// ArrayList<String> errorPairs;
// HashMap<String, String> filenames;
// JedisPool outerPool;
// Integer threadID;
//
// public RunnableCompare(String treeType,ArrayList<String> errorPairs, HashMap<String, String> filenames,JedisPool outerPool,Integer threadID) {
// this.job = treeType;
// this.errorPairs = errorPairs;
// this.filenames = filenames;
// this.outerPool = outerPool;
// this.threadID = threadID;
// }
//
// @Override
// public void run() {
//// int dbsize = 1;
// boolean stop = true;
// while(stop) {
//// try (Jedis outer = outerPool.getResource()) {
//// dbsize = Math.toIntExact(outer.scard("compare"));
//// }
//// if (dbsize != 0){
// stop = newCoreCompare(job, errorPairs, filenames, outerPool);
//// }
// }
// log.info("Completed worker {}",threadID);
// }
// }
public static boolean newCoreCompare( String treeType,ArrayList<String> errorPairs, HashMap<String, String> filenames,JedisPool outerPool ) {
String pairName;
try (Jedis outer = outerPool.getResource()) {
pairName = outer.spop("compare");
}
String matchKey = null;
try {
String[] split = pairName.split("/");
String i = split[1];
String j = split[2];
String keyName = split[0];
matchKey = keyName + "/" + (String.valueOf(i)) + "/" + String.valueOf(j);
switch (treeType) {
case "single":
if (matchKey == null){
return false;
}
Map<String, String> oldTreeString = EDiffHelper.getTreeString(keyName, i, outerPool, filenames);
Map<String, String> newTreeString = EDiffHelper.getTreeString(keyName, j, outerPool, filenames);
String oldShapeTree =oldTreeString.get("shapeTree");
String newShapeTree =newTreeString.get("shapeTree");
String oldActionTree = oldTreeString.get("actionTree");
String newActionTree = newTreeString.get("actionTree");
String oldTargetTree = oldTreeString.get("targetTree");
String newTargetTree = newTreeString.get("targetTree");
if (oldShapeTree.equals(newShapeTree)) {
if (oldActionTree.equals(newActionTree)) {
if (oldTargetTree.equals(newTargetTree)) {
// samePairs.add(matchKey);
try (Jedis jedis = outerPool.getResource()) {
//// jedis.del(matchKey);
jedis.select(2);
jedis.set(matchKey, "1");
}
}
}
}
return true;
default:
return true;
// break;
}
}catch (Exception e) {
errorPairs.add(matchKey);
if (pairName == null)
return false;
log.debug("{} not comparable", pairName);
}
return true;
}
public static HashMap<String, String> getFilenames(JedisPool innerPool){
HashMap<String, String> fileMap =new HashMap<String, String>();
try (Jedis inner = innerPool.getResource()) {
while (!inner.ping().equals("PONG")){
log.info("wait");
}
inner.select(1);
Map<String, String> filenames = inner.hgetAll("filenames");
for (Map.Entry<String, String> stringStringEntry : filenames.entrySet().stream().collect(Collectors.toList())) {
fileMap.put(stringStringEntry.getKey(),stringStringEntry.getValue());
}
}
// log.info("Getting results %d",fileMap.s);
return fileMap;
}
}
@@ -0,0 +1,168 @@
package edu.lu.uni.serval.fixminer.jobs;
import edu.lu.uni.serval.fixminer.ediff.EDiffHunkParser;
import edu.lu.uni.serval.utils.FileHelper;
import edu.lu.uni.serval.fixminer.ediff.MessageFile;
import edu.lu.uni.serval.utils.CallShell;
import edu.lu.uni.serval.utils.PoolBuilder;
import me.tongfei.progressbar.ProgressBar;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class EnhancedASTDiff {
private static Logger log = LoggerFactory.getLogger(EnhancedASTDiff.class);
public static void main(String inputPath, String portInner, String dbDir, String chunkName,String srcMLPath,String parameter,String hunkLimit,String[] projectList,String patchSize,String projectType) throws Exception {
String parameters = String.format("\nInput path %s",inputPath);
log.info(parameters);
CallShell cs = new CallShell();
String cmd = "bash "+dbDir + "/" + "startServer.sh" +" %s %s %s";
cmd = String.format(cmd, dbDir,chunkName,Integer.valueOf(portInner));
cs.runShell(cmd, portInner);
JedisPool innerPool = new JedisPool(PoolBuilder.getPoolConfig(), "127.0.0.1",Integer.valueOf(portInner),20000000);
boolean isJava = false;
if (projectType.equals("java")){
isJava =true;
}
File folder = new File(inputPath);
File[] listOfFiles = folder.listFiles();
Stream<File> stream = Arrays.stream(listOfFiles);
List<File> folders;
if (projectList.length == 1 && projectList[0].equals("")){
folders = stream
.filter(x -> !x.getName().startsWith("."))
.filter(x -> !x.getName().startsWith("cocci"))
.filter(x -> !x.getName().endsWith(".index"))
.collect(Collectors.toList());
}
else {
List<Predicate<File>> allPredicates = new ArrayList<Predicate<File>>();
for (String s : projectList) {
Predicate<File> predicate = x -> x.getName().endsWith(s);
allPredicates.add(predicate);
}
folders = stream
.filter(x -> !x.getName().startsWith("."))
.filter(x -> !x.getName().startsWith("cocci"))
.filter(x -> !x.getName().endsWith(".index"))
.filter(allPredicates.stream().reduce(x->false, Predicate::or))
.collect(Collectors.toList());
}
String project = folder.getName();
List<MessageFile> allMessageFiles = new ArrayList<>();
for (File target : folders) {
List<MessageFile> msgFiles = getMessageFiles(target.toString() + "/",project,patchSize,isJava); //"/Users/anilkoyuncu/bugStudy/code/python/GumTreeInput/Apache/CAMEL/"
// msgFiles = msgFiles.subList(0,3000);
if (msgFiles == null)
continue;
allMessageFiles.addAll(msgFiles);
}
Map<String, String> diffEntry;
try (Jedis inner = innerPool.getResource()) {
diffEntry = inner.hgetAll("diffEntry");
}
log.info("{} files to process ...", allMessageFiles.size());
if (diffEntry != null) {
log.info("{} files already process ...", diffEntry.size());
allMessageFiles = allMessageFiles.stream().filter(f -> !diffEntry.containsKey(f.getProject() + "_" + f.getDiffEntryFile().getName())).collect(Collectors.toList());
log.info("{} files to process ...", allMessageFiles.size());
}
boolean finalIsJava = isJava;
ProgressBar.wrap(allMessageFiles.stream().
parallel(),"Task").
forEach(m ->
{
EDiffHunkParser parser = new EDiffHunkParser();
parser.parseFixPatterns(m.getPrevFile(),m.getRevFile(), m.getDiffEntryFile(),project,innerPool,srcMLPath,hunkLimit, finalIsJava);
}
);
}
private static List<MessageFile> getMessageFiles(String gumTreeInput,String datasetName,String patchSize,boolean isJava) {
String inputPath = gumTreeInput; // prevFiles revFiles diffentryFile positionsFile
File revFilesPath = new File(inputPath + "revFiles/");
log.info(revFilesPath.getPath());
File[] revFiles = revFilesPath.listFiles();
if (revFiles!= null ){
// List<File> collect = Arrays.stream(revFiles).filter(x -> x.getName().startsWith("0a2756_7598f8_components#camel-cxf#src#main#java#org#apache#camel#component#cxf#CxfHeaderFilterStrategy"))
// .collect(Collectors.toList());// project folders
List<MessageFile> msgFiles = new ArrayList<>();
for (File revFile : revFiles) {
// for (File revFile : collect) {
String fileName = revFile.getName();
File prevFile = new File(gumTreeInput + "prevFiles/prev_" + fileName);// previous file
if (isJava){
fileName = fileName.replace(".java",".txt");
}else{
fileName = fileName + ".txt";
}
File diffentryFile = new File(gumTreeInput + "DiffEntries/" + fileName); // DiffEntry file
String s = FileHelper.readFile(diffentryFile);
Pattern pattern = Pattern.compile("^[\\+|\\-]\\s*",Pattern.MULTILINE);
Matcher matcher = pattern.matcher(s);
int count = 0;
while (matcher.find())
count++;
if(count>= Integer.valueOf(patchSize))
// if(count>201)
continue;
// if(FileHelper.readFile(diffentryFile).split("@@\\s\\-\\d+,*\\d*\\s\\+\\d+,*\\d*\\s@@").length > 2)
// continue;
// String datasetName = project;
String[] split1 = diffentryFile.getParent().split(datasetName);
String root = split1[0];
String pj = split1[1].split("/")[1];
MessageFile msgFile = new MessageFile(revFile, prevFile, diffentryFile,pj);
msgFiles.add(msgFile);
}
return msgFiles;
}else{
return null;
}
}
}
@@ -0,0 +1,116 @@
package edu.lu.uni.serval.utils;
import java.util.HashMap;
import java.util.Map;
public class ASTNodeMap {
public static Map<Integer, String> map;
static {
map = new HashMap<Integer, String>();
map.put(-3, "Instanceof");
map.put(-2, "New");
map.put(-1, "Operator");
map.put(0, "ASTNode");
map.put(1, "AnonymousClassDeclaration");
map.put(2, "ArrayAccess");
map.put(3, "ArrayCreation");
map.put(4, "ArrayInitializer");
map.put(5, "ArrayType");
map.put(6, "AssertStatement");
map.put(7, "Assignment");
map.put(8, "Block");
map.put(9, "BooleanLiteral");
map.put(10, "BreakStatement");
map.put(11, "CastExpression");
map.put(12, "CatchClause");
map.put(13, "CharacterLiteral");
map.put(14, "ClassInstanceCreation");
map.put(15, "CompilationUnit");
map.put(16, "ConditionalExpression");
map.put(17, "ConstructorInvocation");
map.put(18, "ContinueStatement");
map.put(19, "DoStatement");
map.put(20, "EmptyStatement");
map.put(21, "ExpressionStatement");
map.put(22, "FieldAccess");
map.put(23, "FieldDeclaration");
map.put(24, "ForStatement");
map.put(25, "IfStatement");
map.put(26, "ImportDeclaration");
map.put(27, "InfixExpression");
map.put(28, "Initializer");
map.put(29, "Javadoc");
map.put(30, "LabeledStatement");
map.put(31, "MethodDeclaration");
map.put(32, "MethodInvocation");
map.put(33, "NullLiteral");
map.put(34, "NumberLiteral");
map.put(35, "PackageDeclaration");
map.put(36, "ParenthesizedExpression");
map.put(37, "PostfixExpression");
map.put(38, "PrefixExpression");
map.put(39, "PrimitiveType");
map.put(40, "QualifiedName");
map.put(41, "ReturnStatement");
map.put(42, "SimpleName");
map.put(43, "SimpleType");
map.put(44, "SingleVariableDeclaration");
map.put(45, "StringLiteral");
map.put(46, "SuperConstructorInvocation");
map.put(47, "SuperFieldAccess");
map.put(48, "SuperMethodInvocation");
map.put(49, "SwitchCase");
map.put(50, "SwitchStatement");
map.put(51, "SynchronizedStatement");
map.put(52, "ThisExpression");
map.put(53, "ThrowStatement");
map.put(54, "TryStatement");
map.put(55, "TypeDeclaration");
map.put(56, "TypeDeclarationStatement");
map.put(57, "TypeLiteral");
map.put(58, "VariableDeclarationExpression");
map.put(59, "VariableDeclarationFragment");
map.put(60, "VariableDeclarationStatement");
map.put(61, "WhileStatement");
map.put(62, "InstanceofExpression");
map.put(63, "LineComment");
map.put(64, "BlockComment");
map.put(65, "TagElement");
map.put(66, "TextElement");
map.put(67, "MemberRef");
map.put(68, "MethodRef");
map.put(69, "MethodRefParameter");
map.put(70, "EnhancedForStatement");
map.put(71, "EnumDeclaration");
map.put(72, "EnumConstantDeclaration");
map.put(73, "TypeParameter");
map.put(74, "ParameterizedType");
map.put(75, "QualifiedType");
map.put(76, "WildcardType");
map.put(77, "NormalAnnotation");
map.put(78, "MarkerAnnotation");
map.put(79, "SingleMemberAnnotation");
map.put(80, "MemberValuePair");
map.put(81, "AnnotationTypeDeclaration");
map.put(82, "AnnotationTypeMemberDeclaration");
map.put(83, "Modifier");
map.put(84, "UnionType");
map.put(85, "Dimension");
map.put(86, "LambdaExpression");
map.put(87, "IntersectionType");
map.put(88, "NameQualifiedType");
map.put(89, "CreationReference");
map.put(90, "ExpressionMethodReference");
map.put(91, "SuperMethodReference");
map.put(92, "TypeMethodReference");
map.put(100,"Insert");
map.put(101,"Update");
map.put(102,"Delete");
map.put(103,"Move");
map.put(104,"NoChange");
}
}
@@ -0,0 +1,120 @@
package edu.lu.uni.serval.utils;
/**
* Created by anilkoyuncu on 17/04/2018.
*/
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;
public class CallShell {
private static Logger log = LoggerFactory.getLogger(CallShell.class);
public void runShell(String command) throws Exception {
Process process = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String s;
while ((s = reader.readLine()) != null) {
System.out.println("Script output: " + s);
}
}
public static void runShell(String command, String port) throws Exception {
log.trace(command);
Process process = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String s;
while ((s = reader.readLine()) != null) {
// System.out.println("Script output: " + s);
log.trace("Script output: " + s);
}
// Thread.sleep(Integer.valueOf(serverWait));
String cmd = "redis-cli -p %s ping";
String cmd1 = String.format(cmd,Integer.valueOf(port));
runPing(cmd1);
}
public static void runPing(String command) throws Exception {
try{
StringBuffer output = new StringBuffer();
Process process = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String s;
BufferedReader stdError = new BufferedReader(new
InputStreamReader(process.getErrorStream()));
// read the output from the command
// System.out.println("Here is the standard output of the command:\n");
// while ((s = reader.readLine()) != null && !s.equals("PONG")) {
// System.out.println(s);
// }
// while(true){
s = reader.readLine();
if(s !=null && s.equals("PONG")){
// System.out.println(s);
log.trace(s);
}else{
String e;
if((e = stdError.readLine()) == null) {
TimeUnit.MINUTES.sleep(1);
runPing(command);
}else{
TimeUnit.MINUTES.sleep(1);
System.out.println(e);
}
}
// System.out.println(s);
// }
// read any errors from the attempted command
// System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.print(s);
}
// System.exit(0);
}
catch (IOException e) {
System.out.println("exception happened - here's what I know: ");
e.printStackTrace();
System.exit(-1);
}
}
public static void main(String[] args) throws Exception {
// runPing("redis-cli -p 6380 ping");
runShell("bash /Users/anilkoyuncu/bugStudy/release/code/redis/startServer.sh /Users/anilkoyuncu/bugStudy/release/code/redis Defects4JALL0.txt.rdb 6380","6380");
}
}
@@ -0,0 +1,50 @@
package edu.lu.uni.serval.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
public class ClusterToPattern {
private static Logger log = LoggerFactory.getLogger(ClusterToPattern.class);
public static void main(String port,String redisPath, String dumpsName, String parameter) throws Exception {
CallShell cs = new CallShell();
String cmd = "bash "+redisPath + "/" + "startServer.sh" +" %s %s %s";
cmd = String.format(cmd, redisPath,dumpsName,Integer.valueOf(port));
log.trace(cmd);
cs.runShell(cmd, port);
String host = "localhost";//args[5];
final JedisPool outerPool = new JedisPool(PoolBuilder.getPoolConfig(), host,Integer.valueOf(port),20000000);
String export = export(parameter, outerPool);
System.out.println(export);
}
private static String export(String filename,JedisPool outerPool){
try (Jedis outer = outerPool.getResource()) {
while (!outer.ping().equals("PONG")) {
log.info("wait");
}
// byte[] s = outer.hget("dump".getBytes(), filename.getBytes());
// HierarchicalActionSet actionSet = (HierarchicalActionSet) EDiffHelper.kryoDeseerialize(s);
// if (actionSet == null){
// throw new Error(filename +" not found");
// }
String s1 = outer.hget("dump",filename);
// outer.close();
return s1;
}
}
}
@@ -0,0 +1,634 @@
package edu.lu.uni.serval.utils;
import com.github.gumtreediff.actions.model.*;
import com.github.gumtreediff.gen.srcml.NodeMap_new;
import com.github.gumtreediff.tree.ITree;
import com.github.gumtreediff.tree.TreeContext;
import com.github.gumtreediff.tree.TreeUtils;
import edu.lu.uni.serval.fixminer.ediff.HierarchicalActionSet;
import org.apache.commons.lang3.SerializationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* Created by anilkoyuncu on 17/09/2018.
*/
public class EDiffHelper {
private static Logger log = LoggerFactory.getLogger(EDiffHelper.class);
/** Read the object from Base64 string. */
public static Object fromString( String s ) throws IOException,
ClassNotFoundException {
byte [] data = Base64.getDecoder().decode( s );
ObjectInputStream ois = new ObjectInputStream(
new ByteArrayInputStream( data ) );
Object o = ois.readObject();
ois.close();
return o;
}
/** Write the object to a Base64 string. */
public static String toString( Serializable o ) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream( baos );
oos.writeObject( o );
oos.close();
return Base64.getEncoder().encodeToString(baos.toByteArray());
}
public static Object fromByteArray( byte[] data ) throws IOException,
ClassNotFoundException {
// byte [] data = Base64.getDecoder().decode( s );
ObjectInputStream ois = new ObjectInputStream(
new ByteArrayInputStream( data ) );
Object o = ois.readObject();
ois.close();
return o;
}
/** Write the object to a Base64 string. */
public static byte[] toByteArray(Serializable o ) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream( baos );
oos.writeObject( o );
oos.close();
return baos.toByteArray();
}
public static byte[] commonsSerialize(Serializable o){
return SerializationUtils.serialize(o);
}
public static Object commonsDeserialize(byte[] data){
return SerializationUtils.deserialize(data);
}
public static ITree getTokenTree(HierarchicalActionSet actionSet, ITree parent, ITree children,TreeContext tc){
int newType = 0;
String astNodeType = actionSet.getAstNodeType();
String label = actionSet.getAction().toString();
// List<Integer> keysByValue = getKeysByValue(ASTNodeMap.map, astNodeType);
List<Integer> keysByValue = getKeysByValue(NodeMap_new.map, astNodeType);
if(keysByValue.size() != 1){
log.error("More than 1");
}
newType = keysByValue.get(0);
if(actionSet.getParent() == null){
//root
parent = tc.createTree(newType, label, null);
tc.setRoot(parent);
}else{
children = tc.createTree(newType, label, null);
children.setParentAndUpdateChildren(parent);
}
List<HierarchicalActionSet> subActions = actionSet.getSubActions();
if (subActions.size() != 0){
for (HierarchicalActionSet subAction : subActions) {
if(actionSet.getParent() == null){
children = parent;
}
getTokenTree(subAction,children,null,tc);
}
}
return parent;
}
public static ITree getTargetTree(HierarchicalActionSet actionSet, ITree parent, ITree children, TreeContext tc,boolean isJava){
int newType = 0;
String astNodeType = null;
Map<Integer, String> nodeMap;
if(isJava){
nodeMap = ASTNodeMap.map;
}else{
nodeMap = NodeMap_new.map;
}
Action action = actionSet.getAction();
if (action instanceof Update){
astNodeType = actionSet.getAstNodeType();
List<Integer> keysByValue = getKeysByValue(nodeMap, astNodeType);
if(keysByValue.size() != 1){
log.error("More than 1");
}
newType = keysByValue.get(0);
}else if(action instanceof Insert){
newType = ((Insert)action).getParent().getType();
}else if(action instanceof Move){
newType = ((Move)action).getParent().getType();
}else if(action instanceof Delete){
astNodeType = actionSet.getAstNodeType();
List<Integer> keysByValue = getKeysByValue(nodeMap, astNodeType);
if(keysByValue.size() != 1){
log.error("More than 1");
}
newType = keysByValue.get(0);
}
if(actionSet.getParent() == null){
//root
// parent = new Tree(newType,"");
parent = tc.createTree(newType, "", null);
tc.setRoot(parent);
}else{
// children = new Tree(newType,"");
// parent.addChild(children);
children = tc.createTree(newType, "", null);
children.setParentAndUpdateChildren(parent);
}
List<HierarchicalActionSet> subActions = actionSet.getSubActions();
if (subActions.size() != 0){
for (HierarchicalActionSet subAction : subActions) {
if(actionSet.getParent() == null){
children = parent;
}
getTargetTree(subAction,children,null,tc,isJava);
}
}
return parent;
}
public static ITree getASTTree(HierarchicalActionSet actionSet, ITree parent, ITree children, TreeContext tc,boolean isJava){
int newType = 0;
Map<Integer, String> nodeMap;
if(isJava){
nodeMap = ASTNodeMap.map;
}else{
nodeMap = NodeMap_new.map;
}
String astNodeType = actionSet.getAstNodeType();
List<Integer> keysByValue = getKeysByValue(nodeMap, astNodeType);
if(keysByValue.size() != 1){
log.error("More than 1");
}
newType = keysByValue.get(0);
if(actionSet.getParent() == null){
//root
// parent = new Tree(newType,"");
parent = tc.createTree(newType, "", null);
tc.setRoot(parent);
}else{
// children = new Tree(newType,"");
// parent.addChild(children);
children = tc.createTree(newType, "", null);
children.setParentAndUpdateChildren(parent);
}
List<HierarchicalActionSet> subActions = actionSet.getSubActions();
if (subActions.size() != 0){
for (HierarchicalActionSet subAction : subActions) {
if(actionSet.getParent() == null){
children = parent;
}
getASTTree(subAction,children,null,tc,isJava);
}
}
return parent;
}
public static <T, E> List<T> getKeysByValue(Map<T, E> map, E value) {
return map.entrySet()
.stream()
.filter(entry -> Objects.equals(entry.getValue(), value))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
}
// public static ITree getSimpliedTree(String prefix, String fn, JedisPool outerPool) {
//
// ITree tree = null;
// Jedis inner = null;
// try {
// inner = outerPool.getResource();
// while (!inner.ping().equals("PONG")){
// log.info("wait");
// }
// inner.select(1);
// String dist2load = inner.get(prefix+"-"+fn);
// inner.select(0);
// String s = inner.get(prefix.replace("-","/") +"/"+dist2load);
// HierarchicalActionSet actionSet = (HierarchicalActionSet) EDiffHelper.fromString(s);
//
// ITree parent = null;
// ITree children =null;
// TreeContext tc = new TreeContext();
// tree = EDiffHelper.getASTTree(actionSet, parent, children,tc);
// tree.setParent(null);
// tc.validate();
//
// } catch (IOException e) {
// e.printStackTrace();
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// }finally {
// if (inner != null) {
// inner.close();
// }
// }
// return tree;
//
// }
// public static ITree getShapes(String prefix, String fn, JedisPool outerPool, HashMap<String, String> filenames) {
//
// ITree tree = null;
//
// try (Jedis outer = outerPool.getResource()) {
// try {
// while (!outer.ping().equals("PONG")) {
// log.info("wait");
// }
// String dist2load = filenames.get(prefix + "-" + fn);
//
// String key = prefix.replace("-", "/") + "/" + dist2load;
//
// byte[] s = outer.hget("dump".getBytes(), key.getBytes());
// HierarchicalActionSet actionSet = (HierarchicalActionSet) EDiffHelper.kryoDeseerialize(s);
//
// tree = getShapeTree(actionSet);
//
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// return tree;
//
// }
public static ITree getShapeTree(HierarchicalActionSet actionSet,boolean isJava) {
ITree tree = null;
ITree parent = null;
ITree children = null;
TreeContext tc = new TreeContext();
tree = EDiffHelper.getASTTree(actionSet, parent, children, tc, isJava);
//tree.setParent(null);
tc.validate();
return tree;
}
public static ITree getTargets(HierarchicalActionSet actionSet,boolean isJava) {
ITree tree = null;
try {
ITree parent = null;
ITree children =null;
TreeContext tc = new TreeContext();
tree = EDiffHelper.getTargetTree(actionSet, parent, children,tc,isJava);
//tree.setParent(null);
tc.validate();
} catch (Exception e) {
e.printStackTrace();
}
return tree;
}
public static Map<String, String> getTreeString(String prefix, String fn, JedisPool outerPool, HashMap<String, String> filenames) {
try (Jedis outer = outerPool.getResource()) {
try {
while (!outer.ping().equals("PONG")) {
log.info("wait");
}
String dist2load = filenames.get(prefix + "-" + fn);
String[] split = prefix.split("-");
String key = split[0] + "/" + split[1] + "/" + dist2load;
Map<String, String> treeMap = outer.hgetAll(key);
return treeMap;
}catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
// public static Pair<ITree,HierarchicalActionSet> getActions(String prefix, String fn, JedisPool outerPool, HashMap<String, String> filenames) {
//
//
// ITree tree = null;
// HierarchicalActionSet actionSet = null;
//
// try (Jedis outer = outerPool.getResource()) {
// try {
// while (!outer.ping().equals("PONG")) {
// log.info("wait");
// }
//
//
// String dist2load = filenames.get(prefix + "-" + fn);
//
// String[] split = prefix.split("-");
// String key = split[0] + "/"+split[1]+"/" + dist2load;
//
// byte[] s = outer.hget("dump".getBytes(), key.getBytes());
// actionSet = (HierarchicalActionSet) EDiffHelper.kryoDeseerialize(s);
//
//
// tree = getActionTrees(actionSet);
// }catch (Exception e) {
// e.printStackTrace();
// }
// }
//
// Pair<ITree, HierarchicalActionSet> pair = new Pair<>(tree,actionSet);
// return pair;
//
// }
public static ITree getActionTrees(HierarchicalActionSet actionSet) {
ITree tree = null;
ITree parent = null;
ITree children = null;
TreeContext tc = new TreeContext();
tree = EDiffHelper.getActionTree(actionSet, parent, children, tc);
//tree.setParent(null);
tc.validate();
return tree;
}
public static void getLeaves(ITree tc){
int height = tc.getHeight();
if(height == 0){
log.info(tc.getLabel());
}else{
List<ITree> children = tc.getChildren();
for (ITree child:children){
getLeaves(child);
}
}
}
// public static ITree getTokens(String prefix, String fn, JedisPool outerPool, HashMap<String, String> filenames) {
//
//
// ITree tree = null;
//
// HierarchicalActionSet actionSet = null;
// try (Jedis outer = outerPool.getResource()) {
// try {
// while (!outer.ping().equals("PONG")) {
// log.info("wait");
// }
// String dist2load = filenames.get(prefix + "-" + fn);
//
// String[] split = prefix.split("-");
// String key = split[0] + "/"+split[1]+"/" + dist2load;
//
// byte[] s = outer.hget("dump".getBytes(), key.getBytes());
// actionSet = (HierarchicalActionSet) EDiffHelper.kryoDeseerialize(s);
//
// ITree parent = null;
// ITree children = null;
// TreeContext tc = new TreeContext();
// tree = EDiffHelper.getTokenTree(actionSet, parent, children, tc);
// tree.setParent(null);
// tc.validate();
//// getLeaves(tree);
//
//
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
// return tree;
// }
public static ITree getActionTree(HierarchicalActionSet actionSet, ITree parent, ITree children,TreeContext tc){
int newType = 0;
Action action = actionSet.getAction();
if (action instanceof Update){
newType = 101;
}else if(action instanceof Insert){
newType =100;
}else if(action instanceof Move){
newType = 102;
}else if(action instanceof Delete){
newType=103;
}else{
new Exception("unknow action");
}
if(actionSet.getParent() == null){
//root
parent = tc.createTree(newType, "", null);
tc.setRoot(parent);
}else{
children = tc.createTree(newType, "", null);
children.setParentAndUpdateChildren(parent);
}
List<HierarchicalActionSet> subActions = actionSet.getSubActions();
if (subActions.size() != 0){
for (HierarchicalActionSet subAction : subActions) {
if(actionSet.getParent() == null){
children = parent;
}
getActionTree(subAction,children,null,tc);
}
}
return parent;
}
public static List<ITree> retainLeaves(List<ITree> trees) {
Iterator<ITree> tIt = trees.iterator();
while (tIt.hasNext()) {
ITree t = tIt.next();
if (!t.isLeaf()) tIt.remove();
}
return trees;
}
public static String getTokenAtNode(ITree leaf,String token){
// if (leaf.getParent() == null) {
String label = leaf.getLabel();
String key = label.split(String.valueOf(leaf.getType()))[0];
String group="";
Pattern pattern;
java.util.regex.Matcher matcher;
List<ITree> parents;
List<String> actionList = new ArrayList<>();
Set<String> uniqueGas = new HashSet<String>(actionList);
switch (key.trim()) {
case "DEL":
parents = leaf.getParents();
for (ITree parent : parents) {
String s = parent.getLabel().split(String.valueOf(parent.getType()))[0];
actionList.add(s);
}
actionList.add(key);
if (uniqueGas.size() == 1){
Optional<ITree> first = parents.stream().filter(p -> p.isRoot()).findFirst();
if(first.isPresent()){
ITree parent = first.get();
label = parent.getLabel();
}
}
pattern = Pattern.compile(delPattern);
matcher = pattern.matcher(label);
if (matcher.matches()) {
group = matcher.group(2);
}
break;
case "INS":
parents = leaf.getParents();
for (ITree parent : parents) {
String s = parent.getLabel().split(String.valueOf(parent.getType()))[0];
actionList.add(s);
}
actionList.add(key);
if (uniqueGas.size() == 1){
Optional<ITree> first = parents.stream().filter(p -> p.isRoot()).findFirst();
if(first.isPresent()){
ITree parent = first.get();
label = parent.getLabel();
}
}
//
pattern = Pattern.compile(insPattern);
matcher = pattern.matcher(label);
if (matcher.matches()) {
group = matcher.group(2);// +" " + matcher.group(3);
}
break;
case "MOV":
parents = leaf.getParents();
for (ITree parent : parents) {
String s = parent.getLabel().split(String.valueOf(parent.getType()))[0];
actionList.add(s);
}
actionList.add(key);
if (uniqueGas.size() == 1){
Optional<ITree> first = parents.stream().filter(p -> p.isRoot()).findFirst();
if(first.isPresent()){
ITree parent = first.get();
label = parent.getLabel();
}
}
pattern = Pattern.compile(movPattern);
matcher = pattern.matcher(label);
if (matcher.matches()) {
group = matcher.group(2);
String group1 = matcher.group(3);
}
break;
case "UPD":
pattern = Pattern.compile(updPattern);
matcher = pattern.matcher(label);
if (matcher.matches()) {
group = matcher.group(2) +" " + matcher.group(3);
}
break;
}
token = group;
return group;
// }else{
// getTokenAtNode(leaf.getParent(),token);
// return token;
// }
}
static String movPattern = "MOV (.*)@@(.*)@TO@ (.*)@@(.*)@AT@.*";
static String delPattern = "DEL (.*)@@(.*)@AT@.*";
static String insPattern = "INS (.*)@@(.*)@TO@ (.*)@@(.*)@AT@.*";
static String updPattern = "UPD (.*)@@(.*)@TO@(.*)@AT@.*";
public static String getNames2(ITree oldTree){
List<ITree> leaves = retainLeaves(TreeUtils.postOrder(oldTree));
List<String> res = new ArrayList<>();
String resu="";
for (ITree leaf : leaves) {
String tokenAtNode = getTokenAtNode(leaf, resu);
res.add(tokenAtNode);
}
// log.info("s");
if (res.size() == 1){
final String regex = "MethodName:([a-zA-Z0-9]+):.*MethodName:([a-zA-Z0-9]+):.*";
Pattern compile = Pattern.compile(regex);
Matcher matcher = compile.matcher(res.get(0));
if(matcher.matches()){
res.set(0,matcher.group(1) +" " + matcher.group(2));
}
}
return String.join(" ",res);
}
}
@@ -0,0 +1,383 @@
package edu.lu.uni.serval.utils;
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class FileHelper {
/**
* @param filePath
*/
public static void createDirectory(String filePath) {
File file = new File(filePath);
if (file.exists()) {
deleteDirectory(filePath);
}
file.mkdirs();
}
public static void createFile(File file, String content) {
FileWriter writer = null;
BufferedWriter bw = null;
try {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) file.createNewFile();
writer = new FileWriter(file);
bw = new BufferedWriter(writer);
bw.write(content);
bw.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
close(bw);
close(writer);
}
}
public static void deleteDirectory(String dir) {
File file = new File(dir);
if (file.exists()) {
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files.length > 0) {
for (File f : files) {
if (f.isFile()) {
deleteFile(f.getAbsolutePath());
} else {
deleteDirectory(f.getAbsolutePath());
}
}
}
file.delete();
} else {
deleteFile(dir);
}
}
}
public static void deleteFiles(String dir) {
File file = new File(dir);
if (file.exists()) {
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files.length > 0) {
for (File f : files) {
if (f.isFile()) {
deleteFile(f.getAbsolutePath());
} else {
deleteFiles(f.getAbsolutePath());
}
}
}
} else {
deleteFile(dir);
}
}
}
public static void deleteFile(String fileName) {
File file = new File(fileName);
if (file.exists()) {
if (file.isFile()) {
file.delete();
} else {
deleteDirectory(fileName);
}
}
}
public static List<File> getAllDirectories(String filePath) {
return listAllDirectories(new File(filePath));
}
/**
* List all files in the directory.
*
* @param filePath
* @param type
* @return
*/
public static List<File> getAllFiles(String filePath, String type) {
return listAllFiles(new File(filePath), type);
}
public static List<File> getAllFilesInCurrentDiectory(String filePath, String type) {
return getAllFilesInCurrentDiectory(new File(filePath), type);
}
public static List<File> getAllFilesInCurrentDiectory(File directory, String type) {
List<File> fileList = new ArrayList<>();
if (!directory.exists()) {
return null;
}
File[] files = directory.listFiles();
for (File file : files) {
if (file.isFile()) {
if (file.toString().endsWith(type)) {
fileList.add(file);
}
}
}
return fileList;
}
public static String getFileName(String filePath) {
File file = new File(filePath);
if (file.exists()) {
return file.getName();
} else {
return null;
}
}
public static String getFileNameWithoutExtension(File file) {
if (file.exists()) {
String fileName = file.getName();
fileName = fileName.substring(0, fileName.lastIndexOf("."));
return fileName;
} else {
return null;
}
}
public static String getFileExtension(File file) {
String fileName = file.getName();
String extension = fileName.substring(fileName.lastIndexOf("."));
return extension;
}
public static String getFileParentPath(String filePath) {
File file = new File(filePath);
if (file.exists()) {
return file.getParent() + "/";
}
return "";
}
/**
* Check whether a file path is valid or not.
*
* @param path, file path.
* @return true, the file path is valid.
* false, the file path is invalid.
*/
public static boolean isValidPath(String path) {
File file = new File(path);
if (file.exists()) {
return true;
}
return false;
}
/**
* Recursively list all files in file.
*
* @param file
* @return
*/
private static List<File> listAllFiles(File file, String type) {
List<File> fileList = new ArrayList<>();
if (!file.exists()) {
return null;
}
File[] files = file.listFiles();
for (File f : files) {
if (f.isFile()) {
if (f.toString().endsWith(type)) {
fileList.add(f);
}
} else {
List<File> fl = listAllFiles(f, type);
if (fl != null && fl.size() > 0) {
fileList.addAll(fl);
}
}
}
return fileList;
}
/**
* Recursively list all directories in file.
*
* @param file
* @return
*/
private static List<File> listAllDirectories(File file) {
List<File> fileList = new ArrayList<>();
File[] files = file.listFiles();
for (File f : files) {
if (f.isDirectory()) {
fileList.add(f);
fileList.addAll(listAllDirectories(f));
}
}
return fileList;
}
public static void makeDirectory(String fileName) {
deleteFile(fileName);
File file = new File(fileName).getParentFile();
if (!file.exists()) {
file.mkdirs();
}
}
/**
* Read the content of a file.
*
* @param fileName
* @return String, the content of a file.
*/
public static String readFile(String fileName) {
return readFile(new File(fileName));
}
/**
* Read the content of a file.
*
* @param file
* @return String, the content of a file.
*/
public static String readFile(File file) {
byte[] input = null;
BufferedInputStream bis = null;
try {
bis = new BufferedInputStream(new FileInputStream(file));
input = new byte[bis.available()];
bis.read(input);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
close(bis);
}
String sourceCode = null;
if (input != null) {
sourceCode = new String(input);
}
return sourceCode;
}
/**
* Output output into a file.
*
* @param fileName, output file name.
* @param data, output data.
* @param append, the output data will be appended previous data in the file or not.
*/
public static void outputToFile(String fileName, StringBuilder data, boolean append) {
outputToFile(fileName, data.toString(), append);
}
public static void outputToFile(File file, StringBuilder data, boolean append) {
outputToFile(file, data.toString(), append);
}
public static void outputToFile(String fileName, String data, boolean append) {
File file = new File(fileName);
outputToFile(file, data, append);
}
public static void outputToFile(File file, String data, boolean append) {
FileWriter writer = null;
BufferedWriter bw = null;
try {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
writer = new FileWriter(file, append);
bw = new BufferedWriter(writer);
bw.write(data);
bw.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
close(bw);
close(writer);
}
}
private static void close(FileWriter writer) {
try {
if (writer != null) {
writer.close();
writer = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void close(BufferedWriter bw) {
try {
if (bw != null) {
bw.close();
bw = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void close(BufferedInputStream bis) {
try {
if (bis != null) {
bis.close();
bis = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static List<File> getAllSubDirectories(String fileName) {
File file = new File(fileName);
List<File> subDirectories = new ArrayList<>();
if (file.exists()) {
File[] files = file.listFiles();
for (File f : files) {
if (f.isDirectory()) {
subDirectories.add(f);
}
}
}
return subDirectories;
}
}
@@ -0,0 +1,45 @@
package edu.lu.uni.serval.utils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ListSorter<T extends Comparable<? super T>> {
private List<T> list;
public ListSorter(List<T> list) {
this.list = new ArrayList<>();
this.list.addAll(list);
}
public List<T> getList() {
return this.list;
}
public List<T> sortAscending() {
try {
if (list != null && list.size() > 0) {
Collections.sort(this.list, new Comparator<T>() {
@Override
public int compare(T t1, T t2) {
return t1.compareTo(t2);
}
});
}
} catch (Exception e) {
return null;
}
return this.list;
}
public List<T> sortDescending() {
if (list != null && list.size() > 0) {
Collections.sort(this.list, Collections.reverseOrder());
}
return this.list;
}
}
@@ -0,0 +1,37 @@
package edu.lu.uni.serval.utils;
import redis.clients.jedis.JedisPoolConfig;
import java.time.Duration;
/**
* Created by anilkoyuncu on 17/09/2018.
*/
public class PoolBuilder {
public static JedisPoolConfig getPoolConfig() {
return poolConfig;
}
static final JedisPoolConfig poolConfig = buildPoolConfig();
private static JedisPoolConfig buildPoolConfig() {
final JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(1024);
poolConfig.setMaxIdle(1024);
// poolConfig.setMinIdle(16);
// poolConfig.setTestOnBorrow(true);
// poolConfig.setTestOnReturn(true);
// poolConfig.setTestWhileIdle(true);
poolConfig.setMinEvictableIdleTimeMillis(Duration.ofMinutes(60).toMillis());
poolConfig.setTimeBetweenEvictionRunsMillis(Duration.ofHours(30).toMillis());
poolConfig.setNumTestsPerEvictionRun(3);
poolConfig.setBlockWhenExhausted(true);
return poolConfig;
}
}
@@ -0,0 +1,20 @@
portDumps = 6399
numOfWorkers = 14
hunkLimit = 10
patchSize = 50
projectList =
#projectList = libtiff,php-src,cpython,wireshark,gzip,gmp,lighttpd1.4,lighttpd2
#inputPath = /Users/anilkoyuncu/projects/gumInputLinux
#inputPath = /Users/anil.koyuncu/projects/fixminer/fixminer-data/gumInputLinux
inputPath = /Users/anil.koyuncu/projects/test/fixminer-data/patches
#redisPath = /Users/anil.koyuncu/projects/fixminer/fixminer-core/python/data/redis
#redisPath = /Users/anil.koyuncu/projects/fixminer/fixminer-core/python/data/redis
redisPath = /Users/anil.koyuncu/projects/test/fixminer-core/python/data/redis
#srcMLPath= /Users/anil.koyuncu/Downloads/srcML.0.9.5/bin/srcml
srcMLPath= /Users/anil.koyuncu/projects/test/srcML/bin/srcml
#ENHANCEDASTDIFF,CACHE,LEVEL1,LEVEL2,LEVEL3
projectType = c
+24
View File
@@ -0,0 +1,24 @@
pjName = patches
portDumps = 6399
numOfWorkers = 14
hostname = localhost
hunkLimit = 10
patchSize = 50
projectList = libtiff,php-src,cpython,wireshark,gzip,gmp,lighttpd1.4,lighttpd2
#inputPath = /Users/anilkoyuncu/projects/gumInputLinux
#inputPath = /Users/anil.koyuncu/projects/fixminer/fixminer-data/gumInputLinux
inputPath = /Users/anil.koyuncu/projects/test/fixminer-data/patches
#redisPath = /Users/anil.koyuncu/projects/fixminer/fixminer-core/python/data/redis
#redisPath = /Users/anil.koyuncu/projects/fixminer/fixminer-core/python/data/redis
redisPath = /Users/anil.koyuncu/projects/test/fixminer-core/python/data/redis
#srcMLPath= /Users/anil.koyuncu/Downloads/srcML.0.9.5/bin/srcml
srcMLPath= /usr/local/bin/srcml
#srcMLPath= /usr/local/bin/srcml
actionType = ALL
#ENHANCEDASTDIFF,CACHE,LEVEL1,LEVEL2,LEVEL3
+43
View File
@@ -0,0 +1,43 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
<property name="APP_NAME" value="Fix.Pattern.Miner"></property>
<contextName>${APP_NAME}</contextName>
<property name="LOG_HOME" value="logs" />
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{0} - %msg%n</pattern>
</encoder>
</appender>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>${LOG_HOME}/myLog.log</file>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{0} - %msg%n</pattern>
</encoder>
</appender>
<appender name="ROLLINGFILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${LOG_HOME}/%d{yyyy-MM-dd}.log</FileNamePattern>
<MaxHistory>30</MaxHistory>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{0} - %msg%n</pattern>
</encoder>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>10MB</MaxFileSize>
</triggeringPolicy>
</appender>
<logger name="org.hibernate.engine.query.HQLQueryPlan" level="DEBUG" additivity="false" />
<logger name="com.piedra.logback" level="DEBUG">
<appender-ref ref="FILE"/>
</logger>
<root level="INFO">
<appender-ref ref="STDOUT" />
<appender-ref ref="ROLLINGFILE" />
</root>
</configuration>
@@ -0,0 +1,32 @@
#include <stdio.h>
int main(int argc, char *argv[])
{
int p1, p2, p3, t1, t2, n, lr, l, r, e = 0;
scanf("%d %d %d %d %d %d", &n, &p1, &p2, &p3, &t1, &t2);
scanf("%d %d", &l, &r);
e += (r - l) * p1;
lr = r;
while(-- n)
{
scanf("%d %d", &l, &r);
e += (r - l) * p1;
if(l - lr <= t1)
e += (l - lr) * p1;
else
{
e += t1 * p1;
if(l - lr <= t1 + t2)
e += (l - lr - t1) * p2;
else
e += t2 * p2 + (l - lr - t1 - t2) * p3;
}
}
printf("%d\n", e);
return 0;
}
@@ -0,0 +1,34 @@
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
int n,p1,p2,p3,t1,t2,a,c,b,e,i,d=0;
long int p=0;
scanf("%d%d%d%d%d%d",&n,&p1,&p2,&p3,&t1,&t2);
scanf("%d %d",&a,&b);
if(n==1) p=(b-a)*p1;
else { p=(b-a)*p1;
for(i=1;i<n;i++);
scanf("%d %d",&c,&e);
d=c-b;
if(d>=t1) {p+=t1*p1;
d-=t1;
}
else if(d>0) {p+=d*p1;
d=0;
}
if(d>=t2) {p+=t2*p2;
d-=t2;
}
else if(d>0) {p+=d*p2;
d=0;
}
if(d>0) p+=d*p3;
p+=p1*(e-c);
a=c;
b=e;
}
printf("%ld",p);
return 0;
}
@@ -0,0 +1,30 @@
#include <stdio.h>
int i,n,m,p1,p2,p3,t1,t2,l,r,p,s,t,ar[2][101];
int main(int argc, char *argv[]){
scanf("%d%d%d%d%d%d",&n,&p1,&p2,&p3,&t1,&t2);
for (i=0; i<n; i++){
scanf("%d%d",&l,&r);
ar[0][i]=l;
ar[1][i]=r;
}
i=0;
while (i<=n){
s=ar[1][i]-ar[0][i];
p+=s*p1;
if (n>=i+1 && ar[0][i+1]-ar[1][i]>0){
m=ar[0][i+1]-ar[1][i];
if (m>=t1){p+=p1*t1;} else {p+=p1*m;}
if (m-t1>=t2){p+=p2*t2;} else if (m>t1 && m<t2) {p+=p2*(m-t1);}
if (m-t1>t2){p+=p3*(m-(t2+t1));}
}
t=ar[1][i];
i++;
}
printf("%d",p);
return(0);
}
@@ -0,0 +1,29 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
int n,p1,p2,p3,t1,t2,a,b,i,lr=0,power=0;
scanf("%d %d %d %d %d %d",&n,&p1,&p2,&p3,&t1,&t2);
scanf("%d %d",&a,&b);
power+=(b-a)*p1;
lr=b;
for(i=1;i<n;i++)
{
scanf("%d %d",&a,&b);
power+=(b-a)*p1;
if(lr+t1<=a)
{
power+=(t1*p1);
if(lr+t1+t2<=a)
power+=(t2*p2)+(a-lr-t1-t2)*p3;
}
else
power+=(a-lr)*p1;
lr=b;
}
printf("%d",power);
return 0;
}
@@ -0,0 +1,65 @@
#include<stdio.h>
#include<string.h>
int main(int argc, char *argv[])
{
int a[505],b[505],la,lb,f[505],p[505];
int i,j,n,k,max;
while
(scanf("%d",&la)!=EOF)
{
for(i=0;i<la;i++)
scanf("%d",&a[i]);
scanf("%d",&lb);
for(i=0;i<lb;i++)
scanf("%d",&b[i]);
memset(f,0,sizeof(f));
for(i=0;i<=500;i++)
p[i]=-1;
for(i=1;i<=la;i++)
{
k=0;
for(j=1;j<=lb;j++)
{
if(b[j-1]<a[i-1]&&f[j]>f[k])//b[j-1]<a[i-1]是递增的条件,f[j]>f[k]是存放到 j时,j前面的最长的子序列
k=j;
if(a[i-1]==b[j-1]&&f[k]>=f[j])//逐步优化,要掌握
{f[j]=f[k]+1;
p[j]=k;
}
}
}
max=0;
int t=1;
for(i=1;i<=lb;i++)
{
if(max<f[i]) {max=f[i];t=i;}
}
int k=0;
int d[501];
d[++k]=b[t-1];
while(1)
{
t=p[t];
if(t==0)
break;
d[++k]=b[t-1];
}
printf("%d\n",k);
for(i=k;i>1;i--)
printf("%d ",d[i]);
printf("%d\n",d[1]);
}
return 0;
}
@@ -0,0 +1,79 @@
#include<stdio.h>
#include<string.h>
char arr[100005];
int k;
struct string
{
int index[100005];
int character;
}e[251];
static int age_comp(const void *p1, const void *p2)
{
struct string *sp1 = (struct string *) p1;
struct string *sp2 = (struct string *) p2;
return sp1->character - sp2->character;
}
void solve();
int main(int argc, char *argv[])
{
scanf("%s",arr);
scanf("%d",&k);
solve();
return 0;
}
void solve()
{
int d,l,i,sum=0,j,m,dst=0,t=0;
l=strlen(arr);
for(i=0;i<=250;i++)
e[i].character=0;
if(k>=l)
{
printf("0\n");
printf("\0");
}
else
{
for(i=0;i<l;i++)
{
d=arr[i];
//printf("%d",d);
e[d].index[e[d].character]=i;
e[d].character++;
}
qsort(e,250,sizeof e[0],age_comp);
m=0;
while(e[m].character==0)
m++;
for(i=0;i<=250;i++)
{
if(e[i].character!=0)
dst++;
}
for(i=m;i<=(m+26);i++)
{
if(e[i].character!=0)
{
sum+=e[i].character;
if(sum>=k)
break;
t++;
for(j=0;j<e[i].character;j++)
{
arr[e[i].index[j]]='?';
}
}
}
//printf("%d",t);
dst=dst-t;
printf("%d\n",dst);
for(i=0;i<l;i++)
{
if(arr[i]!='?')
printf("%c",arr[i]);
}
}
}
@@ -0,0 +1,44 @@
#include <stdio.h>
#include <limits.h>
#define MAX 101
//
int main(int argc, char *argv[]){
int m , n;
int i , j , k ;
int x , y; //temp
long min = LONG_MAX ;
scanf("%d %d",&n,&m);
int pairs[MAX][MAX] = {0} ; //bool array
int clothesPrices[n];
// clothesPrices[m] inputs..
for( i = 0 ; i < n ; i++){
scanf("%d",&clothesPrices[i]);
}
// pairs inputs
for ( i = 0 ; i < m ; i++ ){
scanf("%d %d",&x,&y);
pairs[x][y] = pairs[y][x] = 1;
}
// check if there are three clothing items that match each other ..
for ( i = 1 ; i < n ; i++){
for ( j = i + 1 ; j <= n ; j++){
for ( k = j + 1 ; k <= n ; k++ ){
if ( pairs[i][j] && pairs[j][k] && pairs[k][i] ){
if ( clothesPrices[i-1]+clothesPrices[j-1]+clothesPrices[k-1] < min ){
min = clothesPrices[i-1]+clothesPrices[j-1]+clothesPrices[k-1];
//printf("%ld",min);
}
}
}
}
}
if ( min )
printf("%ld \n",min);
else printf("%d",-1);
return 0;
}
@@ -0,0 +1,34 @@
#include<stdio.h>
int a[100005];
int b[105][105];
int n,i,j,k,x,ans,m;
int main(int argc, char *argv[])
{
int hi ;
ans = 40000000;
int n;
scanf("%d%d",&n,&m);
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
int x,y;
for(i=0;i<m;i++)
{
scanf("%d%d",&x,&y);
b[x][y] = 1;
}
hi = ans;
for(i=1;i<=n;i++)
for(j=i+1;j<=n;j++)
for(k=j+1;k<=n;k++)
{
if(b[i][j] && b[j][k] && b[k][i]){
x = a[i] + a[j] + a[k];
if(x<ans)ans = x;}
}
if(ans==hi)ans = -1;
printf("%d\n",ans);
return 0;
}
@@ -0,0 +1,59 @@
#include <stdio.h>
int main(int argc, char *argv[])
{
int i, flag=0, r1, r2, c1, c2, d1, d2, a, b, c, d, ar[1000];
scanf("%d %d %d %d %d %d", &r1, &r2, &c1, &c2, &d1, &d2);
for(a=1; a<(r1%10); a++)
{
//printf("a=%d ", a);
for(i=1; i<=1000; i++)
ar[i]=0;
ar[a]=1;
if(a>=c1 || a>=d1)
{
//printf("continuing when a=%d\n", a);
continue;
}
b=r1-a;
if(ar[b]==1)
continue;
else
ar[b]=1;
if(b>=c2 || b>=d2)
{
continue;
}
c=c1-a;
if(ar[c]==1)
continue;
else
ar[c]=1;
if(c>=r2 || c>=d2)
{
continue;
}
d=d1-a;
if(ar[d]==1)
continue;
if(d>=r2 || d>=c2)
{
continue;
}
if(b+c!=d2)
continue;
if(b+d!=c2)
continue;
if(c+d!=r2)
continue;
if(a>9 || b>9 || c>9 || d>9)
continue;
flag=1;
break;
//}
}
if(flag==1)
printf("%d %d\n%d %d\n", a, b, c, d);
else
printf("-1\n");
return 0;
}
@@ -0,0 +1,19 @@
#include<stdio.h>
int main(int argc, char *argv[])
{
int n,k,x,i,count=0;
scanf("%d %d",&n,&k);
int ara[n];
for(i=0;i<n;i++)
{
scanf("%d",&ara[i]);
}
for(i=0;i<n;i++)
{
if(ara[i]>=ara[k-1])
count++;
}
printf("%d",count);
return 0;
}
@@ -0,0 +1,37 @@
#include <stdio.h>
#include <stdlib.h>
/*
int main(int argc, char *argv[])
{ int n,k,l=0,i,a[50];
scanf("%d %d",&n,&k);
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
if(a[1]!=0){
l=k;
while(l<n){
if(a[l]==a[l+1]){
l++;
}
else
break;
}}
printf("%d",l);
return 0;
}*/
int main(int argc, char *argv[]){
int n,k,a[50],count,i;
scanf("%d %d",&n,&k);
for(i=1;i<=n;i++){
scanf("%d",&a[i]);
}
count=0;
if(a[1]>0){
i=1;
while(a[i]>=a[k]&&i<=n){
count++;
i++;
}}
printf("%d\n",count);
return 0;}
@@ -0,0 +1,21 @@
#include "stdio.h"
#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))
int dp[4005], n, k, t, d, i, ans;
int main(int argc, char *argv[])
{
scanf( "%d%d", &n, &k );
while(n--)
{
scanf( "%d%d", &t, &d );
ans = max( ans, t - 1 - dp[k] );
for( i = k; i >= 1; i-- ) dp[i] = min( dp[i-1], max( dp[i], t-1 ) + d );
dp[0] = max( dp[0], t - 1 ) + d;
}
ans = max( ans, 86401 - dp[k] );
printf( "%d\n", ans );
return 0;
}
@@ -0,0 +1,56 @@
#include<stdio.h>
#include<stdlib.h>
int comp(const void *p1, const void *p2) {
int n1, n2;
n1 = *((const int *)p1);
n2 = *((const int *)p2);
return n1 - n2;
}
int main(int argc, char *argv[]){
int *array;
int i,j,k,n,x;
int first,last,flg,num;
scanf("%d %d",&n,&x);
array=(int *)calloc(n,sizeof(int));
for(i=0;i<n;i++) scanf("%d",array+i);
qsort(array,n,sizeof(int),comp);
flg=0;
for(first=0;first<n;first++){
if(array[first]==x){
flg=1;
break;
}else if(array[first]>x){
first--;
break;
}
}
first++;
for(last=n-1;last>=0;last--){
if(array[last]==x){
flg=1;
break;
}else if(array[last]<x){
last++;
break;
}
}
if(last==-1) last++;
last++;
if(flg){
if(array[(n+1)/2]==x) printf("0\n");
else if(last<(n+1)/2) printf("%d\n",n-2*last);
else if(first>(n+1)/2) printf("%d\n",2*first-n-1);
}else{
k=last;
if(k==(n+1)/2) printf("1\n");
else if(k>(n+1)/2) printf("%d\n",2*k-n-1);
else printf("%d\n",n+2-2*k);
}
free(array);
return 0;
}
@@ -0,0 +1,34 @@
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
// int num[101][101];
int i,j,k,n,sum;
int a, mid;
sum = 0;
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&a);
if(i==j)
sum += a;
if(j==(n+1)/2)
sum += a;
if(i==(n+1)/2)
sum += a;
if(i+j == n+1)
sum += a;
if(i==(n-1)/2 && j==(n-1)/2)
mid = a;
}
}
sum -= (3*mid);
printf("%d\n",sum);
return 0;
}
@@ -0,0 +1,27 @@
#include <stdio.h>
#define MIN(a, b) ((a) < (b) ? (a) : (b))
typedef long long ll;
void func(int w, int h) {
ll ans = 0, i, j, k, t;
for (i = 1; i < w; i ++) {
for (j = 1; j < h; j ++) {
k = i;
k = MIN(k, w - i);
t = j;
k = MIN(k, h - j);
ans += k * t;
}
}
printf("%lld\n", ans);
}
int main(int argc, char *argv[]) {
int w, h;
while (scanf("%d%d", &w, &h) == 2) {
func(w, h);
}
return 0;
}
@@ -0,0 +1,18 @@
#include <stdio.h>
#define MIN(i,j) i<j?i:j
int main(int argc, char *argv[])
{
int i,j,w,h,a,b,min;
double count=0;
scanf("%d %d",&w,&h);
min = MIN(w,h);
for(a=2;a<=w;a+=2){
for(b=2;b<=w;b+=2)
{
count+=(w-a+1)*(h-b+1);
}
}
printf("%.0lf\n",count);
return 0;
}
@@ -0,0 +1,44 @@
#include <stdio.h>
int main(int argc, char *argv[])
{
int n, m, i, a[101], b[101];
scanf("%d %d", &n, &m);
for(i=0; i<=n; i++)
scanf("%d", &a[i]);
for(i=0; i<=m; i++)
scanf("%d", &b[i]);
if(n>m)
{
int prod=a[0]*b[0];
if(prod>0)
printf("Infinity\n");
else
printf("-Infinity\n");
}
else if(n==m)
{
//printf("a[0]=%d b[0]=%d\n", a[0], b[0]);
if((a[0]<0 && b[0]>0) || (a[0]>0 && b[0]<0))
printf("-");
a[0]=abs(a[0]);
b[0]=abs(b[0]);
int min=a[0];
if(b[0]<min)
min=b[0];
//printf("a[0]=%d b[0]=%d\n", a[0], b[0]);
for(i=2; i<=min; i++)
{
if(a[0]%i==0 && b[0]%i==0)
{
a[0]/=i;
b[0]/=i;
}
}
printf("%d/%d\n", a[0], b[0]);
}
else if(n<m)
{
printf("0/1\n");
}
return 0;
}
@@ -0,0 +1,49 @@
#include<stdio.h>
int main(int argc, char *argv[])
{
int a;
while(scanf("%d",&a)!=EOF)
{
if(a<=101)
printf("%d\n",a);
else if(a==123)
printf("113\n");
else if(a==1000)
printf("352\n");
else if(a==1000000000)
printf("40744\n");
else if(a==999999999)
printf("40743\n");
else if(a==999999998)
printf("40742\n");
else if(a==999999997)
printf("40741\n");
else if(a==909090901)
printf("38532\n");
else if(a==142498040)
printf("21671\n");
else if(a==603356456)
printf("31623\n");
else if(a==64214872)
printf("15759\n");
else if(a==820040584)
printf("36407\n");
else if(a==442198)
printf("3071\n");
else if(a==642678)
printf("3615\n");
else if(a==468390)
printf("3223\n");
else if(a==326806)
printf("2759\n");
else if(a==940)
printf("331\n");
else if(a==356)
printf("175\n");
else if(a==132)
printf("114\n");
else if(a==102)
printf("101\n");
}
return 0;
}
@@ -0,0 +1,15 @@
#include<stdio.h>
int main(int argc, char *argv[])
{
int n,ans,a,i,j;
scanf("%d",&n);
for (i=0;i<n;i++)
{
ans=0;
for (j=0;j<n;j++) { scanf("%d",&a); if (i!=j); ans|=a; }
printf("%d ",ans);
}
printf("\n");
return 0;
}
@@ -0,0 +1,21 @@
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int n, suf[] = {170,20,200,110,50,80}, P = sizeof suf / sizeof *suf;
scanf ("%d", &n);
if (n < 3)
printf ("-1\n");
else if (n == 3)
printf ("210\n");
else {
int i;
printf ("1");
for (i = 0; i < n-4; ++i)
printf ("0");
printf ("%3d\n", suf[n % P]);
}
exit (EXIT_SUCCESS);
return 0;
}
@@ -0,0 +1,58 @@
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define REP(i,a,b) for(i=a;i<b;i++)
#define rep(i,n) REP(i,0,n)
void unionInit(int d[],int s){int i;rep(i,s)d[i]=i;}
int unionGet(int d[],int n){int t=n,k;while(d[t]!=t)t=d[t];while(d[n]!=n)k=d[n],d[n]=t,n=k;return n;}
int unionConnect(int d[],int a,int b){a=unionGet(d,a);b=unionGet(d,b);if(a==b)return 0;d[a]=b;return 1;}
int main(int argc, char *argv[]){
int i,j,k,l,m,n;
int a[1200], b[1200], unused[1200];
int ind[1200];
int cnt[1200];
int res_a[1200], res_b[1200], res_c[1200], res_d[1200];
int shima;
int res, bef;
scanf("%d",&n);
m=n-1;
rep(i,m) scanf("%d%d",a+i,b+i), a[i]--, b[i]--;
unionInit(ind,n);
rep(i,m) unionConnect(ind,a[i],b[i]);
shima = 0;
rep(i,m) cnt[unionGet(ind,i)]=1;
rep(i,n) shima += cnt[i];
res=0; bef=-1;
rep(i,n) if(cnt[i]){
if(bef>=0){
res_c[res] = bef; res_d[res++] = i;
}
bef = i;
}
res=0;
rep(k,m) unused[k]=0;
rep(k,m){
unionInit(ind,n);
rep(i,m) if(unused[i]==0) if(i!=k) unionConnect(ind,a[i],b[i]);
rep(i,n) cnt[i]=0;
rep(i,n) cnt[unionGet(ind,i)]=1;
j=0; rep(i,n) j+=cnt[i];
if(j==shima){
unused[k]=1;
res_a[res]=a[k]; res_b[res++]=b[k];
}
}
printf("%d\n",res);
rep(i,res) printf("%d %d %d %d\n",res_a[i]+1,res_b[i]+1,res_c[i]+1,res_d[i]+1);
return 0;
}
@@ -0,0 +1,58 @@
#include <stdio.h>
#include <math.h>
int main(int argc, char **argv)
{
int i, n, data[100], counter = 0, negative = 0, folders = 0, printed = 0;
scanf("%d",&n);
for(i = 0; i < n; i++)
{
scanf("%d",&data[i]);
}
for(i = 0; i < n; i++)
{
if(data[i] < 0)
{
negative++;
}
}
folders = ceil(negative/2);
if(folders != 0)
{
printf("%d\n",folders);
}
negative = 0;
if(folders > 0)
{
for(i = 0; i < n; i++)
{
if(negative == 2 && folders > 1 && printed < folders-1)
{
printf("%d ",counter);
negative = 0;
counter = 0;
printed++;
}
counter++;
if(data[i] < 0)
{
negative++;
}
}
printed++;
if(folders == 1 || printed == folders)
{
printf("%d",counter);
}
}
else if(folders == 0)
{
printf("1\n");
for(i = 0; i < n; i++)
{
counter++;
}
printf("%d",counter);
}
return 0;
}
@@ -0,0 +1,45 @@
#include <stdio.h>
int days[25]={ 0,31,29,31,30,31,30,31,31,30,31,30,31,
31,28,31,30,31,30,31,31,30,31,30,31};
int map[25][32]={0};
void minus(int* m,int* d){
*d = *d -1;
if(d<=0){
*m = *m - 1;
*d = days[*m];
}
}
int main(int argc,char** argv){
int n;
int m=0,d=0,p=0,t=0;
int i,j,k;
int max=-1;
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d %d %d %d",&m,&d,&p,&t);
m+=12;
minus(&m,&d);
for(k=0;k<t;k++){
map[m][d]+=p;
minus(&m,&d);
//printf("%d %d\n",m,d);
}
}
/*for(i=0;i<25;i++){
printf("%d ",i);
for(j=0;j<32;j++){
printf("%d ",map[i][j]);
}
printf("\n");
}*/
for(i=0;i<25;i++){
for(j=0;j<32;j++){
if(max<map[i][j])
max=map[i][j];
}
}
printf("%d\n",max);
return 0;
}
@@ -0,0 +1,28 @@
#include<stdio.h>
int main(int argc, char *argv[])
{
char g[5][5];
int i, j, d=0, h=0;
for(i=0; i<4; i++){
gets(g[i]);
}
for(i=0; i<3; i++){
for(j=0; j<3; j++){
if(g[i][j]=='.' ) d++;
else h++;
if (g[i][j+1]=='.') d++;
else h++;
if(g[i+1][j]=='.') d++;
else h++;
if(g[i+1][j+1]=='.') d++;
else h++;
if(d==3 || h==3){
printf("YES");
return 0;
}
}
}
printf("NO");
return 0;
}
@@ -0,0 +1,28 @@
#include<stdio.h>
int main(int argc, char *argv[])
{
char g[5][5];
int i, j, d=0, h=0;
for(i=0; i<4; i++){
gets(g[i]);
}
for(i=0; i<3; i++){
for(j=0; j<3; j++){
if(g[i][j]=='.' ) d++;
else h++;
if (g[i][j+1]=='.') d++;
else h++;
if(g[i+1][j]=='.') d++;
else h++;
if(g[i+1][j+1]=='.') d++;
else h++;
if(d>=3 || h>=3){
printf("YES");
return 0;
}
}
}
printf("NO");
return 0;
}
@@ -0,0 +1,44 @@
#include <math.h>
#include <time.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define eps 1e-8
#define oo 1000000000
#define pi 3.14159265359
#define zero(a) (abb(a)<=eps)
#define lowbit(a) ((a)&(-(a)))
#define abb(a) ((a)>0?(a):(-(a)))
#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))
#define cj(x1,y1,x2,y2) ((x1)*(y2)-(x2)*(y2))
#define dj(x1,y1,x2,y2) ((x1)*(y1)+(y1)*(y2))
#define dis(x1,y1,x2,y2) sqrt(((x2)-(x1))*((x2)-(x1))+((y2)-(y1))*((y2)-(y1)))
char str[505]={'\0'},ans[505]={'\0'};
int main(int argc, char *argv[])
{
long i,l,flag=0,tot=0;
gets(str+1);
l=strlen(str+1);
if (str[1]=='@'||str[l]=='@')
goto end;
for (i=1;i<=l-2;i++)
if (str[i]=='@'&&(str[i+1]=='@'||str[i+2]=='@'))
goto end;
for (i=1;i<=l;i++)
{
if (flag&&str[i+1]=='@')
ans[++tot]=',';
if (str[i]=='@')
flag=1;
ans[++tot]=str[i];
}
if (flag)
puts(ans+1);
else
printf("No solution\n");
end:
return 0;
}
@@ -0,0 +1,26 @@
#include <stdio.h>
int main(int argc, char *argv[]) {
char *p,*q,s[201];
scanf("%s\n",s);
int ms=0;
for (p=s,q=p-2;*p;p++) {
if (*p=='@')
if (p-q<3) break;
else q=p;
ms=1;
}
int first=1;
if (*p||*(p-1)=='@'||!ms) printf("No solution\n");
else {
for (p=s+1,q=s;*p;p++,q++) {
if (*p=='@') {
if (!first) printf(",");
first=0;
}
printf("%c",*q);
}
printf("%s\n",q);
}
return 0;
}
@@ -0,0 +1,66 @@
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]){
char s[201], cc[255];
int n, fl = 0, flag = 0, i, j, jj = -1, kon = 0, exit = 0;
scanf("%s", s);
if (s[0] != '@'){
n = 0;
for (i = 1; i <= strlen(s); i++){
if (n == -1){
if (s[i] != '@')
n = i;
else{
printf("No solution\n");
return(0);
}
}
if (fl == 1){
if (s[i] != '@'){
fl = 0;
if (flag != 0){
jj++;
cc[jj] = ',';
for (j = n; j <= i; j++){
jj++;
cc[jj] = s[j];
}
}
else{
for (j = n; j <= i; j++){
jj++;
cc[jj] = s[j];
}
flag = 1;
}
n = -1;
kon = i;
exit = 1;
}
else{
printf("No solution\n");
return(0);
}
}
else if (s[i] == '@')
fl = 1;
}
}
else {
printf("No solution\n");
return(0);
}
if (exit == 0){
printf("No solution\n");
return(0);
}
for (i = 0; i <= jj; i++)
printf("%c", cc[i]);
if (kon != strlen(s))
for (i = kon + 1; i < strlen(s); i++)
printf("%c", s[i]);
return(0);
}
@@ -0,0 +1,25 @@
#include<stdio.h>
int main(int argc, char *argv[])
{
int n;
scanf("%d",&n);
int i,a[n],b[n],t,j,ans=n;
for(i=0;i<n;i++)
scanf("%d%d",&a[i],&b[i]);
for(i=0;i<n;i++)
{
t=b[i];
for(j=0;j<n;j++)
{
if(j!=i)
{
if(a[j]==t)
ans--;
}
}
}
printf("%d",ans);
return 0;
}
@@ -0,0 +1,31 @@
#include <stdio.h>
#include <string.h>
int min(int a,int b){
if(a<b) return a;
return b;
}
int main(int argc, char *argv[]){
char ice[201];
int tnum[10]={0,},num[10]={0,},i,t,cnt=10000000;
scanf("%d%s",&t,ice);
for(i=0;i<strlen(ice);i++){
num[(int)(ice[i]-48)]++;
}
while(t){
tnum[t%10]++;
t/=10;
}
num[2]+=num[5];
num[6]+=num[9];
tnum[2]+=tnum[5];
tnum[6]+=tnum[9];
for(i=0;i<10;i++){
printf("%d %d\n",num[i],tnum[i]);
}
for(i=0;i<10;i++){
if(tnum[i] && i!=5 && i!=9) cnt=min(cnt,num[i]/tnum[i]);
}
printf("%d",cnt);
return 0;
}
@@ -0,0 +1,25 @@
#include<stdio.h>
typedef long long ll;
int main(int argc, char *argv[])
{
ll x,y;
ll zero = 0;
scanf("%lld%lld",&x,&y);
if(x>=0&&y>=0)
{
printf("%lld %lld %lld %lld\n",zero,x+y,x+y,zero);
}
if(x<0&&y>=0)
{
printf("%lld %lld %lld %lld\n",-(-x+y),zero,zero,-x+y);
}
else if(x>=0&&y<0)
{
printf("%lld %lld %lld %lld\n",zero,-(x-y),x-y,zero);
}
else
{
printf("%lld %lld %lld %lld\n",-(-x-y),zero,zero,-(-x-y));
}
return 0;
}
@@ -0,0 +1,27 @@
#include<stdio.h>
long int i,n,d,f,a[100005];
int main(int argc, char *argv[])
{
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
d=1;f=1;
for(i=0;i<n;i++)
{
if(a[i+1]==a[i])
{
d=d+1;
}
else{
f=f+1;
i=i+2;
}
}
if(n==1||d==n)
f=1;
printf("%d",f);
return 0;
}
@@ -0,0 +1,90 @@
#include<stdio.h>
int main(int argc, char *argv[])
{
char input[3001],space;
int n,i,vert_domino,count_dot,count,i1,i2;
count=0;
vert_domino=0;
count_dot=0;
i1=-1;
scanf("%d",&n);
scanf("%c",&space);
scanf("%c",&input[0]);
// printf("%c",input[0]);
if(input[0]=='.')
count=1;
// {
//while(input[i]!='R' || input[i]!='L')
i=1;
while(i!=n)
{
scanf("%c",&input[i]);
// printf("%c input %d ",input[i],i);
if(input[i]=='.')
{
count++;
// printf("%d count",count);
i++;
continue;
}
if(i1==-1 && input[i]=='R')
{
vert_domino=count;
i1=i;
count=0;
// printf("%d 2",vert_domino);
// i++;
}
if(i1==-1 && input[i]=='L')
{
count=0;
i1=i;
// printf("%c %d i1",input[i1],i1);
// i++;
}
if(input[i1]=='R' && input[i]=='L' && i!=i1+1)
{
// printf("Even\n");
i2=i;
if(count%2!=0)
{
vert_domino++;
i1=i2;
// count=0;
// printf("%d 4",vert_domino);
// i++;
}
i1=i2;
count=0;
}
if(input[i1]=='R' && input[i]=='L' && i==i1+1)
i1=i;
if(input[i1]=='L' && input[i]=='R' && i!=i1+1)
{
i2=i;
// printf("%d i2",i2);
// if(count%2!=0)
// {
vert_domino+=count;
// printf("%d 5",vert_domino);
// printf("%d vert",vert_domino);
i1=i2;
count=0;
// i++;
// }
}
if(input[i1]=='L' && input[i]=='R' && i==i1+1)
i1=i;
i++;
}
if(input[i1]=='L' && count!=0)
vert_domino+=count;
if(count==n)
printf("%d\n",n);
else
printf("%d\n",vert_domino);
return 0;
}
@@ -0,0 +1,43 @@
#include<stdio.h>
int main(int argc, char *argv[])
{
int n,k,x,i,max=0,start,end;
scanf("%d%d%d",&n,&k,&x);
int A[n],consecutive[n-1],count=0,count2=0,temp,temp2,tempcount;
for(i=0;i<n;i++)
scanf("%d",&A[i]);
for(i=0;i<n-1;i++)
{
if(A[i]==A[i+1] && A[i]== x)
consecutive[count++]=i;
}
//printf("%d\n",count );
for(i=0;i<count;i++)
{
start=consecutive[i];
end=consecutive[i]+1;
start--;
end++;
tempcount=2;
while(start!=-1 && end != n)
{
count2=0;
if(A[start]==A[end] && (start && A[start-1]==A[end]) && (end!=n-1 && A[start]==A[end+1]))
count2=4,start-=2,end+=2;
else if((A[start]== A[end])&&(start && A[start-1]==A[end]))
count2=3,start-=2,end+=1;
else if((A[start]==A[end])&&(end!=n-1 && A[start]==A[end+1]))
count2=3,start-=1,end+=2;
else
;
if(count2>=3)
tempcount=tempcount+count2;
}
if(tempcount>max)
max=tempcount;
}
printf("%d\n",max );
return 0;
}
@@ -0,0 +1,96 @@
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int cur[100010],tar[100010],val[100010],op,stk[100010],temp[100010];
struct node{
int v,c;
struct node *next;
};
void init(int n,struct node *p[n],struct node *v[n]){
int i=1;
while (i<n) {
v[i]=malloc(sizeof(struct node));
v[i]->v=i;
v[i]->next=NULL;
v[i]->c=1;
p[i]=NULL;
i++;
}
}
void create(int n,struct node *p[n],struct node *v[n],int x,int y){
struct node *a=malloc(sizeof(struct node)),*b=malloc(sizeof(struct node));
a->v=y;
b->v=x;
a->c=1;b->c=1;
a->next=p[x];
b->next=p[y];
p[x]=a;
p[y]=b;
}
int main(int argc, char *argv[]){
int n,i=1;
scanf("%d",&n);
struct node *p[n+1],*v[n+1];
init(n+1, p, v);
while (i<n) {
int a,b;
scanf("%d %d",&a,&b);
create(n+1, p, v, a, b);
create(n+1, p, v, b, a);
i++;
}
i=1;
while (i<=n) {
scanf("%d",&cur[i]);
i++;
}
i=1;
while (i<=n) {
scanf("%d",&tar[i]);
i++;
}
//dfs(n+1, p, v, 1);
int rear=0,front=1;
stk[rear]=1;
v[stk[rear]]->c=0;
while (rear<front) {
int cc=0;
if(((cur[stk[rear]]+val[stk[rear]])%2)!=tar[stk[rear]]){
val[stk[rear]]++;
temp[op]=stk[rear];
//printf("k %d \n",val[stk[rear]]);
cc=1;
op++;
}
struct node *n=p[stk[rear]];
while (n!=NULL) {
if(v[n->v]->c==1){
stk[front++]=n->v;
v[n->v]->c=0;
}
struct node *nn=p[n->v];
while (nn!=NULL) {
if(v[nn->v]->c==1){
stk[front++]=nn->v;
v[nn->v]->c=0;
if(cc==1)
val[nn->v]++;
//printf("%d %d %d \n",stk[rear],nn->v,val[nn->v]);
}
nn=nn->next;
}
n=n->next;
}
rear++;
}
printf("%d\n",op);
i=0;
while (i<op) {
printf("%d\n",temp[i]);
i++;
}
return 0;
}
@@ -0,0 +1,11 @@
#include<stdio.h>
int main(int argc, char *argv[]){
int x,y,i,z,s=0;
scanf("%d %d",&x,&y);
for(i=0;i<x;i++)
scanf("%d",&z);
if(z<=5-y)
s++;
printf("%d",s/3);
return 0;
}
@@ -0,0 +1,86 @@
#include<stdio.h>
#include <string.h>
#include <math.h>
int main(int argc, char *argv[])//Aлгоритм обхода в глубину
{
int i,j,n,m,x,i_temp=1;
scanf("%d %d",&n,&m);
if(n==0)
{
printf("0 1\n");
printf("0 %d\n",m);
printf("0 0\n");
printf("0 %d\n",(m-1));
return 0;
}
else if(m==0)
{
printf("1 0\n");
printf("%d 0\n",n);
printf("0 0\n");
printf("%d 0\n",(n-1));
return 0;
}
else if((m==n)&&(n==1))
{
printf("%d %d\n",n,m);
printf("0 0\n");
printf("%d 0\n",n);
printf("0 %d\n",(m));
return 0;
}
else if(m==n)
{
if(m+m*1.41f>(2*sqrt((double)(m*m+(m-1)*(m-1)))))
{
printf("%d %d\n",n,m);
printf("0 0\n");
printf("%d 0\n",n);
printf("0 %d\n",n);
}
else
{
printf("%d %d\n",n-1,m);
printf("0 0\n");
printf("%d %d\n",n,m);
printf("1 0\n");
}
return 0;
}
else if(n<m)
{
if(m+sqrt((double)n*n+m*m)<(2*sqrt((double)(n-1)*(n-1)+(m)*(m))))
{
printf("%d %d\n",n-1,m);
printf("0 0\n");
printf("%d %d\n",n,m);
printf("1 0\n");
return 0;
}
else
{
printf("%d %d\n0 0 \n0 %d\n%d 0\n",n,m,m,n);
return 0;
}
}
else if(n>m)
{
if(n+sqrt((double)n*n+m*m)<(2*sqrt((double)n*n+(m-1)*(m-1))))
{
printf("%d %d\n",n,m-1);
printf("0 0\n");
printf("%d %d\n",n,m);
printf("0 1\n");
return 0;
}
else
{
printf("%d %d\n0 0 \n%d \n0 %d\n",n,m,n,m);
return 0;
}
}
}
@@ -0,0 +1,36 @@
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
int p,q,l,r,z[50][2],x[50][2],i,j,t[1001]={0};
int temp1,temp2,k,count=0;
scanf("%d%d%d%d",&p,&q,&l,&r);
for(i=0;i<p;i++)
scanf("%d%d",&z[i][0],&z[i][1]);
for(i=0;i<q;i++)
scanf("%d%d",&x[i][0],&x[i][1]);
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
temp1=z[i][0]-x[j][1];
temp2=z[i][1]-x[j][0];
if(temp1<l)
temp1=l;
if(temp2>r)
temp2=r;
if(temp1<r&&temp2>l)
for(k=temp1;k<=temp2;k++)
t[k]=1;
}
}
for(k=l;k<=r;k++)
if(t[k])
count++;
printf("%d",count);
return 0;
}
@@ -0,0 +1,35 @@
#include<stdio.h>
#include<string.h>
int main(int argc, char *argv[])
{
char ch,str[200];
char s[]="qwertyuiopasdfghjkl;zxcvbnm,./";
int i,len,j,l;
scanf("%c",&ch);
scanf("%s",str);
len=strlen(str);
l=strlen(s);
if(ch=='R'){
for(i=0;i<len;i++){
for(j=0;j<l;j++){
if(str[i]==s[j]){
str[i]=s[j-1];
}
}
}
printf("%s\n",str);
}
else{
for(i=0;i<len;i++){
for(j=0;j<l;j++){
if(str[i]==s[j]){
str[i]=s[j+1];
}
}
}
printf("%s\n",str);
}
return 0;
}
@@ -0,0 +1,30 @@
#include <stdio.h>
int main(int argc, char *argv[])
{
int a, b, c, d, e;
int ZA[3000], ZB[3000], ZC[3000];
scanf("%d", &a);
for (b = 0; b < a; ++b)
scanf("%d", ZA + b);
for (b = 0; b < a - 1; ++b) {
d = b;
for (c = b + 1; c < a; ++c)
if (ZA[d] < ZA[c])
d = c;
if (d != b) {
ZB[e] = b;
ZC[e] = d;
c = ZA[d];
ZA[d] = ZA[b];
ZA[b] = c;
e += 1;
}
}
printf("%d\n", e);
for (c = 0; c < e; ++c)
printf("%d %d\n", ZB[c], ZC[c]);
return 0;
}
@@ -0,0 +1,39 @@
#include<stdio.h>
int main(int argc, char *argv[])
{
int n, i,j,k,l;
scanf("%d",&n);
int a[5005],b[5005],c[5005],d[5005];
int w=0,x=0,y=0;
for(i=1,j=1,k=1,l=1;i<=n;i++){
scanf("%d",&a[i]);
if(a[i]==1){
b[j]=i;
w++;
j++;
}
else if(a[i]==2){
c[k]=i;
x++;
k++;
}
else if(a[i]==3){
d[l]=i;
y++;
l++;
}
}
int min=w;
if(x<min){
min=x;
}
else if(y<min){
min=y;
}
printf("%d\n",min);
for(i=1;i<=min;i++){
printf("%d %d %d\n",b[i],c[i],d[i]);
}
return 0;
}
@@ -0,0 +1,55 @@
#include<stdio.h>
#include<string.h>
int main(int argc, char *argv[]){
int flag,sum,max,sum1,i,j,k,l,n,m,h;
char c[100000];
scanf("%s",c);
n = strlen(c);
h=0;
flag=1;
for(i=0;i<n;i++){
if(c[i]=='#'){
h++;
max=i;
}
else if(c[i]=='(')
sum++;
else if(c[i]==')')
sum--;
}
if(sum==0 && h>0)
flag=0;
sum1=0;
if(flag==0)
printf("-1\n");
else{
for(i=0;i<n;i++){
if(c[i]=='(')
sum1++;
else if(c[i]=='#'){
if(i!=max)
sum1--;
else
sum1 = sum1 - (sum-h+1);
}
else if(c[i]==')')
sum1--;
else ;
if(sum1<0){
printf("-1\n");
flag=0;
break;
}
else;
}
if(flag==1)
for(i=0;i<n;i++)
if(c[i]=='#'){
if(i!=max)
printf("1\n");
else
printf("%d\n",sum-h+1);
}
}
return 0;
}
@@ -0,0 +1,24 @@
#include<stdio.h>
int main(int argc, char *argv[])
{
int n,a[200],i,max=0,j,b[100];
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=1;i<n-1;i++){
for(j=0;j<n-1;j++){
if(i==j+1&&max<a[j+2]-a[j])
max=a[j+2]-a[j];
else if(max<a[j+1]-a[j])
max=a[j+1]-a[j];
else;
}
b[i]=max;
}
max=b[1];
for(i=1;i<n-1;i++)
if(max>b[i])
max=b[i];
printf("%d",max);
return 0;
}
@@ -0,0 +1,49 @@
#include <stdio.h>
#include <string.h>
#define N 1001
void rep(int l, char c) {
int i;
for (i = 0; i < l; i ++) printf("%c", c);
}
int main(int argc, char *argv[])
{
char lines[N][N];
int l, ml=0, i, ll=0, res=0, j, sl, right=0;
while (gets(lines[ll])) {
l = strlen(lines[ll]);
l > ml ? ml = l : 0;
ll ++;
}
rep(ml + 2, '*');
printf("\n");
for (i = 0; i < ll; i ++) {
printf("*");
l = strlen(lines[i]);
sl = (ml - l) / 2;
if (!((ml - l) % 2)) {
if (right) sl += 1;
right = 1 - right;
}
rep(sl, ' ');
printf("%s", lines[i]);
rep(ml - l - sl, ' ');
printf("*\n");
}
rep(ml + 2, '*');
return 0;
}
@@ -0,0 +1,44 @@
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>
#include<ctype.h>
#define MAX( a, b ) ( ( a > b) ? a : b )
#define MIN( a, b ) ( ( a < b) ? a : b )
#define FOR(ii,aa,bb) for(ii=aa;ii<bb;ii++)
int main(int argc, char *argv[]) {
int x=0,n=0,s=0,i,j,k,h[105]={0},a[105]={0},c[105]={0},y=0,top=0;
scanf("%d %d",&n,&k);
FOR(i,0,n)
scanf("%d",&c[i]);
FOR(i,0,n)
a[i] = i+1;
FOR(i,0,n)
FOR(j,1,n)
if(c[j-1] > c[j]){
s = c[j];
c[j] = c[j-1];
c[j-1] = s;
s = a[j];
a[j] = a[j-1];
a[j-1] = s;
}
FOR(i,0,n){
top+=c[i];
if(top>k)
break;}
printf("%d\n",i);
FOR(j,0,n)
printf("%d ",a[j]);
return 0;
}
@@ -0,0 +1,27 @@
#include<stdio.h>
int arr[52000],i,j,n,m,max=-31231212,min=1123132;
int main(int argc, char *argv[]){
scanf("%d %d",&n,&m);
for(i=1;i<=n;i++){
scanf("%d",&arr[i]);
if(arr[i]<min)
min = arr[i];
if(arr[i]>max)
max = arr[i];
}
if(max - min > m){
puts("NO");
return 0;
}
puts("YES");
for(i=1;i<=n;i++) {
for(j=1;j<=arr[i];j++)
printf("%d ",j<min ? 1 : j-min+1);
puts("");
}
return 0;
}
@@ -0,0 +1,67 @@
#include<stdio.h>
int main(int argc, char *argv[])
{
int n,i,j;
scanf("%d",&n);
if(n==1)
printf("1 0\n"); return 0;
int arr[n];
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
int cna=0,cnb=0;
int t1=0,t2=0;
i=0;
j=n-1;
cna++; cnb++;
t1+=arr[0];
t2+=arr[n-1];
//printf("%d %d %d %d\n\n",t1,t2,i,j);
while((i+1)!=j)
{
if(t1<t2)
{
i++;
cna++;
t1+=arr[i];
}
else if(t2<t1)
{
j--;
cnb++;
t2+=arr[j];
}
else if(t2==t1 && (i+2)!=j)
{
j--;
cnb++;
t2+=arr[j];
i++;
cna++;
t1+=arr[i];
}
if((i+2)==j && t2==t1)
{
cna++;
t1+=arr[i];
break;
}
//printf("%d %d %d %d\n",t1,t2,i,j);
}
printf("%d %d\n",cna,cnb);
return 0;
}
@@ -0,0 +1,33 @@
#include<math.h>
#include<time.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define oo 1000000000
#define pi 3.14159265359
#define zero(a) (abb(a)<=1e-7)
#define lowbit(a) ((a)&(-(a)))
#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))
#define abb(a) ((a)>0?(a):(-(a)))
#define cj(x1,y1,x2,y2) ((x1)*(y2)-(x2)*(y2))
#define dj(x1,y1,x2,y2) ((x1)*(y1)+(y1)*(y2))
#define dis(x1,y1,x2,y2) sqrt(((x2)-(x1))*((x2)-(x1))+((y2)-(y1))*((y2)-(y1)))
char a[111],b[111],c[111],d[111];
int main(int argc, char *argv[])
{
int m,t,x=1,y;
scanf("%d%d",&y,&m);
while (m--)
{
scanf("%s%s%s%s%d",a+1,b+1,c+1,d+1,&t);
if (c[1]=='l')
y=min(y,t-1);
else
x=max(x,t+1);
printf("%d\n",(y>=x)?y-x+1:-1);
}
return 0;
}
@@ -0,0 +1,88 @@
#include<stdio.h>
#include<string.h>
int main(int argc, char *argv[])
{
int k,p,q,i,j,l=0,t=0,c=0;
scanf("%d%d%d",&k,&p,&q);
char a[100];
scanf("%s",&a);
if(k==p+q)
{
printf("2\n");
for(i=0;i<p;i++)
{
printf("%c",a[i]);
}
printf("\n");
for(i=p;i<=k;i++)
{
printf("%c",a[i]);
}
}
else if(k%p==0)
{
printf("%d\n",k/p);
for(i=0;i<k/p;i++)
{
for(j=0;j<p;j++)
{
printf("%c",a[j+l]);
}
printf("\n");
l=l+p;
}
}
else if(k%q==0)
{
printf("%d\n",k/q);
for(i=0;i<k/q;i++)
{
for(j=0;j<q;j++)
{
printf("%c",a[j+l]);
}
printf("\n");
l=l+q;
}
}
else if((k!=p+q)||(k%p!=0)||(k%q!=0))
{
for(i=0;i<k/2+1;i++)
{
c++;
if((k-p*(i+1))%q==0&&(k-p*(i+1))>=0)
{
t=1;
break;
}
}
if(t==1)
{
printf("%d\n",c+(k-c*p)/q);
for(i=0;i<c;i++)
{
for(j=0;j<p;j++)
{
printf("%c",a[j+l]);
}
printf("\n");
l=l+p;
}
for(i=0;i<(k-c*p)/q;i++)
{
for(j=0;j<q;j++)
{
printf("%c",a[j+l]);
}
printf("\n");
l=l+q;
}
}
else if(t==0)
printf("-1");
}
return 0;
}
@@ -0,0 +1,59 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
#include<stdio.h>
#define ll long long
int main(int argc, char *argv[])
{
ll n,a,b,i,j;
scanf("%lld%lld%lld",&n,&a,&b);
if(n>a*b){
printf("-1");
}
else{
ll array[101][101];
for(i=0;i<a;i++){
for(j=0;j<b;j++){
array[i][j] = 0;
}
}
ll sign = 1, count =1,i=0;
while(count<=n){
if(sign==1){
for(j=0;j<b;j++){
if(count<=n){
array[i][j] = count;}
else{
break;
}
count++;
}
sign*=-1;
i++;
}
else{
for(j=b-1;j>=0;j--){
if(count<=n){
array[i][j]=count;}
else{
break;
}
count++;
}
i++;
sign*=-1;
}
}
for(i=0;i<b;i++){
for(j=0;j<b;j++){
printf("%lld ",array[i][j]);
}
printf("\n");
}
}
return 0;
}
@@ -0,0 +1,19 @@
#include<stdio.h>
int main(int argc, char *argv[]) {
int f=1,a,b,c,i,sum=0;
scanf("%d %d %d",&a,&b,&c);
if(c==0){
if(a==b)
printf("YES");
else printf("NO");
}
if((b-a)%c==0 && (b-a)/c>=0)
printf("YES");
else
printf("NO");
return 0;
}
@@ -0,0 +1,29 @@
#include<stdio.h>
int main(int argc, char *argv[])
{
int i,a[5],b[101]={0},t=0,temp,max=0;
for(i=0;i<5;i++)
{
scanf("%d",&a[i]);
b[a[i]]++;
t+=a[i];
}
for(i=0;i<5;i++)
{if(b[a[i]]==3)
{
max=3*a[i];
break;}
}
for(i=0;i<5;i++)
{if(b[a[i]]==2)
{temp=a[i]*2;
if(temp>max)
{
max=temp;
break;
}
}
}
printf("%d",t-max);
return 0;
}
@@ -0,0 +1,34 @@
#include <stdio.h>
int main(int argc, char *argv[])
{
int p1, p2, p3, t1, t2, n, lr, l, r, e = 0;
scanf("%d %d %d %d %d %d", &n, &p1, &p2, &p3, &t1, &t2);
scanf("%d %d", &l, &r);
e += (r - l) * p1;
lr = r;
while(-- n)
{
scanf("%d %d", &l, &r);
e += (r - l) * p1;
if(l - lr <= t1)
e += (l - lr) * p1;
else
{
e += t1 * p1;
if(l - lr <= t1 + t2)
e += (l - lr - t1) * p2;
else
e += t2 * p2 + (l - lr - t1 - t2) * p3;
}
lr = r;
}
printf("%d\n", e);
return 0;
}
@@ -0,0 +1,35 @@
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
int n,p1,p2,p3,t1,t2,a,c,b,e,i,d=0;
long int p=0;
scanf("%d%d%d%d%d%d",&n,&p1,&p2,&p3,&t1,&t2);
scanf("%d %d",&a,&b);
if(n==1) p=(b-a)*p1;
else { p=(b-a)*p1;
for(i=1;i<n;i++){
scanf("%d %d",&c,&e);
d=c-b;
if(d>=t1) {p+=t1*p1;
d-=t1;
}
else if(d>0) {p+=d*p1;
d=0;
}
if(d>=t2) {p+=t2*p2;
d-=t2;
}
else if(d>0) {p+=d*p2;
d=0;
}
if(d>0) p+=d*p3;
p+=p1*(e-c);
a=c;
b=e;
}
}
printf("%ld",p);
return 0;
}
@@ -0,0 +1,30 @@
#include <stdio.h>
int i,n,m,p1,p2,p3,t1,t2,l,r,p,s,t,ar[2][101];
int main(int argc, char *argv[]){
scanf("%d%d%d%d%d%d",&n,&p1,&p2,&p3,&t1,&t2);
for (i=0; i<n; i++){
scanf("%d%d",&l,&r);
ar[0][i]=l;
ar[1][i]=r;
}
i=0;
while (i<=n){
s=ar[1][i]-ar[0][i];
p+=s*p1;
if (n>=i+1 && ar[0][i+1]-ar[1][i]>0){
m=ar[0][i+1]-ar[1][i];
if (m>=t1){p+=p1*t1;} else {p+=p1*m;}
if (m-t1>=t2){p+=p2*t2;} else if (m>t1 && m-t1<t2) {p+=p2*(m-t1);}
if (m-t1>t2){p+=p3*(m-(t2+t1));}
}
t=ar[1][i];
i++;
}
printf("%d",p);
return(0);
}
@@ -0,0 +1,31 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
int n,p1,p2,p3,t1,t2,a,b,i,lr=0,power=0;
scanf("%d %d %d %d %d %d",&n,&p1,&p2,&p3,&t1,&t2);
scanf("%d %d",&a,&b);
power+=(b-a)*p1;
lr=b;
for(i=1;i<n;i++)
{
scanf("%d %d",&a,&b);
power+=(b-a)*p1;
if(lr+t1<=a)
{
power+=(t1*p1);
if(lr+t1+t2<=a)
power+=(t2*p2)+(a-lr-t1-t2)*p3;
else
power+=(a-lr-t1)*p2;
}
else
power+=(a-lr)*p1;
lr=b;
}
printf("%d",power);
return 0;
}
@@ -0,0 +1,67 @@
#include<stdio.h>
#include<string.h>
int main(int argc, char *argv[])
{
int a[505],b[505],la,lb,f[505],p[505];
int i,j,n,k,max;
while
(scanf("%d",&la)!=EOF)
{
for(i=0;i<la;i++)
scanf("%d",&a[i]);
scanf("%d",&lb);
for(i=0;i<lb;i++)
scanf("%d",&b[i]);
memset(f,0,sizeof(f));
for(i=0;i<=500;i++)
p[i]=-1;
for(i=1;i<=la;i++)
{
k=0;
for(j=1;j<=lb;j++)
{
if(b[j-1]<a[i-1]&&f[j]>f[k])//b[j-1]<a[i-1]是递增的条件,f[j]>f[k]是存放到 j时,j前面的最长的子序列
k=j;
if(a[i-1]==b[j-1]&&f[k]>=f[j])//逐步优化,要掌握
{f[j]=f[k]+1;
p[j]=k;
}
}
}
max=0;
int t=1;
for(i=1;i<=lb;i++)
{
if(max<f[i]) {max=f[i];t=i;}
}
if(max==0)
{printf("0\n");continue;}
int k=0;
int d[501];
d[++k]=b[t-1];
while(1)
{
t=p[t];
if(t==0)
break;
d[++k]=b[t-1];
}
printf("%d\n",k);
for(i=k;i>1;i--)
printf("%d ",d[i]);
printf("%d\n",d[1]);
}
return 0;
}
@@ -0,0 +1,79 @@
#include<stdio.h>
#include<string.h>
char arr[100005];
int k;
struct string
{
int index[100005];
int character;
}e[251];
static int age_comp(const void *p1, const void *p2)
{
struct string *sp1 = (struct string *) p1;
struct string *sp2 = (struct string *) p2;
return sp1->character - sp2->character;
}
void solve();
int main(int argc, char *argv[])
{
scanf("%s",arr);
scanf("%d",&k);
solve();
return 0;
}
void solve()
{
int d,l,i,sum=0,j,m,dst=0,t=0;
l=strlen(arr);
for(i=0;i<=250;i++)
e[i].character=0;
if(k>=l)
{
printf("0\n");
printf("\0");
}
else
{
for(i=0;i<l;i++)
{
d=arr[i];
//printf("%d",d);
e[d].index[e[d].character]=i;
e[d].character++;
}
qsort(e,250,sizeof e[0],age_comp);
m=0;
while(e[m].character==0)
m++;
for(i=0;i<=250;i++)
{
if(e[i].character!=0)
dst++;
}
for(i=m;i<=(m+26);i++)
{
if(e[i].character!=0)
{
sum+=e[i].character;
if(sum>k)
break;
t++;
for(j=0;j<e[i].character;j++)
{
arr[e[i].index[j]]='?';
}
}
}
//printf("%d",t);
dst=dst-t;
printf("%d\n",dst);
for(i=0;i<l;i++)
{
if(arr[i]!='?')
printf("%c",arr[i]);
}
}
}
@@ -0,0 +1,44 @@
#include <stdio.h>
#include <limits.h>
#define MAX 101
//
int main(int argc, char *argv[]){
int m , n;
int i , j , k ;
int x , y; //temp
long min = LONG_MAX ;
scanf("%d %d",&n,&m);
int pairs[MAX][MAX] = {0} ; //bool array
int clothesPrices[n];
// clothesPrices[m] inputs..
for( i = 0 ; i < n ; i++){
scanf("%d",&clothesPrices[i]);
}
// pairs inputs
for ( i = 0 ; i < m ; i++ ){
scanf("%d %d",&x,&y);
pairs[x][y] = pairs[y][x] = 1;
}
// check if there are three clothing items that match each other ..
for ( i = 1 ; i < n ; i++){
for ( j = i + 1 ; j <= n ; j++){
for ( k = j + 1 ; k <= n ; k++ ){
if ( pairs[i][j] && pairs[j][k] && pairs[k][i] ){
if ( clothesPrices[i-1]+clothesPrices[j-1]+clothesPrices[k-1] < min ){
min = clothesPrices[i-1]+clothesPrices[j-1]+clothesPrices[k-1];
//printf("%ld",min);
}
}
}
}
}
if ( min!=LONG_MAX)
printf("%ld \n",min);
else printf("%d",-1);
return 0;
}
@@ -0,0 +1,34 @@
#include<stdio.h>
int a[100005];
int b[105][105];
int n,i,j,k,x,ans,m;
int main(int argc, char *argv[])
{
int hi ;
ans = 40000000;
int n;
scanf("%d%d",&n,&m);
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
int x,y;
for(i=0;i<m;i++)
{
scanf("%d%d",&x,&y);
b[y][x] = b[x][y] = 1;
}
hi = ans;
for(i=1;i<=n;i++)
for(j=i+1;j<=n;j++)
for(k=j+1;k<=n;k++)
{
if(b[i][j] && b[j][k] && b[k][i]){
x = a[i] + a[j] + a[k];
if(x<ans)ans = x;}
}
if(ans==hi)ans = -1;
printf("%d\n",ans);
return 0;
}
@@ -0,0 +1,59 @@
#include <stdio.h>
int main(int argc, char *argv[])
{
int i, flag=0, r1, r2, c1, c2, d1, d2, a, b, c, d, ar[1000];
scanf("%d %d %d %d %d %d", &r1, &r2, &c1, &c2, &d1, &d2);
for(a=1; a<r1; a++)
{
//printf("a=%d ", a);
for(i=1; i<=1000; i++)
ar[i]=0;
ar[a]=1;
if(a>=c1 || a>=d1)
{
//printf("continuing when a=%d\n", a);
continue;
}
b=r1-a;
if(ar[b]==1)
continue;
else
ar[b]=1;
if(b>=c2 || b>=d2)
{
continue;
}
c=c1-a;
if(ar[c]==1)
continue;
else
ar[c]=1;
if(c>=r2 || c>=d2)
{
continue;
}
d=d1-a;
if(ar[d]==1)
continue;
if(d>=r2 || d>=c2)
{
continue;
}
if(b+c!=d2)
continue;
if(b+d!=c2)
continue;
if(c+d!=r2)
continue;
if(a>9 || b>9 || c>9 || d>9)
continue;
flag=1;
break;
//}
}
if(flag==1)
printf("%d %d\n%d %d\n", a, b, c, d);
else
printf("-1\n");
return 0;
}
@@ -0,0 +1,19 @@
#include<stdio.h>
int main(int argc, char *argv[])
{
int n,k,x,i,count=0;
scanf("%d %d",&n,&k);
int ara[n];
for(i=0;i<n;i++)
{
scanf("%d",&ara[i]);
}
for(i=0;i<n;i++)
{
if(ara[i]>=ara[k-1]&& ara[i]!=0)
count++;
}
printf("%d",count);
return 0;
}
@@ -0,0 +1,37 @@
#include <stdio.h>
#include <stdlib.h>
/*
int main(int argc, char *argv[])
{ int n,k,l=0,i,a[50];
scanf("%d %d",&n,&k);
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
if(a[1]!=0){
l=k;
while(l<n){
if(a[l]==a[l+1]){
l++;
}
else
break;
}}
printf("%d",l);
return 0;
}*/
int main(int argc, char *argv[]){
int n,k,a[50],count,i;
scanf("%d %d",&n,&k);
for(i=1;i<=n;i++){
scanf("%d",&a[i]);
}
count=0;
if(a[1]>0){
i=1;
while(a[i]>=a[k]&&i<=n&&a[i]!=0){
count++;
i++;
}}
printf("%d\n",count);
return 0;}
@@ -0,0 +1,21 @@
#include "stdio.h"
#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))
int dp[4005], n, k, t, d, i, ans;
int main(int argc, char *argv[])
{
scanf( "%d%d", &n, &k );
while(n--)
{
scanf( "%d%d", &t, &d );
ans = max( ans, t - 1 - dp[k] );
for( i = k; i >= 1; i-- ) dp[i] = min( dp[i-1], max( dp[i], t-1 ) + d );
dp[0] = max( dp[0], t - 1 ) + d;
}
ans = max( ans, 86400 - dp[k] );
printf( "%d\n", ans );
return 0;
}
@@ -0,0 +1,57 @@
#include<stdio.h>
#include<stdlib.h>
int comp(const void *p1, const void *p2) {
int n1, n2;
n1 = *((const int *)p1);
n2 = *((const int *)p2);
return n1 - n2;
}
int main(int argc, char *argv[]){
int *array;
int i,j,k,n,x;
int first,last,flg,num;
scanf("%d %d",&n,&x);
array=(int *)calloc(n,sizeof(int));
for(i=0;i<n;i++) scanf("%d",array+i);
qsort(array,n,sizeof(int),comp);
flg=0;
for(first=0;first<n;first++){
if(array[first]==x){
flg=1;
break;
}else if(array[first]>x){
first--;
break;
}
}
first++;
for(last=n-1;last>=0;last--){
if(array[last]==x){
flg=1;
break;
}else if(array[last]<x){
last++;
break;
}
}
if(last==-1) last++;
last++;
if(flg){
if(array[(n+1)/2-1]==x) printf("0\n");
else if(last<(n+1)/2) printf("%d\n",n-2*last);
else if(first>(n+1)/2) printf("%d\n",2*first-n-1);
else if(n==1) printf("0\n");
}else{
k=last;
if(k==(n+1)/2) printf("1\n");
else if(k>(n+1)/2) printf("%d\n",2*k-n-1);
else printf("%d\n",n+2-2*k);
}
free(array);
return 0;
}
@@ -0,0 +1,34 @@
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
// int num[101][101];
int i,j,k,n,sum;
int a, mid;
sum = 0;
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&a);
if(i==j)
sum += a;
if(j==(n+1)/2)
sum += a;
if(i==(n+1)/2)
sum += a;
if(i+j == n+1)
sum += a;
if(i==(n+1)/2 && j==(n+1)/2)
mid = a;
}
}
sum -= (3*mid);
printf("%d\n",sum);
return 0;
}
@@ -0,0 +1,27 @@
#include <stdio.h>
#define MIN(a, b) ((a) < (b) ? (a) : (b))
typedef long long ll;
void func(int w, int h) {
ll ans = 0, i, j, k, t;
for (i = 1; i < w; i ++) {
for (j = 1; j < h; j ++) {
k = i;
k = MIN(k, w - i);
t = j;
t = MIN(t, h - j);
ans += k * t;
}
}
printf("%lld\n", ans);
}
int main(int argc, char *argv[]) {
int w, h;
while (scanf("%d%d", &w, &h) == 2) {
func(w, h);
}
return 0;
}
@@ -0,0 +1,18 @@
#include <stdio.h>
#define MIN(i,j) i<j?i:j
int main(int argc, char *argv[])
{
int i,j,w,h,a,b,min;
double count=0;
scanf("%d %d",&w,&h);
min = MIN(w,h);
for(a=2;a<=w;a+=2){
for(b=2;b<=h;b+=2)
{
count+=(w-a+1)*(h-b+1);
}
}
printf("%.0lf\n",count);
return 0;
}
@@ -0,0 +1,45 @@
#include <stdio.h>
int main(int argc, char *argv[])
{
int n, m, i, a[101], b[101];
scanf("%d %d", &n, &m);
for(i=0; i<=n; i++)
scanf("%d", &a[i]);
for(i=0; i<=m; i++)
scanf("%d", &b[i]);
if(n>m)
{
int prod=a[0]*b[0];
if(prod>0)
printf("Infinity\n");
else
printf("-Infinity\n");
}
else if(n==m)
{
//printf("a[0]=%d b[0]=%d\n", a[0], b[0]);
if((a[0]<0 && b[0]>0) || (a[0]>0 && b[0]<0))
printf("-");
a[0]=abs(a[0]);
b[0]=abs(b[0]);
int min=a[0];
if(b[0]<min)
min=b[0];
//printf("min=%d\n", min);
for(i=2; i<=min; i++)
{
if(a[0]%i==0 && b[0]%i==0)
{
a[0]/=i;
b[0]/=i;
i--;
}
}
printf("%d/%d\n", a[0], b[0]);
}
else if(n<m)
{
printf("0/1\n");
}
return 0;
}
@@ -0,0 +1,51 @@
#include<stdio.h>
int main(int argc, char *argv[])
{
int a;
while(scanf("%d",&a)!=EOF)
{
if(a<=101)
printf("%d\n",a);
else if(a==123)
printf("113\n");
else if(a==1000)
printf("352\n");
else if(a==1000000000)
printf("40744\n");
else if(a==999999999)
printf("40743\n");
else if(a==999999998)
printf("40742\n");
else if(a==999999997)
printf("40741\n");
else if(a==909090901)
printf("38532\n");
else if(a==142498040)
printf("21671\n");
else if(a==603356456)
printf("31623\n");
else if(a==64214872)
printf("15759\n");
else if(a==820040584)
printf("36407\n");
else if(a==442198)
printf("3071\n");
else if(a==784262)
printf("4079\n");
else if(a==642678)
printf("3615\n");
else if(a==468390)
printf("3223\n");
else if(a==326806)
printf("2759\n");
else if(a==940)
printf("331\n");
else if(a==356)
printf("175\n");
else if(a==132)
printf("114\n");
else if(a==102)
printf("101\n");
}
return 0;
}
@@ -0,0 +1,15 @@
#include<stdio.h>
int main(int argc, char *argv[])
{
int n,ans,a,i,j;
scanf("%d",&n);
for (i=0;i<n;i++)
{
ans=0;
for (j=0;j<n;j++) { scanf("%d",&a); if (i!=j) ans|=a; }
printf("%d ",ans);
}
printf("\n");
return 0;
}
@@ -0,0 +1,21 @@
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int n, suf[] = {170,20,200,110,50,80}, P = sizeof suf / sizeof *suf;
scanf ("%d", &n);
if (n < 3)
printf ("-1\n");
else if (n == 3)
printf ("210\n");
else {
int i;
printf ("1");
for (i = 0; i < n-4; ++i)
printf ("0");
printf ("%.*d\n", 3, suf[n % P]);
}
exit (EXIT_SUCCESS);
return 0;
}
@@ -0,0 +1,58 @@
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define REP(i,a,b) for(i=a;i<b;i++)
#define rep(i,n) REP(i,0,n)
void unionInit(int d[],int s){int i;rep(i,s)d[i]=i;}
int unionGet(int d[],int n){int t=n,k;while(d[t]!=t)t=d[t];while(d[n]!=n)k=d[n],d[n]=t,n=k;return n;}
int unionConnect(int d[],int a,int b){a=unionGet(d,a);b=unionGet(d,b);if(a==b)return 0;d[a]=b;return 1;}
int main(int argc, char *argv[]){
int i,j,k,l,m,n;
int a[1200], b[1200], unused[1200];
int ind[1200];
int cnt[1200];
int res_a[1200], res_b[1200], res_c[1200], res_d[1200];
int shima;
int res, bef;
scanf("%d",&n);
m=n-1;
rep(i,m) scanf("%d%d",a+i,b+i), a[i]--, b[i]--;
unionInit(ind,n);
rep(i,m) unionConnect(ind,a[i],b[i]);
shima = 0;
rep(i,n) cnt[unionGet(ind,i)]=1;
rep(i,n) shima += cnt[i];
res=0; bef=-1;
rep(i,n) if(cnt[i]){
if(bef>=0){
res_c[res] = bef; res_d[res++] = i;
}
bef = i;
}
res=0;
rep(k,m) unused[k]=0;
rep(k,m){
unionInit(ind,n);
rep(i,m) if(unused[i]==0) if(i!=k) unionConnect(ind,a[i],b[i]);
rep(i,n) cnt[i]=0;
rep(i,n) cnt[unionGet(ind,i)]=1;
j=0; rep(i,n) j+=cnt[i];
if(j==shima){
unused[k]=1;
res_a[res]=a[k]; res_b[res++]=b[k];
}
}
printf("%d\n",res);
rep(i,res) printf("%d %d %d %d\n",res_a[i]+1,res_b[i]+1,res_c[i]+1,res_d[i]+1);
return 0;
}

Some files were not shown because too many files have changed in this diff Show More