File size: 178,379 Bytes
d30c238
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{"class_name": "Actor_relationship_game", "id": "./MultiFileTest/Java/Actor_relationship_game.java", "original_code": "// ./Actor_relationship_game/Actor.java\npackage projecteval.Actor_relationship_game;\n\nimport java.io.Serializable;\nimport java.util.HashSet;\nimport java.util.Set;\n\npublic class Actor implements Serializable{\n    private static final long serialVersionUID=1L;\n    private String id;\n    private String name;\n    private Set<String> movieIds; // Store movie IDs\n\n    public Actor(String id, String name) {\n        this.id = id;\n        this.name = name;\n        this.movieIds = new HashSet<>();\n    }\n\n    // Getters and setters\n    public Set<String> getMovieIds() {\n        return movieIds;\n    }\n    public String getId() {\n        return id;\n    }\n    public String getName() {\n        return name;\n    }\n    public void setId(String id) {\n        this.id = id;\n    }\n    public void setMovieIds(Set<String> movieIds) {\n        this.movieIds = movieIds;\n    }\n    public void setName(String name) {\n        this.name = name;\n    }\n}\n\n\n// ./Actor_relationship_game/ActorGraph.java\npackage projecteval.Actor_relationship_game;\n\nimport java.io.Serializable;\nimport java.util.*;\n\npublic class ActorGraph implements Serializable {\n    private static final long serialVersionUID=1L;\n    private Map<String, Actor> actors;\n    private Map<String, Movie> movies;\n    private Map<String, String> nameToIdMap;\n    private Map<String, String> idToNameMap;\n\n    public ActorGraph() {\n        this.actors = new HashMap<>();\n        this.movies = new HashMap<>();\n        this.nameToIdMap = new HashMap<>();\n        this.idToNameMap = new HashMap<>();\n    }\n\n    // getters\n    public Map<String, Actor> getActors() {\n        return actors;\n    }\n    public Map<String, Movie> getMovies() {\n        return movies;\n    }\n    public Map<String, String> getIdToNameMap() {\n        return idToNameMap;\n    }\n    public Map<String, String> getNameToIdMap() {\n        return nameToIdMap;\n    }\n    public static long getSerialVersionUID() {\n        return serialVersionUID;\n    }\n\n    // Methods\n    public void addActor(Actor actor) {\n        actors.putIfAbsent(actor.getId(), actor);\n        nameToIdMap.put(actor.getName(), actor.getId());\n        idToNameMap.put(actor.getId(), actor.getName());\n    }\n\n    public void addMovie(Movie movie) {\n        movies.putIfAbsent(movie.getId(), movie);\n    }\n\n    public String getActorIdByName(String name) {\n        return nameToIdMap.get(name);\n    }\n\n    public String getActorNameById(String id) {\n        return idToNameMap.get(id);\n    }\n\n    public List<String> getAllActorNames() {\n        return new ArrayList<>(nameToIdMap.keySet());\n    }\n\n    /**\n     * This connects an actor to a movie.\n     * It's useful for building the graph based on TMDB API data.\n     */\n    public void addActorToMovie(String actorId, String movieId) {\n        if (actors.containsKey(actorId) && movies.containsKey(movieId)) {\n            Actor actor = actors.get(actorId);\n            Movie movie = movies.get(movieId);\n            actor.getMovieIds().add(movieId);\n            movie.getActorIds().add(actorId);\n        }\n    }\n\n    /**\n     * Implements BFS to find the shortest path from startActorId to endActorId.\n     * It uses a queue for BFS and a map (visited) to track the visited actors and their previous actor in the path.\n     */\n    public List<Map.Entry<String, String>> findConnectionWithPath(String startActorId, String endActorId) {\n        if (!actors.containsKey(startActorId) || !actors.containsKey(endActorId)) {\n            return Collections.emptyList();\n        }\n\n        Queue<String> queue = new LinkedList<>();\n        Map<String, String> visited = new HashMap<>();\n        Map<String, String> previousMovie = new HashMap<>();\n        queue.add(startActorId);\n        visited.put(startActorId, null);\n\n        while (!queue.isEmpty()) {\n            String currentActorId = queue.poll();\n            Actor currentActor = actors.get(currentActorId);\n\n            for (String movieId : currentActor.getMovieIds()) {\n                Movie movie = movies.get(movieId);\n                for (String coActorId : movie.getActorIds()) {\n                    if (!visited.containsKey(coActorId)) {\n                        visited.put(coActorId, currentActorId);\n                        previousMovie.put(coActorId, movieId);\n                        queue.add(coActorId);\n\n                        if (coActorId.equals(endActorId)) {\n                            return buildPath(visited, previousMovie, endActorId);\n                        }\n                    }\n                }\n            }\n        }\n\n        return Collections.emptyList();\n    }\n\n    /**\n     * Helper method to construct the path from the endActorId back to the startActorId using the visited map.\n     */\n    private List<Map.Entry<String, String>> buildPath(Map<String, String> visited, Map<String, String> previousMovie, String endActorId) {\n        LinkedList<Map.Entry<String, String>> path = new LinkedList<>();\n        String current = endActorId;\n        while (current != null) {\n            String movieId = previousMovie.get(current);\n            String movieName = (movieId != null) ? movies.get(movieId).getTitle() : \"Start\";\n            path.addFirst(new AbstractMap.SimpleEntry<>(idToNameMap.get(current), movieName));\n            current = visited.get(current);\n        }\n        return path;\n    }\n}\n\n\n\n// ./Actor_relationship_game/ActorGraphUtil.java\npackage projecteval.Actor_relationship_game;\n\nimport java.io.*;\nimport java.util.List;\n\npublic class ActorGraphUtil {\n\n    public static void main(String[] args) {\n        String graphPath = args[0];\n        String filePath = args[1];\n        ActorGraph actorGraph = loadGraph(graphPath);\n        if (actorGraph != null) {\n            List<String> actorNames = actorGraph.getAllActorNames();\n            writeActorsToFile(actorNames, filePath);\n            System.out.println(\"Actors list has been saved to \" + filePath);\n        } else {\n            System.out.println(\"Failed to load the graph.\");\n        }\n    }\n\n    protected static ActorGraph loadGraph(String graphPath) {\n        try (FileInputStream fileIn = new FileInputStream(graphPath);\n             ObjectInputStream in = new ObjectInputStream(fileIn)) {\n            return (ActorGraph) in.readObject();\n        } catch (Exception e) {\n            e.printStackTrace();\n            return null;\n        }\n    }\n\n    protected static void writeActorsToFile(List<String> actorNames, String fileName) {\n        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {\n            for (String name : actorNames) {\n                writer.write(name);\n                writer.newLine();\n            }\n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n    }\n}\n\n\n\n// ./Actor_relationship_game/GameplayInterface.java\npackage projecteval.Actor_relationship_game;\n\nimport java.io.*;\nimport java.util.*;\nimport java.util.List;\n\npublic class GameplayInterface {\n    private ActorGraph actorGraph;\n\n    public void setActorGraph(ActorGraph actorGraph) {\n        this.actorGraph = actorGraph;\n    }\n    \n\n    public void loadGraph(String fileName) {\n        try (FileInputStream fileIn = new FileInputStream(fileName);\n             ObjectInputStream in = new ObjectInputStream(fileIn)) {\n            actorGraph = (ActorGraph) in.readObject();\n            System.out.println(\"Graph successfully loaded.\");\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    public void findConnections(List<String[]> actorPairs, String outputFilePath) {\n        try (PrintWriter writer = new PrintWriter(new FileWriter(outputFilePath))) {\n            for (String[] pair : actorPairs) {\n                if (pair.length != 2) {\n                    System.out.println(\"Invalid actor pair. Skipping.\");\n                    continue;\n                }\n\n                String actor1Name = pair[0];\n                String actor2Name = pair[1];\n\n                // Assuming getActorIdByName is a method in ActorGraph that returns the actor's ID given a name\n                String actor1Id = actorGraph.getActorIdByName(actor1Name);\n                String actor2Id = actorGraph.getActorIdByName(actor2Name);\n\n                if (actor1Id == null || actor2Id == null) {\n                    writer.println(\"One or both actors not found in the graph.\");\n                    continue;\n                }\n\n                List<Map.Entry<String, String>> connectionPath = actorGraph.findConnectionWithPath(actor1Id, actor2Id);\n\n                if (connectionPath.isEmpty()) {\n                    writer.println(\"===================================================\");\n                    writer.println(\"No connection found between \" + actor1Name + \" and \" + actor2Name + \".\");\n                    writer.println(\"===================================================\");\n                    writer.println();\n                } else {\n                    writer.println(\"===================================================\");\n                    writer.println(\"Connection Number between \" + actor1Name + \" and \" + actor2Name + \":\" + (connectionPath.size() - 1));\n                    writer.println(\"Connection path between \" + actor1Name + \" and \" + actor2Name + \":\");\n                    for (int i = 0; i < connectionPath.size(); i++) {\n                        Map.Entry<String, String> step = connectionPath.get(i);\n                        writer.println((i + 1) + \". \" + step.getKey() + \": \" + step.getValue());\n                    }\n                    writer.println(\"===================================================\");\n                    writer.println();\n                }\n            }\n        } catch (IOException e){\n            e.printStackTrace();\n        }\n    }\n\n\n    private static List<String> readActorsFromFile(String fileName) {\n        List<String> actors = new ArrayList<>();\n        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {\n            String line;\n            while ((line = reader.readLine()) != null) {\n                actors.add(line.trim());\n            }\n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n        return actors;\n    }\n\n    private static List<String[]> generateAllActorPairs(String fileName) {\n        List<String> actors = readActorsFromFile(fileName);\n        List<String[]> pairs = new ArrayList<>();\n\n        for (int i = 0; i < actors.size(); i++) {\n            for (int j = i + 1; j < actors.size(); j++) {\n                pairs.add(new String[]{actors.get(i), actors.get(j)});\n            }\n        }\n\n        return pairs;\n    }\n\n    public static void main(String[] args) {\n        String graphPath = args[0];\n        String actorPath = args[1];\n        String filePath = args[2];\n\n        GameplayInterface gameplay = new GameplayInterface();\n        gameplay.loadGraph(graphPath);\n\n        List<String[]> actorPairs = generateAllActorPairs(actorPath);\n        gameplay.findConnections(actorPairs,filePath);\n    }\n}\n\n\n\n// ./Actor_relationship_game/GraphCreation.java\npackage projecteval.Actor_relationship_game;\n\nimport com.google.gson.JsonArray;\nimport com.google.gson.JsonElement;\nimport com.google.gson.JsonObject;\nimport com.google.gson.JsonParser;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.ObjectOutputStream;\n\npublic class GraphCreation {\n    private final TMDBApi tmdbApi;\n    private final ActorGraph actorGraph;\n\n    public GraphCreation() {\n        this.tmdbApi = new TMDBApi();\n        this.actorGraph = new ActorGraph();\n    }\n\n    public void createGraph(String fileName) throws IOException {\n        populateGraphWithActors();\n        saveGraphToFile(fileName);\n    }\n\n    private void populateGraphWithActors() throws IOException {\n        String popularActorsJson = tmdbApi.searchPopularActors();\n        JsonArray actorsArray = JsonParser.parseString(popularActorsJson)\n                .getAsJsonObject().getAsJsonArray(\"results\");\n\n        for (JsonElement actorElement : actorsArray) {\n            processActorElement(actorElement);\n        }\n    }\n\n    private void processActorElement(JsonElement actorElement) throws IOException {\n        JsonObject actorObject = actorElement.getAsJsonObject();\n        String actorId = actorObject.get(\"id\").getAsString();\n        String actorName = actorObject.get(\"name\").getAsString();\n\n        Actor actor = new Actor(actorId, actorName);\n        actorGraph.addActor(actor);\n        populateGraphWithMoviesForActor(actorId);\n    }\n\n    private void populateGraphWithMoviesForActor(String actorId) throws IOException {\n        String moviesJson = tmdbApi.getMoviesByActorId(actorId);\n        JsonArray moviesArray = JsonParser.parseString(moviesJson)\n                .getAsJsonObject().getAsJsonArray(\"cast\");\n\n        for (JsonElement movieElement : moviesArray) {\n            processMovieElement(movieElement, actorId);\n        }\n    }\n\n    private void processMovieElement(JsonElement movieElement, String actorId) {\n        JsonObject movieObject = movieElement.getAsJsonObject();\n        String movieId = movieObject.get(\"id\").getAsString();\n        String movieTitle = movieObject.get(\"title\").getAsString();\n\n        Movie movie = new Movie(movieId, movieTitle);\n        actorGraph.addMovie(movie);\n        actorGraph.addActorToMovie(actorId, movieId);\n    }\n\n    private void saveGraphToFile(String fileName) throws IOException {\n        try (FileOutputStream fileOut = new FileOutputStream(fileName);\n             ObjectOutputStream out = new ObjectOutputStream(fileOut)) {\n            out.writeObject(actorGraph);\n            System.out.println(\"Serialized data is saved in \"+fileName);\n        }\n    }\n\n    public static void main(String[] args) {\n        try {\n            String fileName = args[0];\n            new GraphCreation().createGraph(fileName);\n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n    }\n}\n\n\n\n// ./Actor_relationship_game/Movie.java\npackage projecteval.Actor_relationship_game;\n\nimport java.io.Serializable;\nimport java.util.HashSet;\nimport java.util.Set;\n\npublic class Movie implements Serializable {\n    private static final long serialVersionUID=1L;\n\n    private String id;\n    private String title;\n    private Set<String> actorIds; // Store actor IDs\n\n    public Movie(String id, String title) {\n        this.id = id;\n        this.title = title;\n        this.actorIds = new HashSet<>();\n    }\n\n    // Getters and setters\n    public String getId() {\n        return id;\n    }\n    public Set<String> getActorIds() {\n        return actorIds;\n    }\n    public String getTitle() {\n        return title;\n    }\n    public void setId(String id) {\n        this.id = id;\n    }\n    public void setActorIds(Set<String> actorIds) {\n        this.actorIds = actorIds;\n    }\n    public void setTitle(String title) {\n        this.title = title;\n    }\n\n}\n\n\n\n// ./Actor_relationship_game/TMDBApi.java\npackage projecteval.Actor_relationship_game;\n\nimport okhttp3.OkHttpClient;\nimport okhttp3.Request;\nimport okhttp3.Response;\nimport java.io.IOException;\n\npublic class TMDBApi {\n    private final OkHttpClient client;\n    private final String apiKey = System.getenv(\"TMDB_API_KEY\"); // get API Key from environmental variable\n\n    public TMDBApi() {\n        this.client = new OkHttpClient();\n    }\n\n    public String getMoviesByActorId(String actorId) throws IOException {\n        String url = \"https://api.themoviedb.org/3/person/\" + actorId + \"/movie_credits?api_key=\" + apiKey;\n        Request request = new Request.Builder().url(url).build();\n\n        try (Response response = client.newCall(request).execute()) {\n            if (!response.isSuccessful()) {\n                throw new IOException(\"Unexpected code \" + response);\n            }\n            return response.body().string();\n        }\n    }\n\n\n    public String searchPopularActors() throws IOException {\n        String url = \"https://api.themoviedb.org/3/person/popular?api_key=\" + apiKey;\n        Request request = new Request.Builder().url(url).build();\n\n        try (Response response = client.newCall(request).execute()) {\n            if (!response.isSuccessful()) {\n                throw new IOException(\"Unexpected code \" + response);\n            }\n            return response.body().string();\n        }\n    }\n\n\n}\n", "num_file": 7, "num_lines": 479, "programming_language": "Java"}
{"class_name": "CalculatorOOPS", "id": "./MultiFileTest/Java/CalculatorOOPS.java", "original_code": "// ./CalculatorOOPS/Add.java\npackage projecteval.CalculatorOOPS;\n\npublic class Add implements Operate{\n    @Override\n    public Double getResult(Double... numbers){\n        Double sum = 0.0;\n\n        for(Double num: numbers){\n            sum += num;\n        }\n        return sum;\n    }\n}\n\n\n// ./CalculatorOOPS/Calculator.java\npackage projecteval.CalculatorOOPS;\n\nimport java.util.Arrays;\nimport java.util.LinkedList;\nimport java.util.Objects;\nimport java.util.Queue;\n\npublic class Calculator {\n    public static void main(String[] args){\n        final String inputExp = ReadInput.read();\n\n        Queue<String> operations;\n        Queue<String> numbers;\n\n        String[] numbersArr = inputExp.split(\"[-+*/%]\");\n//        String[] operArr = inputExp.split(\"[0-9]+\");\n        String[] operArr = inputExp.split(\"\\\\d+\");\n        numbers = new LinkedList<>(Arrays.asList(numbersArr));\n        operations = new LinkedList<>(Arrays.asList(operArr));\n\n        Double res = Double.parseDouble(Objects.requireNonNull(numbers.poll()));\n\n        while(!numbers.isEmpty()){\n            String opr = operations.poll();\n\n            Operate operate;\n            switch(Objects.requireNonNull(opr)){\n                case \"+\":\n                    operate = new Add();\n                    break;\n                case \"-\":\n                    operate = new Sub();\n                    break;\n                case \"*\":\n                    operate = new Multiply();\n                    break;\n                case \"/\":\n                    operate = new Divide();\n                    break;\n                case \"%\":\n                    operate = new Modulus();\n                    break;\n                default:\n                    continue;\n            }\n            Double num = Double.parseDouble(Objects.requireNonNull(numbers.poll()));\n            res = operate.getResult(res, num);\n        }\n\n        System.out.println(res);\n    }\n}\n\n// ./CalculatorOOPS/Divide.java\npackage projecteval.CalculatorOOPS;\n\npublic class Divide implements Operate {\n    @Override\n    public Double getResult(Double... numbers){\n        Double div = numbers[0];\n\n        for(int i=1;i< numbers.length;i++){\n            div /= numbers[i];\n        }\n        return div;\n    }\n}\n\n\n// ./CalculatorOOPS/Modulus.java\npackage projecteval.CalculatorOOPS;\n\npublic class Modulus implements Operate{\n    @Override\n    public Double getResult(Double... numbers){\n        Double mod = numbers[0];\n\n        for (int i = 1; i < numbers.length; i++) {\n            mod %= numbers[i];\n        }\n        return mod;\n    }\n}\n\n\n// ./CalculatorOOPS/Multiply.java\npackage projecteval.CalculatorOOPS;\n\npublic class Multiply implements Operate {\n    @Override\n    public Double getResult(Double... numbers){\n        Double mul = 1.0;\n\n        for(Double num: numbers){\n            mul *= num;\n        }\n        return mul;\n    }\n\n}\n\n\n// ./CalculatorOOPS/Operate.java\npackage projecteval.CalculatorOOPS;\n\npublic interface Operate {\n    Double getResult(Double... numbers);\n}\n\n\n// ./CalculatorOOPS/ReadInput.java\npackage projecteval.CalculatorOOPS;\n\nimport java.util.Scanner;\n\npublic class ReadInput {\n    public static String read(){\n        Scanner scanner = new Scanner(System.in);\n        \n        System.out.println(\"Input Expression Example: 4*3/2\");\n        String inputLine = scanner.nextLine();\n        \n        scanner.close();\n        return inputLine;\n    }\n}\n\n// ./CalculatorOOPS/Sub.java\npackage projecteval.CalculatorOOPS;\n\npublic class Sub implements Operate{\n    @Override\n    public Double getResult(Double... numbers){\n        Double sub = numbers[0];\n\n        for(int i=1;i< numbers.length;i++){\n            sub -= numbers[i];\n        }\n        return sub;\n    }\n}\n", "num_file": 8, "num_lines": 138, "programming_language": "Java"}
{"class_name": "PongGame", "id": "./MultiFileTest/Java/PongGame.java", "original_code": "// ./PongGame/Ball.java\npackage projecteval.PongGame;\n\nimport java.awt.*;\nimport java.util.*;\n\n\npublic class Ball extends Rectangle{\n\n    Random random;\n    int xVelocity;\n    int yVelocity;\n    int initialSpeed = 4 ;\n\n    Ball(int x, int y, int width, int height){\n        super(x, y, width, height);\n        random = new Random();\n        int randomXDirection = random.nextInt(2);\n\n        if(randomXDirection==0)\n            randomXDirection--;\n        setXDirection(randomXDirection*initialSpeed);\n\n        int randomYDirection = random.nextInt(2);\n\n        if(randomYDirection==0)\n            randomYDirection--;\n        setXDirection(randomYDirection*initialSpeed);\n    }\n\n    public void setXDirection(int randomXDirection){\n        xVelocity = randomXDirection;\n\n    }\n    public void setYDirection(int randomYDirection){\n        yVelocity=randomYDirection;\n    }\n    public void move(){\n        x+=xVelocity;\n        y+=yVelocity;\n    }\n    public void draw(Graphics g){\n        g.setColor(Color.white);\n        g.fillOval(x, y, height, width);\n    }\n}\n\n\n// ./PongGame/GameFrame.java\npackage projecteval.PongGame;\n\nimport java.awt.*;\nimport javax.swing.*;\n\n\npublic class GameFrame extends JFrame{\n\n    GamePanel panel;\n    GameFrame(){\n        panel = new GamePanel();\n        this.add(panel);\n        this.setTitle(\"Pong Game\");\n        this.setResizable(false);\n        this.setBackground(Color.black);\n        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        this.pack();\n        this.setVisible(true);\n        this.setLocationRelativeTo(null);\n\n    }\n}\n\n\n// ./PongGame/GamePanel.java\npackage projecteval.PongGame;\n\nimport java.awt.*;\nimport java.awt.event.*;\nimport java.util.*;\nimport javax.swing.*;\n\npublic class GamePanel extends JPanel implements Runnable{\n\n\tstatic final int GAME_WIDTH = 1000;\n\tstatic final int GAME_HEIGHT = (int)(GAME_WIDTH * (0.5555));\n\tstatic final Dimension SCREEN_SIZE = new Dimension(GAME_WIDTH,GAME_HEIGHT);\n\tstatic final int BALL_DIAMETER = 20;\n\tstatic final int PADDLE_WIDTH = 25;\n\tstatic final int PADDLE_HEIGHT = 100;\n\tThread gameThread;\n\tImage image;\n\tGraphics graphics;\n\tRandom random;\n\tPaddle paddle1;\n\tPaddle paddle2;\n\tBall ball;\n\tScore score;\n\t\n\tGamePanel(){\n\t\tnewPaddles();\n\t\tnewBall();\n\t\tscore = new Score(GAME_WIDTH,GAME_HEIGHT);\n\t\tthis.setFocusable(true);\n\t\tthis.addKeyListener(new AL());\n\t\tthis.setPreferredSize(SCREEN_SIZE);\n\t\t\n\t\tgameThread = new Thread(this);\n\t\tgameThread.start();\n\t}\n\t\n\tpublic void newBall() {\n\t\trandom = new Random();\n\t\tball = new Ball((GAME_WIDTH/2)-(BALL_DIAMETER/2),random.nextInt(GAME_HEIGHT-BALL_DIAMETER),BALL_DIAMETER,BALL_DIAMETER);\n\t}\n\tpublic void newPaddles() {\n\t\tpaddle1 = new Paddle(0,(GAME_HEIGHT/2)-(PADDLE_HEIGHT/2),PADDLE_WIDTH,PADDLE_HEIGHT,1);\n\t\tpaddle2 = new Paddle(GAME_WIDTH-PADDLE_WIDTH,(GAME_HEIGHT/2)-(PADDLE_HEIGHT/2),PADDLE_WIDTH,PADDLE_HEIGHT,2);\n\t}\n\tpublic void paint(Graphics g) {\n\t\timage = createImage(getWidth(),getHeight());\n\t\tgraphics = image.getGraphics();\n\t\tdraw(graphics);\n\t\tg.drawImage(image,0,0,this);\n\t}\n\tpublic void draw(Graphics g) {\n\t\tpaddle1.draw(g);\n\t\tpaddle2.draw(g);\n\t\tball.draw(g);\n\t\tscore.draw(g);\nToolkit.getDefaultToolkit().sync(); // I forgot to add this line of code in the video, it helps with the animation\n\n\t}\n\tpublic void move() {\n\t\tpaddle1.move();\n\t\tpaddle2.move();\n\t\tball.move();\n\t}\n\tpublic void checkCollision() {\n\t\t\n\t\t//bounce ball off top & bottom window edges\n\t\tif(ball.y <=0) {\n\t\t\tball.setYDirection(-ball.yVelocity);\n\t\t}\n\t\tif(ball.y >= GAME_HEIGHT-BALL_DIAMETER) {\n\t\t\tball.setYDirection(-ball.yVelocity);\n\t\t}\n\t\t//bounce ball off paddles\n\t\tif(ball.intersects(paddle1)) {\n\t\t\tball.xVelocity = Math.abs(ball.xVelocity);\n\t\t\tball.xVelocity++; //optional for more difficulty\n\t\t\tif(ball.yVelocity>0)\n\t\t\t\tball.yVelocity++; //optional for more difficulty\n\t\t\telse\n\t\t\t\tball.yVelocity--;\n\t\t\tball.setXDirection(ball.xVelocity);\n\t\t\tball.setYDirection(ball.yVelocity);\n\t\t}\n\t\tif(ball.intersects(paddle2)) {\n\t\t\tball.xVelocity = Math.abs(ball.xVelocity);\n\t\t\tball.xVelocity++; //optional for more difficulty\n\t\t\tif(ball.yVelocity>0)\n\t\t\t\tball.yVelocity++; //optional for more difficulty\n\t\t\telse\n\t\t\t\tball.yVelocity--;\n\t\t\tball.setXDirection(-ball.xVelocity);\n\t\t\tball.setYDirection(ball.yVelocity);\n\t\t}\n\t\t//stops paddles at window edges\n\t\tif(paddle1.y<=0)\n\t\t\tpaddle1.y=0;\n\t\tif(paddle1.y >= (GAME_HEIGHT-PADDLE_HEIGHT))\n\t\t\tpaddle1.y = GAME_HEIGHT-PADDLE_HEIGHT;\n\t\tif(paddle2.y<=0)\n\t\t\tpaddle2.y=0;\n\t\tif(paddle2.y >= (GAME_HEIGHT-PADDLE_HEIGHT))\n\t\t\tpaddle2.y = GAME_HEIGHT-PADDLE_HEIGHT;\n\t\t//give a player 1 point and creates new paddles & ball\n\t\tif(ball.x <=0) {\n\t\t\tscore.player2++;\n\t\t\tnewPaddles();\n\t\t\tnewBall();\n\t\t\tSystem.out.println(\"Player 2: \"+score.player2);\n\t\t}\n\t\tif(ball.x >= GAME_WIDTH-BALL_DIAMETER) {\n\t\t\tscore.player1++;\n\t\t\tnewPaddles();\n\t\t\tnewBall();\n\t\t\tSystem.out.println(\"Player 1: \"+score.player1);\n\t\t}\n\t}\n\tpublic void run() {\n\t\t//game loop\n\t\tlong lastTime = System.nanoTime();\n\t\tdouble amountOfTicks =60.0;\n\t\tdouble ns = 1000000000 / amountOfTicks;\n\t\tdouble delta = 0;\n\t\twhile(true) {\n\t\t\tlong now = System.nanoTime();\n\t\t\tdelta += (now -lastTime)/ns;\n\t\t\tlastTime = now;\n\t\t\tif(delta >=1) {\n\t\t\t\tmove();\n\t\t\t\tcheckCollision();\n\t\t\t\trepaint();\n\t\t\t\tdelta--;\n\t\t\t}\n\t\t}\n\t}\n\tpublic class AL extends KeyAdapter{\n\t\tpublic void keyPressed(KeyEvent e) {\n\t\t\tpaddle1.keyPressed(e);\n\t\t\tpaddle2.keyPressed(e);\n\t\t}\n\t\tpublic void keyReleased(KeyEvent e) {\n\t\t\tpaddle1.keyReleased(e);\n\t\t\tpaddle2.keyReleased(e);\n\t\t}\n\t}\n}\n\n\n// ./PongGame/Paddle.java\npackage projecteval.PongGame;\n\nimport java.awt.*;\nimport java.awt.event.*;\n\n\npublic class Paddle extends Rectangle{\n    int id;\n    int yVelocity;\n    int speed=10;\n    Paddle(int x, int y, int PADDLE_WIDTH, int PADDLE_HEIGHT, int id){\n        super(x,y,PADDLE_WIDTH,PADDLE_HEIGHT);\n        this.id=id;\n    }\n\n    public void keyPressed(KeyEvent e){\n        switch (id){\n            case 1:\n                if(e.getKeyCode()==KeyEvent.VK_W){\n                    setYDirection(-speed);\n                    move();\n                }\n                if(e.getKeyCode()==KeyEvent.VK_S){\n                    setYDirection(speed);\n                    move();\n                }\n                break;\n            case 2:\n                if(e.getKeyCode()==KeyEvent.VK_UP){\n                    setYDirection(-speed);\n                    move();\n                }\n                if(e.getKeyCode()==KeyEvent.VK_DOWN){\n                    setYDirection(speed);\n                    move();\n                }\n                break;\n        }\n    }\n    public void keyReleased(KeyEvent e){\n        switch (id){\n            case 1:\n                if(e.getKeyCode()==KeyEvent.VK_W){\n                    setYDirection(0);\n                    move();\n                }\n                if(e.getKeyCode()==KeyEvent.VK_S){\n                    setYDirection(0);\n                    move();\n                }\n                break;\n            case 2:\n                if(e.getKeyCode()==KeyEvent.VK_UP){\n                    setYDirection(0);\n                    move();\n                }\n                if(e.getKeyCode()==KeyEvent.VK_DOWN){\n                    setYDirection(0);\n                    move();\n                }\n                break;\n        }\n    }\n    public void setYDirection(int yDirection){\n        yVelocity = yDirection;\n    }\n    public void move(){\n        y=y+yVelocity;\n    }\n    public void draw(Graphics g){\n        if (id==1)\n            g.setColor(Color.BLUE);\n        else\n            g.setColor(Color.red);\n        g.fillRect(x, y, width, height);\n    }\n}\n\n\n// ./PongGame/PongGame.java\npackage projecteval.PongGame;\n\npublic class PongGame {\n\n\tpublic static void main(String[] args) {\n\t\t\n\t\tGameFrame frame = new GameFrame();\n\t\t\n\t}\n}\n\n\n// ./PongGame/Score.java\npackage projecteval.PongGame;\n\nimport java.awt.*;\n\npublic class Score extends Rectangle{\n    static int GAME_WIDTH;\n    static int GAME_HEIGHT;\n    int player1;\n    int player2;\n\n    Score(int GAME_WIDTH, int GAME_HEIGHT){\n        Score.GAME_WIDTH = GAME_WIDTH;\n        Score.GAME_HEIGHT=GAME_HEIGHT;\n    }\n    public void draw(Graphics g){\n        g.setColor(Color.white);\n        g.setFont(new Font(\"Consolas\", Font.PLAIN,60));\n        g.drawLine(GAME_WIDTH/2,0,GAME_WIDTH/2,GAME_HEIGHT);\n        g.drawString(String.valueOf(player1/10)+String.valueOf(player1%10), (GAME_WIDTH/2)-85, 50);\n        g.drawString(String.valueOf(player2/10)+String.valueOf(player2%10), (GAME_WIDTH/2)+20, 50);\n    }\n}\n", "num_file": 6, "num_lines": 321, "programming_language": "Java"}
{"class_name": "SimpleChat", "id": "./MultiFileTest/Java/SimpleChat.java", "original_code": "// ./SimpleChat/Client.java\npackage projecteval.SimpleChat;\n\nimport java.io.*;\nimport java.net.*;\nimport javax.swing.*;\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class Client {\n  JTextArea incoming;\n  JTextField outgoing;\n  BufferedReader reader;\n  PrintWriter writer;\n  Socket sock;\n\n  public static void main(String[] args) {\n    Client client = new Client();\n    client.go();\n  }\n\n  public void go() {\n    JFrame frame = new JFrame(\"Ludicrously Simple Chat Client\");\n    JPanel mainPanel = new JPanel();\n\n    incoming = new JTextArea(15, 50);\n\n    incoming.setLineWrap(true);\n    incoming.setWrapStyleWord(true);\n    incoming.setEditable(false);\n\n    JScrollPane qScroller = new JScrollPane(incoming);\n    qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);\n    qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);\n\n    outgoing = new JTextField(20);\n    JButton sendButton = new JButton(\"Send\");\n    sendButton.addActionListener(new SendButtonListener());\n\n    mainPanel.add(qScroller);\n    mainPanel.add(outgoing);\n    mainPanel.add(sendButton);\n    \n    setUpNetworking();\n\n    Thread readerThread = new Thread(new IncomingReader());\n    \n    readerThread.start();\n\n    frame.getContentPane().add(BorderLayout.CENTER, mainPanel);\n    frame.setSize(400, 500);\n    frame.setVisible(true);\n  }\n\n  private void setUpNetworking() {\n    try {\n      sock = new Socket(\"192.168.5.16\", 5000);\n      InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());\n      reader = new BufferedReader(streamReader);\n      writer = new PrintWriter(sock.getOutputStream());\n      System.out.println(\"networking established\");\n    } catch (IOException ex) {\n      ex.printStackTrace();\n    }\n  } // close setUpNetworking\n\n  public class SendButtonListener implements ActionListener {\n    public void actionPerformed(ActionEvent ev) {\n      try {\n        writer.println(outgoing.getText());\n        writer.flush();\n\n      } catch (Exception ex) {\n        ex.printStackTrace();\n      }\n      outgoing.setText(\"\");\n      outgoing.requestFocus();\n    }\n  } // close inner class\n\n  public class IncomingReader implements Runnable {\n    public void run() {\n      String message;\n      try {\n        while ((message = reader.readLine()) != null) {\n          System.out.println(\"read \" + message);\n          incoming.append(message + \"\\n\");\n\n        } // close while\n      } catch (Exception ex) {\n        ex.printStackTrace();\n      }\n    } // close run\n  }\n}\n\n// ./SimpleChat/Server.java\npackage projecteval.SimpleChat;\n\nimport java.io.*;\nimport java.net.*;\nimport java.util.*;\n\nclass VerySimpleChatServer {\n  ArrayList clientOutputStreams;\n\n  public class ClientHandler implements Runnable {\n    BufferedReader reader;\n    Socket sock;\n\n    public ClientHandler(Socket clientSocket) {\n      try {\n        sock = clientSocket;\n        InputStreamReader isReader = new InputStreamReader(sock.getInputStream());\n        reader = new BufferedReader(isReader);\n\n      } catch (Exception ex) {\n        ex.printStackTrace();\n      }\n    } // close constructor\n\n    public void run() {\n      String message;\n      try {\n        while ((message = reader.readLine()) != null) {\n          System.out.println(\"read \" + message);\n          tellEveryone(message);\n\n        } // close while\n      } catch (Exception ex) {\n        ex.printStackTrace();\n      }\n    } // close run\n  }\n\n  // close inner class\n  public static void main(String[] args) {\n    new VerySimpleChatServer().go();\n  }\n\n  public void go() {\n    clientOutputStreams = new ArrayList();\n    try {\n      ServerSocket serverSock = new ServerSocket(5000);\n      while (true) {\n        Socket clientSocket = serverSock.accept();\n        PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());\n        clientOutputStreams.add(writer);\n        Thread t = new Thread(new ClientHandler(clientSocket));\n        t.start();\n        System.out.println(\"got a connection\");\n      }\n\n    } catch (Exception ex) {\n      ex.printStackTrace();\n    }\n  } // close go\n\n  public void tellEveryone(String message) {\n    Iterator it = clientOutputStreams.iterator();\n    while (it.hasNext()) {\n      try {\n        PrintWriter writer = (PrintWriter) it.next();\n        writer.println(message);\n        writer.flush();\n      } catch (Exception ex) {\n        ex.printStackTrace();\n      }\n\n    } // end while\n\n  } // close tellEveryone\n} // close class", "num_file": 2, "num_lines": 170, "programming_language": "Java"}
{"class_name": "Train", "id": "./MultiFileTest/Java/Train.java", "original_code": "// ./Train/Driver.java\npackage projecteval.Train;\n\npublic class Driver\n{\n    /**\n     * This testdriver wil test the difrent methods from train and trainstation\n     */\n    public static void test() {\n        Train t1 = new Train(\"Aarhus\", \"Berlin\", 999);\n        Train t2 = new Train(\"Herning\", \"Copenhagen\", 42);\n        Train t3 = new Train(\"Aarhus\", \"Herning\", 66);\n        Train t4 = new Train(\"Odense\", \"Herning\", 177);\n        Train t5 = new Train(\"Aarhus\", \"Copenhagen\", 122);\n\n        System.out.println(\"Opgave 3:\");\n        System.out.println(\"*******************\");\n        System.out.println(t1);\n        System.out.println(t2);\n        System.out.println(t3);\n        System.out.println(t4);\n        System.out.println(t5);\n        System.out.println(\"*******************\");\n        System.out.println(\"\");\n\n        TrainStation ts = new TrainStation(\"Herning\");\n        ts.addTrain(t1);\n        ts.addTrain(t2);\n        ts.addTrain(t3);\n        ts.addTrain(t4);\n        ts.addTrain(t5);\n\n        System.out.println(\"Opgave 8:\");\n        System.out.println(\"*******************\");\n        System.out.println(\"No. of trains going from or to Herning:\");\n        System.out.println(ts.connectingTrains());\n        System.out.println(\"*******************\");\n        System.out.println(\"\");\n\n        System.out.println(\"Opgave 9:\");\n        System.out.println(\"*******************\");\n        System.out.println(\"The cheapest train going to Copenhagen is going:\");\n        System.out.println(ts.cheapTrainTo(\"Copenhagen\"));\n        System.out.println(\"*******************\");\n        System.out.println(\"\");\n\n        System.out.println(\"Opgave 10:\");\n        System.out.println(\"*******************\");\n        ts.printTrainStation();\n        System.out.println(\"*******************\");\n        System.out.println(\"\");\n\n        System.out.println(\"Opgave 11:\");\n        System.out.println(\"*******************\");\n        System.out.println(\"Trains going from Aarhus to Herning:\");\n        for(Train t : ts.trainsFrom(\"Aarhus\")) {\n            System.out.println(t);\n        }\n        System.out.println(\"*******************\");\n        System.out.println(\"\");\n\n        System.out.println(\"Opgave 12:\");\n        System.out.println(\"*******************\");\n        System.out.println(\"The cheapest train going from herning to Copenhagen:\");\n        System.out.println(ts.cheapTrain(\"Copenhagen\"));\n        System.out.println(\"*******************\");\n        System.out.println(\"\");\n    }\n}\n\n\n// ./Train/Train.java\npackage projecteval.Train;\n\nimport java.util.Collections;\n\npublic class Train implements Comparable<Train>\n{\n    private String departure;\n    private String destination;\n    private int price;\n\n    public Train(String departure, String destination, int price)\n    {\n        this.departure = departure;\n        this.destination = destination;\n        this.price = price;\n    }\n\n    /**\n     * A method to get the departure\n     */\n    public String getDeparture() {\n        return departure;\n    }\n\n    /**\n     * A method to get the destiantion\n     */\n    public String getDestiantion() {\n        return destination;\n    }\n\n    /**\n     * A method to get grice\n     */\n    public int getPrice() {\n        return price;\n    }\n\n    /**\n     * This method will format a String of the given way\n     */\n    public String toString() {\n        return \"From \" + departure + \" to \" + destination + \" for \" + price + \" DKK\";\n    }\n\n    /**\n     * This method sorts departures alphabeticly, if they have the same \n     * departures then it wil sort after price from lovest til highest\n     */\n    public int compareTo(Train other) {\n        if(!departure.equals(other.departure)) {\n            return departure.compareTo(other.departure);\n        } else \n        {\n            return price - other.price;\n        }\n    }\n}\n\n\n// ./Train/TrainStation.java\npackage projecteval.Train;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.stream.Collectors;\nimport java.util.Comparator;\n\npublic class TrainStation\n{\n    private String city;\n    private ArrayList<Train> trains;\n\n    public TrainStation(String city)\n    {\n        this.city = city;\n        trains = new ArrayList<Train>();\n    }\n\n    /**\n     * this method adds trains tot the ArrayList trains\n     */\n    public void addTrain(Train t) {\n        trains.add(t);\n    }\n\n    /**\n     * Method will return the number of trains that starts or ends in the\n     * city of the Trainstation\n     */\n    public int connectingTrains() {\n        int result = 0;\n        for(Train t : trains) {\n            if(city.equals(t.getDeparture()) || city.equals(t.getDestiantion())) {\n                result ++;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * This method returns the chepest train go to a spesific destination\n     */\n    public Train cheapTrainTo(String destination) {\n        Train result = null;\n        for(Train t : trains) {\n            if(destination.equals(t.getDestiantion())) {\n                if(result == null || result.getPrice() > t.getPrice()) {\n                    result = t;\n                }\n            }\n        }\n        return result;\n    }\n\n    /**\n     * This method prints out all trains in the ArrayList trains\n     * in sorted order after the departurs in alphabeticly order\n     * if they have the same departures then it wil sort after price \n     * from lovest til highest\n     */\n    public void printTrainStation() {\n        Collections.sort(trains);\n        System.out.println(\"The trainstaion in \" + city + \" has following trains:\");\n        for(Train t : trains) {\n            System.out.println(t);\n        }\n    }\n\n    /**\n     * This method will return all trains that starts in a given place\n     * going to the Trainstations city.\n     */\n    public List<Train> trainsFrom(String departure) {\n        return trains.stream()\n        .filter(t -> t.getDeparture().equals(departure) && t.getDestiantion().equals(city))\n        .collect(Collectors.toList());\n    }\n\n    /**\n     * This method returns the cheapest train strating in the Trainstations \n     * city, and ends in a given destination\n     */\n    public Train cheapTrain(String destination) {\n        return trains.stream()\n        .filter(t -> t.getDeparture().equals(city) && t.getDestiantion().equals(destination))\n        .min(Comparator.comparing(t -> t.getPrice()))\n        .orElse(null);\n    }\n}\n", "num_file": 3, "num_lines": 216, "programming_language": "Java"}
{"class_name": "bankingApplication", "id": "./MultiFileTest/Java/bankingApplication.java", "original_code": "// ./bankingApplication/bank.java\npackage projecteval.bankingApplication;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\n\npublic class bank {\n\tpublic static void main(String args[]) //main class of bank\n\t\tthrows IOException\n\t{\n\n\t\tBufferedReader sc = new BufferedReader(\n\t\t\tnew InputStreamReader(System.in));\n\t\tString name = \"\";\n\t\tint pass_code;\n\t\tint ac_no;\n\t\tint ch;\n\n\t\twhile (true) {\n\t\t\tSystem.out.println(\n\t\t\t\t\"\\n ->|| Welcome to InBank ||<- \\n\");\n\t\t\tSystem.out.println(\"1)Create Account\");\n\t\t\tSystem.out.println(\"2)Login Account\");\n\n\t\t\ttry {\n\t\t\t\tSystem.out.print(\"\\n Enter Input:\"); //user input\n\t\t\t\tch = Integer.parseInt(sc.readLine());\n\n\t\t\t\tswitch (ch) {\n\t\t\t\tcase 1:\n\t\t\t\t\ttry {\n\t\t\t\t\t\tSystem.out.print(\n\t\t\t\t\t\t\t\"Enter Unique UserName:\");\n\t\t\t\t\t\tname = sc.readLine();\n\t\t\t\t\t\tSystem.out.print(\n\t\t\t\t\t\t\t\"Enter New Password:\");\n\t\t\t\t\t\tpass_code = Integer.parseInt(\n\t\t\t\t\t\t\tsc.readLine());\n\n\t\t\t\t\t\tif (bankManagement.createAccount(\n\t\t\t\t\t\t\t\tname, pass_code)) {\n\t\t\t\t\t\t\tSystem.out.println(\n\t\t\t\t\t\t\t\t\"MSG : Account Created Successfully!\\n\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tSystem.out.println(\n\t\t\t\t\t\t\t\t\"ERR : Account Creation Failed!\\n\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcatch (Exception e) {\n\t\t\t\t\t\tSystem.out.println(\n\t\t\t\t\t\t\t\" ERR : Enter Valid Data::Insertion Failed!\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 2:\n\t\t\t\t\ttry {\n\t\t\t\t\t\tSystem.out.print(\n\t\t\t\t\t\t\t\"Enter UserName:\");\n\t\t\t\t\t\tname = sc.readLine();\n\t\t\t\t\t\tSystem.out.print(\n\t\t\t\t\t\t\t\"Enter Password:\");\n\t\t\t\t\t\tpass_code = Integer.parseInt(\n\t\t\t\t\t\t\tsc.readLine());\n\n\t\t\t\t\t\tif (bankManagement.loginAccount(\n\t\t\t\t\t\t\t\tname, pass_code)) {\n\t\t\t\t\t\t\tSystem.out.println(\n\t\t\t\t\t\t\t\t\"MSG : Logout Successfully!\\n\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tSystem.out.println(\n\t\t\t\t\t\t\t\t\"ERR : login Failed!\\n\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcatch (Exception e) {\n\t\t\t\t\t\tSystem.out.println(\n\t\t\t\t\t\t\t\" ERR : Enter Valid Data::Login Failed!\\n\");\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\tSystem.out.println(\"Invalid Entry!\\n\");\n\t\t\t\t}\n\n\t\t\t\tif (ch == 5) {\n\t\t\t\t\tSystem.out.println(\n\t\t\t\t\t\t\"Exited Successfully!\\n\\n Thank You :)\");\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch (Exception e) {\n\t\t\t\tSystem.out.println(\"Enter Valid Entry!\");\n\t\t\t}\n\t\t}\n\t\tsc.close();\n\t}\n}\n\n\n// ./bankingApplication/bankManagement.java\npackage projecteval.bankingApplication;\n\nimport java.io.BufferedReader;\nimport java.io.InputStreamReader;\nimport java.sql.Connection;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.SQLIntegrityConstraintViolationException;\nimport java.sql.Statement;\n\npublic class bankManagement { // these class provides all\n\t\t\t\t\t\t\t// bank method\n\n\tprivate static final int NULL = 0;\n\n\tstatic Connection con = connection.getConnection();\n\tstatic String sql = \"\";\n\tpublic static boolean\n\tcreateAccount(String name,\n\t\t\t\tint passCode) // create account function\n\t{\n\t\ttry {\n\t\t\t// validation\n\t\t\tif (name == \"\" || passCode == NULL) {\n\t\t\t\tSystem.out.println(\"All Field Required!\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t// query\n\t\t\tStatement st = con.createStatement();\n\t\t\tsql = \"INSERT INTO customer(cname,balance,pass_code) values('\"\n\t\t\t\t+ name + \"',1000,\" + passCode + \")\";\n\n\t\t\t// Execution\n\t\t\tif (st.executeUpdate(sql) == 1) {\n\t\t\t\tSystem.out.println(name\n\t\t\t\t\t\t\t\t+ \", Now You Login!\");\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\t// return\n\t\t}\n\t\tcatch (SQLIntegrityConstraintViolationException e) {\n\t\t\tSystem.out.println(\"Username Not Available!\");\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn false;\n\t}\n\tpublic static boolean\n\tloginAccount(String name, int passCode) // login method\n\t{\n\t\ttry {\n\t\t\t// validation\n\t\t\tif (name == \"\" || passCode == NULL) {\n\t\t\t\tSystem.out.println(\"All Field Required!\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t// query\n\t\t\tsql = \"select * from customer where cname='\"\n\t\t\t\t+ name + \"' and pass_code=\" + passCode;\n\t\t\tPreparedStatement st\n\t\t\t\t= con.prepareStatement(sql);\n\t\t\tResultSet rs = st.executeQuery();\n\t\t\t// Execution\n\t\t\tBufferedReader sc = new BufferedReader(\n\t\t\t\tnew InputStreamReader(System.in));\n\n\t\t\tif (rs.next()) {\n\t\t\t\t// after login menu driven interface method\n\n\t\t\t\tint ch = 5;\n\t\t\t\tint amt = 0;\n\t\t\t\tint senderAc = rs.getInt(\"ac_no\");\n\t\t\t\t;\n\t\t\t\tint receiveAc;\n\t\t\t\twhile (true) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tSystem.out.println(\n\t\t\t\t\t\t\t\"Hallo, \"\n\t\t\t\t\t\t\t+ rs.getString(\"cname\"));\n\t\t\t\t\t\tSystem.out.println(\n\t\t\t\t\t\t\t\"1)Transfer Money\");\n\t\t\t\t\t\tSystem.out.println(\"2)View Balance\");\n\t\t\t\t\t\tSystem.out.println(\"5)LogOut\");\n\n\t\t\t\t\t\tSystem.out.print(\"Enter Choice:\");\n\t\t\t\t\t\tch = Integer.parseInt(\n\t\t\t\t\t\t\tsc.readLine());\n\t\t\t\t\t\tif (ch == 1) {\n\t\t\t\t\t\t\tSystem.out.print(\n\t\t\t\t\t\t\t\t\"Enter Receiver A/c No:\");\n\t\t\t\t\t\t\treceiveAc = Integer.parseInt(\n\t\t\t\t\t\t\t\tsc.readLine());\n\t\t\t\t\t\t\tSystem.out.print(\n\t\t\t\t\t\t\t\t\"Enter Amount:\");\n\t\t\t\t\t\t\tamt = Integer.parseInt(\n\t\t\t\t\t\t\t\tsc.readLine());\n\n\t\t\t\t\t\t\tif (bankManagement\n\t\t\t\t\t\t\t\t\t.transferMoney(\n\t\t\t\t\t\t\t\t\t\tsenderAc, receiveAc,\n\t\t\t\t\t\t\t\t\t\tamt)) {\n\t\t\t\t\t\t\t\tSystem.out.println(\n\t\t\t\t\t\t\t\t\t\"MSG : Money Sent Successfully!\\n\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tSystem.out.println(\n\t\t\t\t\t\t\t\t\t\"ERR : Failed!\\n\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (ch == 2) {\n\n\t\t\t\t\t\t\tbankManagement.getBalance(\n\t\t\t\t\t\t\t\tsenderAc);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (ch == 5) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tSystem.out.println(\n\t\t\t\t\t\t\t\t\"Err : Enter Valid input!\\n\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcatch (Exception e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t// return\n\t\t\treturn true;\n\t\t}\n\t\tcatch (SQLIntegrityConstraintViolationException e) {\n\t\t\tSystem.out.println(\"Username Not Available!\");\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn false;\n\t}\n\tpublic static void\n\tgetBalance(int acNo) // fetch balance method\n\t{\n\t\ttry {\n\n\t\t\t// query\n\t\t\tsql = \"select * from customer where ac_no=\"\n\t\t\t\t+ acNo;\n\t\t\tPreparedStatement st\n\t\t\t\t= con.prepareStatement(sql);\n\n\t\t\tResultSet rs = st.executeQuery(sql);\n\t\t\tSystem.out.println(\n\t\t\t\t\"-----------------------------------------------------------\");\n\t\t\tSystem.out.printf(\"%12s %10s %10s\\n\",\n\t\t\t\t\t\t\t\"Account No\", \"Name\",\n\t\t\t\t\t\t\t\"Balance\");\n\n\t\t\t// Execution\n\n\t\t\twhile (rs.next()) {\n\t\t\t\tSystem.out.printf(\"%12d %10s %10d.00\\n\",\n\t\t\t\t\t\t\t\trs.getInt(\"ac_no\"),\n\t\t\t\t\t\t\t\trs.getString(\"cname\"),\n\t\t\t\t\t\t\t\trs.getInt(\"balance\"));\n\t\t\t}\n\t\t\tSystem.out.println(\n\t\t\t\t\"-----------------------------------------------------------\\n\");\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\tpublic static boolean transferMoney(int sender_ac,\n\t\t\t\t\t\t\t\t\t\tint reveiver_ac,\n\t\t\t\t\t\t\t\t\t\tint amount)\n\t\tthrows SQLException // transfer money method\n\t{\n\t\t// validation\n\t\tif (reveiver_ac == NULL || amount == NULL) {\n\t\t\tSystem.out.println(\"All Field Required!\");\n\t\t\treturn false;\n\t\t}\n\t\ttry {\n\t\t\tcon.setAutoCommit(false);\n\t\t\tsql = \"select * from customer where ac_no=\"\n\t\t\t\t+ sender_ac;\n\t\t\tPreparedStatement ps\n\t\t\t\t= con.prepareStatement(sql);\n\t\t\tResultSet rs = ps.executeQuery();\n\n\t\t\tif (rs.next()) {\n\t\t\t\tif (rs.getInt(\"balance\") < amount) {\n\t\t\t\t\tSystem.out.println(\n\t\t\t\t\t\t\"Insufficient Balance!\");\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tStatement st = con.createStatement();\n\n\t\t\t// debit\n\t\t\tcon.setSavepoint();\n\n\t\t\tsql = \"update customer set balance=balance-\"\n\t\t\t\t+ amount + \" where ac_no=\" + sender_ac;\n\t\t\tif (st.executeUpdate(sql) == 1) {\n\t\t\t\tSystem.out.println(\"Amount Debited!\");\n\t\t\t}\n\n\t\t\t// credit\n\t\t\tsql = \"update customer set balance=balance+\"\n\t\t\t\t+ amount + \" where ac_no=\" + reveiver_ac;\n\t\t\tst.executeUpdate(sql);\n\n\t\t\tcon.commit();\n\t\t\treturn true;\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\tcon.rollback();\n\t\t}\n\t\t// return\n\t\treturn false;\n\t}\n}\n\n\n// ./bankingApplication/connection.java\npackage projecteval.bankingApplication;\n\nimport java.sql.Connection;\nimport java.sql.DriverManager;\n// Global connection Class\npublic class connection {\n\tstatic Connection con; // Global Connection Object\n\tpublic static Connection getConnection()\n\t{\n\t\ttry {\n\t\t\t\n\t\t\t\n\t\t\tString mysqlJDBCDriver\n\t\t\t\t= \"com.mysql.cj.jdbc.Driver\"; //jdbc driver\n\t\t\tString url\n\t\t\t\t= \"jdbc:mysql://localhost:3306/mydata\"; //mysql url\n\t\t\tString user = \"root\";\t //mysql username\n\t\t\tString pass = \"Pritesh4@\"; //mysql passcode\n\t\t\tClass.forName(mysqlJDBCDriver);\n\t\t\tcon = DriverManager.getConnection(url, user,\n\t\t\t\t\t\t\t\t\t\t\tpass);\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tSystem.out.println(\"Connection Failed!\");\n\t\t}\n\n\t\treturn con;\n\t}\n}\n", "num_file": 3, "num_lines": 357, "programming_language": "Java"}
{"class_name": "emailgenerator", "id": "./MultiFileTest/Java/emailgenerator.java", "original_code": "// ./emailgenerator/Email.java\npackage projecteval.emailgenerator;\n\nimport java.util.Scanner;\n\npublic class Email {\n\tprivate String firstName;\n\tprivate String lastName;\n\tprivate String password;\n\tprivate String department;\n\tprivate String email;\n\tprivate int defaultPasswordLength=8;\n\tprivate int codelen=5;\n\tprivate String Vcode;\n\tprivate String company=\"drngpit.ac.in\";\n\tprivate String name;\n\n\tpublic Email(String firstName, String lastName) {\n\t\tthis.firstName = firstName;\n\t\tthis.lastName = lastName;\n\t\tSystem.out.println(\"Kindly ! Enter department for email creation dear \"+this.firstName+\" \"+this.lastName);\n\t\t//dept\n\t\tthis.department=setDepartment();\n\t\tSystem.out.println(\"Department:\"+department);\n\t\t//pass\n\t\tthis.password=randomPass(defaultPasswordLength);\n\t\tSystem.out.println(\"New Password :\"+password);\n\t\t//clipping name as one\n\t\tthis.name=firstName+lastName;\n\t\t//verification code\n\t\tthis.Vcode=vcode(codelen);\n\t\tSystem.out.println(\"Your verification code : \"+Vcode);\n\n\t\t//Binding\n\t\temail=name.toLowerCase()+\".\"+department+\"@\"+company;\n\t\tSystem.out.println(\"Official mail :\"+email);\n\t}\n\n\tprivate String setDepartment(){\n\t\tSystem.out.println(\"Enter the department Id\\nSales : 1\\nDevelopment : 2\\nAccounting : 3\");\n\t\tScanner in=new Scanner(System.in);\n\t\tint dep=in.nextInt();\n\t\tif(dep==1){\n\t\t\treturn \"sales\";\n\t\t}\n\t\telse if(dep==2){\n\t\t\treturn\"dev\";\n\t\t}\n\t\telse if(dep==3){\n\t\t\treturn \"acc\";\n\t\t}\n\t\treturn\"\";\n\t}\n\n\tprivate String randomPass(int length){\n\t\tString password=\"ABCEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%\";\n\t\tchar[]pass=new char[length];\n\t\tfor(int i=0;i<length;i++){\n\t\t\tint rand=(int)(Math.random()*password.length());\n\t\t\tpass[i]=password.charAt(rand);\n\t\t}\n\t\treturn new String(pass);\n\t}\n\tprivate String vcode(int codelen){\n\t\tString samcode=\"1234567890\";\n\t\tchar[]code=new char[codelen];\n\t\tfor(int i=0;i<codelen;i++){\n\t\t\tint c=(int)(Math.random()*samcode.length());\n\t\t\tcode[i]=samcode.charAt(c);\n\t\t}\n\t\treturn new String(code);\n\t}\n\n\tpublic void setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\n\tpublic String getDepartment() {\n\t\treturn department;\n\t}\n\n\tpublic void setDepartment(String department) {\n\t\tthis.department = department;\n\t}\n\n\tpublic String getEmail() {\n\t\treturn email;\n\t}\n\n\tpublic void setEmail(String email) {\n\t\tthis.email = email;\n\t}\n\n\n\tpublic String getPassword(){\n\t\treturn password;\n\t}\n\n\tpublic String getFirstName() {\n\t\treturn firstName;\n\t}\n\n\tpublic void setFirstName(String firstName) {\n\t\tthis.firstName = firstName;\n\t}\n\n\tpublic String getVcode() {\n\t\treturn Vcode;\n\t}\n\tpublic String getDept(String dep){\n\t\tif(dep.equals(\"dev\")){\n\t\t\treturn \"Developers\";\n\t\t}\n\t\telse if(dep.equals(\"acc\")){\n\t\t\treturn \"Accounts\";\n\t\t}\n\t\telse if(dep.equals(\"sales\")){\n\t\t\treturn \"Sales\";\n\t\t}\n\t\treturn \"\";\n\n\t}\n\tpublic String showInfo(){\n\t\treturn \"Name : \"+name+\"\\nOfficial email : \"+email+\"\\nDepartment : \"+getDept(department);\n\t}\n}\n\n\n// ./emailgenerator/EmailApp.java\npackage projecteval.emailgenerator;\n\nimport com.sun.security.jgss.GSSUtil;\n\nimport java.sql.SQLOutput;\nimport java.util.Scanner;\n\npublic class EmailApp {\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(\"Generate Organization's Email ==>\");\n\t\tScanner sc=new Scanner(System.in);\n\n//        String x=sc.nextLine();\n\t\tSystem.out.println(\"Generating the email...\");\n\t\tSystem.out.println(\"Enter firstname :\");\n\t\tString first=sc.nextLine();\n\t\tSystem.out.println(\"Enter Lastname :\");\n\t\tString second=sc.nextLine();\n\n\t\tEmail em=new Email(first,second);\n\n\t\twhile(true) {\n\t\t\tSystem.out.println(\"1 : Information \");\n\t\t\tSystem.out.println(\"2 : Change Email\");\n\t\t\tSystem.out.println(\"3 : Change Password\");\n\t\t\tSystem.out.println(\"4 : Disclose Password\");\n\t\t\tSystem.out.println(\"5 : Exit\");\n\t\t\tSystem.out.println(\"Enter operation code :\");\n\t\t\tint a = sc.nextInt();\n\t\t\tswitch (a) {\n\t\t\t\tcase 1:\n\t\t\t\t\tSystem.out.println(em.showInfo());\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tSystem.out.println(\"Enter alternate email prefix :\");\n\t\t\t\t\tsc.nextLine();\n\t\t\t\t\tString alt = sc.nextLine();\n\t\t\t\t\tem.setEmail(alt+\"@drngpit.ac.in\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase 3:\n\t\t\t\t\tSystem.out.println(\"Enter the verification code :\");\n\t\t\t\t\tsc.nextLine();\n\t\t\t\t\tString s = sc.nextLine();\n\t\t\t\t\tif (s.equals(em.getVcode())) {\n\t\t\t\t\t\tSystem.out.println(\"Enter alternate password :\");\n\t\t\t\t\t\tString p = sc.nextLine();\n\t\t\t\t\t\tem.setPassword(p);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tSystem.out.println(\"Please Enter valid verification code !!!\");\n\t\t\t\t\t}\n\t\t\t\t\tSystem.out.println(\"Password updated successfully !!!\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase 4:\n\t\t\t\t\tSystem.out.println(\"Password disclose warning !!!\");\n\t\t\t\t\tSystem.out.println(\"Enter the verification code :\");\n\t\t\t\t\tsc.nextLine();\n\t\t\t\t\tString s1 = sc.nextLine();\n\t\t\t\t\tif (s1.equals(em.getVcode())) {\n\t\t\t\t\t\tSystem.out.println(\"Your password : \" + em.getPassword());\n\t\t\t\t\t} else {\n\t\t\t\t\t\tSystem.out.println(\"Please Enter valid verification code !!!\");\n\t\t\t\t\t}\n\t\t\t\tcase 5:\n\t\t\t\t\tSystem.out.println(\"Have a great day ahead ! BYE \");\n\t\t\t\t\treturn ;\n\t\t\t}\n\t\t}\n\t}\n}", "num_file": 2, "num_lines": 194, "programming_language": "Java"}
{"class_name": "heap", "id": "./MultiFileTest/Java/heap.java", "original_code": "// ./heap/FibonacciHeap.java\npackage projecteval.heap;\n\npublic class FibonacciHeap {\n\n    private static final double GOLDEN_RATIO = (1 + Math.sqrt(5)) / 2;\n    private HeapNode min;\n    private static int totalLinks = 0;\n    private static int totalCuts = 0;\n    private int numOfTrees = 0;\n    private int numOfHeapNodes = 0;\n    private int markedHeapNoodesCounter = 0;\n\n    /*\n     * a constructor for an empty Heap\n     * set the min to be null\n     */\n    public FibonacciHeap() {\n        this.min = null;\n    }\n\n    /*\n     * a constructor for a Heap with one element\n     * set the min to be the HeapNode with the given key\n     * @pre key>=0\n     * @post empty == false\n     */\n    public FibonacciHeap(int key) {\n        this.min = new HeapNode(key);\n        this.numOfTrees++;\n        this.numOfHeapNodes++;\n    }\n\n    /*\n     * check if the heap is empty\n     * $ret == true - if the tree is empty\n     */\n    public boolean empty() {\n        return (this.min == null);\n    }\n\n    /**\n     * Creates a node (of type HeapNode) which contains the given key, and inserts it into the heap.\n     *\n     * @pre key>=0\n     * @post (numOfnodes = = $prev numOfnodes + 1)\n     * @post empty == false\n     * $ret = the HeapNode we inserted\n     */\n    public HeapNode insert(int key) {\n        HeapNode toInsert = new HeapNode(key); // creates the node\n        if (this.empty()) {\n            this.min = toInsert;\n        } else { // tree is not empty\n            min.setNext(toInsert);\n            this.updateMin(toInsert);\n        }\n        this.numOfHeapNodes++;\n        this.numOfTrees++;\n        return toInsert;\n    }\n\n    /**\n     * Delete the node containing the minimum key in the heap\n     * updates new min\n     *\n     * @post (numOfnodes = = $prev numOfnodes - 1)\n     */\n    public void deleteMin() {\n        if (this.empty()) {\n            return;\n        }\n        if (this.numOfHeapNodes == 1) { // if there is only one tree\n            this.min = null;\n            this.numOfTrees--;\n            this.numOfHeapNodes--;\n            return;\n        }\n        // change all children's parent to null//\n        if (this.min.child != null) { // min has a child\n            HeapNode child = this.min.child;\n            HeapNode tmpChild = child;\n            child.parent = null;\n            while (child.next != tmpChild) {\n                child = child.next;\n                child.parent = null;\n            }\n        }\n        // delete the node//\n        if (this.numOfTrees > 1) {\n            (this.min.prev).next = this.min.next;\n            (this.min.next).prev = this.min.prev;\n            if (this.min.child != null) {\n                (this.min.prev).setNext(this.min.child);\n            }\n        } else { // this.numOfTrees = 1\n            this.min = this.min.child;\n        }\n        this.numOfHeapNodes--;\n        this.successiveLink(this.min.getNext());\n    }\n\n    /**\n     * Return the node of the heap whose key is minimal.\n     * $ret == null if (empty==true)\n     */\n    public HeapNode findMin() {\n        return this.min;\n    }\n\n    /**\n     * Meld the heap with heap2\n     *\n     * @pre heap2 != null\n     * @post (numOfnodes = = $prev numOfnodes + heap2.numOfnodes)\n     */\n    public void meld(FibonacciHeap heap2) {\n        if (heap2.empty()) {\n            return;\n        }\n        if (this.empty()) {\n            this.min = heap2.min;\n        } else {\n            this.min.setNext(heap2.min);\n            this.updateMin(heap2.min);\n        }\n        this.numOfTrees += heap2.numOfTrees;\n        this.numOfHeapNodes += heap2.numOfHeapNodes;\n    }\n\n    /**\n     * Return the number of elements in the heap\n     * $ret == 0 if heap is empty\n     */\n    public int size() {\n        return this.numOfHeapNodes;\n    }\n\n    /**\n     * Return a counters array, where the value of the i-th index is the number of trees with rank i\n     * in the heap. returns an empty array for an empty heap\n     */\n    public int[] countersRep() {\n        if (this.empty()) {\n            return new int[0]; /// return an empty array\n        }\n        int[] rankArray = new int[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO)) + 1]; // creates the array\n        rankArray[this.min.rank]++;\n        HeapNode curr = this.min.next;\n        while (curr != this.min) {\n            rankArray[curr.rank]++;\n            curr = curr.next;\n        }\n        return rankArray;\n    }\n\n    /**\n     * Deletes the node x from the heap (using decreaseKey(x) to -1)\n     *\n     * @pre heap contains x\n     * @post (numOfnodes = = $prev numOfnodes - 1)\n     */\n    public void delete(HeapNode x) {\n        this.decreaseKey(x, x.getKey() + 1); // change key to be the minimal (-1)\n        this.deleteMin(); // delete it\n    }\n\n    /**\n     * The function decreases the key of the node x by delta.\n     *\n     * @pre x.key >= delta (we don't realize it when calling from delete())\n     * @pre heap contains x\n     */\n    private void decreaseKey(HeapNode x, int delta) {\n        int newKey = x.getKey() - delta;\n        x.key = newKey;\n        if (x.isRoot()) { // no parent to x\n            this.updateMin(x);\n            return;\n        }\n        if (x.getKey() >= x.parent.getKey()) {\n            return;\n        } // we don't need to cut\n        HeapNode prevParent = x.parent;\n        this.cut(x);\n        this.cascadingCuts(prevParent);\n    }\n\n    /**\n     * returns the current potential of the heap, which is:\n     * Potential = #trees + 2*#markedNodes\n     */\n    public int potential() {\n        return numOfTrees + (2 * markedHeapNoodesCounter);\n    }\n\n    /**\n     * This static function returns the total number of link operations made during the run-time of\n     * the program. A link operation is the operation which gets as input two trees of the same\n     * rank, and generates a tree of rank bigger by one.\n     */\n    public static int totalLinks() {\n        return totalLinks;\n    }\n\n    /**\n     * This static function returns the total number of cut operations made during the run-time of\n     * the program. A cut operation is the operation which disconnects a subtree from its parent\n     * (during decreaseKey/delete methods).\n     */\n    public static int totalCuts() {\n        return totalCuts;\n    }\n\n    /*\n     * updates the min of the heap (if needed)\n     * @pre this.min == @param (posMin) if and only if (posMin.key < this.min.key)\n     */\n    private void updateMin(HeapNode posMin) {\n        if (posMin.getKey() < this.min.getKey()) {\n            this.min = posMin;\n        }\n    }\n\n    /*\n     * Recursively \"runs\" all the way up from @param (curr) and mark the nodes.\n     * stop the recursion if we had arrived to a marked node or to a root.\n     * if we arrived to a marked node, we cut it and continue recursively.\n     * called after a node was cut.\n     * @post (numOfnodes == $prev numOfnodes)\n     */\n    private void cascadingCuts(HeapNode curr) {\n        if (!curr.isMarked()) { // stop the recursion\n            curr.mark();\n            if (!curr.isRoot()) this.markedHeapNoodesCounter++;\n        } else {\n            if (curr.isRoot()) {\n                return;\n            }\n            HeapNode prevParent = curr.parent;\n            this.cut(curr);\n            this.cascadingCuts(prevParent);\n        }\n    }\n\n    /*\n     * cut a node (and his \"subtree\") from his origin tree and connect it to the heap as a new tree.\n     * called after a node was cut.\n     * @post (numOfnodes == $prev numOfnodes)\n     */\n    private void cut(HeapNode curr) {\n        curr.parent.rank--;\n        if (curr.marked) {\n            this.markedHeapNoodesCounter--;\n            curr.marked = false;\n        }\n        if (curr.parent.child == curr) { // we should change the parent's child\n            if (curr.next == curr) { // curr do not have brothers\n                curr.parent.child = null;\n            } else { // curr have brothers\n                curr.parent.child = curr.next;\n            }\n        }\n        curr.prev.next = curr.next;\n        curr.next.prev = curr.prev;\n        curr.next = curr;\n        curr.prev = curr;\n        curr.parent = null;\n        this.min.setNext(curr);\n        this.updateMin(curr);\n        this.numOfTrees++;\n        totalCuts++;\n    }\n\n    /*\n     *\n     */\n    private void successiveLink(HeapNode curr) {\n        HeapNode[] buckets = this.toBuckets(curr);\n        this.min = this.fromBuckets(buckets);\n    }\n\n    /*\n     *\n     */\n    private HeapNode[] toBuckets(HeapNode curr) {\n        HeapNode[] buckets = new HeapNode[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO)) + 1];\n        curr.prev.next = null;\n        HeapNode tmpCurr;\n        while (curr != null) {\n            tmpCurr = curr;\n            curr = curr.next;\n            tmpCurr.next = tmpCurr;\n            tmpCurr.prev = tmpCurr;\n            while (buckets[tmpCurr.rank] != null) {\n                tmpCurr = this.link(tmpCurr, buckets[tmpCurr.rank]);\n                buckets[tmpCurr.rank - 1] = null;\n            }\n            buckets[tmpCurr.rank] = tmpCurr;\n        }\n        return buckets;\n    }\n\n    /*\n     *\n     */\n    private HeapNode fromBuckets(HeapNode[] buckets) {\n        HeapNode tmpMin = null;\n        this.numOfTrees = 0;\n        for (int i = 0; i < buckets.length; i++) {\n            if (buckets[i] != null) {\n                this.numOfTrees++;\n                if (tmpMin == null) {\n                    tmpMin = buckets[i];\n                    tmpMin.next = tmpMin;\n                    tmpMin.prev = tmpMin;\n                } else {\n                    tmpMin.setNext(buckets[i]);\n                    if (buckets[i].getKey() < tmpMin.getKey()) {\n                        tmpMin = buckets[i];\n                    }\n                }\n            }\n        }\n        return tmpMin;\n    }\n\n    /*\n     * link between two nodes (and their trees)\n     * defines the smaller node to be the parent\n     */\n    private HeapNode link(HeapNode c1, HeapNode c2) {\n        if (c1.getKey() > c2.getKey()) {\n            HeapNode c3 = c1;\n            c1 = c2;\n            c2 = c3;\n        }\n        if (c1.child == null) {\n            c1.child = c2;\n        } else {\n            c1.child.setNext(c2);\n        }\n        c2.parent = c1;\n        c1.rank++;\n        totalLinks++;\n        return c1;\n    }\n\n    /**\n     * public class HeapNode\n     * each HeapNode belongs to a heap (Inner class)\n     */\n    public class HeapNode {\n\n        public int key;\n        private int rank;\n        private boolean marked;\n        private HeapNode child;\n        private HeapNode next;\n        private HeapNode prev;\n        private HeapNode parent;\n\n        /*\n         * a constructor for a heapNode withe key @param (key)\n         * prev == next == this\n         * parent == child == null\n         */\n        public HeapNode(int key) {\n            this.key = key;\n            this.marked = false;\n            this.next = this;\n            this.prev = this;\n        }\n\n        /*\n         * returns the key of the node.\n         */\n        public int getKey() {\n            return this.key;\n        }\n\n        /*\n         * checks whether the node is marked\n         * $ret = true if one child has been cut\n         */\n        private boolean isMarked() {\n            return this.marked;\n        }\n\n        /*\n         * mark a node (after a child was cut)\n         * @inv root.mark() == false.\n         */\n        private void mark() {\n            if (this.isRoot()) {\n                return;\n            } // check if the node is a root\n            this.marked = true;\n        }\n\n        /*\n         * add the node @param (newNext) to be between this and this.next\n         * works fine also if @param (newNext) does not \"stands\" alone\n         */\n        private void setNext(HeapNode newNext) {\n            HeapNode tmpNext = this.next;\n            this.next = newNext;\n            this.next.prev.next = tmpNext;\n            tmpNext.prev = newNext.prev;\n            this.next.prev = this;\n        }\n\n        /*\n         * returns the next node to this node\n         */\n        private HeapNode getNext() {\n            return this.next;\n        }\n\n        /*\n         * check if the node is a root\n         * root definition - this.parent == null (uppest in his tree)\n         */\n        private boolean isRoot() {\n            return (this.parent == null);\n        }\n    }\n}\n\n\n// ./heap/HeapPerformanceTest.java\npackage projecteval.heap;\n\nimport java.util.HashMap;\nimport java.util.Random;\nimport java.util.ArrayList;\n\npublic class HeapPerformanceTest {\n\n    private final int numElements;\n\n    public HeapPerformanceTest(int numElements) {\n        this.numElements = numElements;\n    }\n\n    public HashMap<String, Long> test() {\n        // Number of elements to test\n        // Create heaps for insertion and deletion tests\n        FibonacciHeap fibonacciHeap = new FibonacciHeap();\n        LeftistHeap leftistHeap = new LeftistHeap();\n        HashMap<String, Long> ret = new HashMap<>();\n\n        // Insertion test\n        long startTime = System.currentTimeMillis();\n        for (int i = 0; i < numElements; i++) {\n            fibonacciHeap.insert(new Random().nextInt());\n        }\n        long endTime = System.currentTimeMillis();\n        ret.put(\"Fibonacci Heap Insertion Time\", endTime - startTime);\n\n        startTime = System.currentTimeMillis();\n        for (int i = 0; i < numElements; i++) {\n            leftistHeap.insert(new Random().nextInt());\n        }\n        endTime = System.currentTimeMillis();\n        ret.put(\"Leftist Heap Insertion Time\", endTime - startTime);\n\n        // Deletion test\n        startTime = System.currentTimeMillis();\n        while (!fibonacciHeap.empty()) {\n            fibonacciHeap.deleteMin();\n        }\n        endTime = System.currentTimeMillis();\n        ret.put(\"Fibonacci Heap Deletion Time\", endTime - startTime);\n\n        startTime = System.currentTimeMillis();\n        while (!leftistHeap.isEmpty()) {\n            leftistHeap.extract_min();\n        }\n        endTime = System.currentTimeMillis();\n        ret.put(\"Leftist Heap Deletion Time\", endTime - startTime);\n\n        // Merge test\n        FibonacciHeap fibonacciHeap1 = new FibonacciHeap();\n        FibonacciHeap fibonacciHeap2 = new FibonacciHeap();\n        LeftistHeap leftistHeap1 = new LeftistHeap();\n        LeftistHeap leftistHeap2 = new LeftistHeap();\n\n        // Populate the heaps for merge test\n        for (int i = 0; i < numElements / 2; i++) {\n            fibonacciHeap1.insert(new Random().nextInt());\n            fibonacciHeap2.insert(new Random().nextInt());\n            leftistHeap1.insert(new Random().nextInt());\n            leftistHeap2.insert(new Random().nextInt());\n        }\n\n        // Merge performance test\n        startTime = System.currentTimeMillis();\n        fibonacciHeap1.meld(fibonacciHeap2);\n        endTime = System.currentTimeMillis();\n        ret.put(\"Fibonacci Heap Merge Time\", endTime - startTime);\n\n        startTime = System.currentTimeMillis();\n        leftistHeap1.merge(leftistHeap2);\n        endTime = System.currentTimeMillis();\n        ret.put(\"Leftist Heap Merge Time\", endTime - startTime);\n        return ret;\n    }\n\n    public static void main(String[] args){\n        int numElements = Integer.parseInt(args[0]);\n\n        HeapPerformanceTest t = new HeapPerformanceTest(numElements);\n        HashMap<String, Long> ret = t.test();\n        for (String key : ret.keySet()) {\n            System.out.println(key + \": \" + ret.get(key) + \"ms\");\n        }\n    }\n}\n\n\n// ./heap/LeftistHeap.java\npackage projecteval.heap;\n\nimport java.util.ArrayList;\n\n/*\n * This is a leftist heap that follows the same operations as a\n * binary min heap, but may be unbalanced at times and follows a\n * leftist property, in which the left side is more heavy on the\n * right based on the null-path length (npl) values.\n *\n * Source: https://iq.opengenus.org/leftist-heap/\n *\n */\n\npublic class LeftistHeap {\n    private class Node {\n        private int element, npl;\n        private Node left, right;\n\n        // Node constructor setting the data element and left/right pointers to null\n        private Node(int element) {\n            this.element = element;\n            left = right = null;\n            npl = 0;\n        }\n    }\n\n    private Node root;\n\n    // Constructor\n    public LeftistHeap() {\n        root = null;\n    }\n\n    // Checks if heap is empty\n    public boolean isEmpty() {\n        return root == null;\n    }\n\n    // Resets structure to initial state\n    public void clear() {\n        // We will put head is null\n        root = null;\n    }\n\n    // Merge function that merges the contents of another leftist heap with the\n    // current one\n    public void merge(LeftistHeap h1) {\n        // If the present function is rhs then we ignore the merge\n        root = merge(root, h1.root);\n        h1.root = null;\n    }\n\n    // Function merge with two Nodes a and b\n    public Node merge(Node a, Node b) {\n        if (a == null) return b;\n\n        if (b == null) return a;\n\n        // Violates leftist property, so must do a swap\n        if (a.element > b.element) {\n            Node temp = a;\n            a = b;\n            b = temp;\n        }\n\n        // Now we call the function merge to merge a and b\n        a.right = merge(a.right, b);\n\n        // Violates leftist property so must swap here\n        if (a.left == null) {\n            a.left = a.right;\n            a.right = null;\n        } else {\n            if (a.left.npl < a.right.npl) {\n                Node temp = a.left;\n                a.left = a.right;\n                a.right = temp;\n            }\n            a.npl = a.right.npl + 1;\n        }\n        return a;\n    }\n\n    // Function insert. Uses the merge function to add the data\n    public void insert(int a) {\n        root = merge(new Node(a), root);\n    }\n\n    // Returns and removes the minimum element in the heap\n    public int extract_min() {\n        // If is empty return -1\n        if (isEmpty()) return -1;\n\n        int min = root.element;\n        root = merge(root.left, root.right);\n        return min;\n    }\n\n    // Function returning a list of an in order traversal of the data structure\n    public ArrayList<Integer> in_order() {\n        ArrayList<Integer> lst = new ArrayList<>();\n        in_order_aux(root, lst);\n        return new ArrayList<>(lst);\n    }\n\n    // Auxiliary function for in_order\n    private void in_order_aux(Node n, ArrayList<Integer> lst) {\n        if (n == null) return;\n        in_order_aux(n.left, lst);\n        lst.add(n.element);\n        in_order_aux(n.right, lst);\n    }\n}\n", "num_file": 3, "num_lines": 629, "programming_language": "Java"}
{"class_name": "idcenter", "id": "./MultiFileTest/Java/idcenter.java", "original_code": "// ./idcenter/Base62.java\npackage projecteval.idcenter;\n\n/**\n * A Base62 method\n *\n * @author adyliu (imxylz@gmail.com)\n * @since 1.0\n */\npublic class Base62 {\n\n    private static final String baseDigits = \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n    private static final int BASE = baseDigits.length();\n    private static final char[] digitsChar = baseDigits.toCharArray();\n    private static final int FAST_SIZE = 'z';\n    private static final int[] digitsIndex = new int[FAST_SIZE + 1];\n\n\n    static {\n        for (int i = 0; i < FAST_SIZE; i++) {\n            digitsIndex[i] = -1;\n        }\n        //\n        for (int i = 0; i < BASE; i++) {\n            digitsIndex[digitsChar[i]] = i;\n        }\n    }\n\n    public static long decode(String s) {\n        long result = 0L;\n        long multiplier = 1;\n        for (int pos = s.length() - 1; pos >= 0; pos--) {\n            int index = getIndex(s, pos);\n            result += index * multiplier;\n            multiplier *= BASE;\n        }\n        return result;\n    }\n\n    public static String encode(long number) {\n        if (number < 0) throw new IllegalArgumentException(\"Number(Base62) must be positive: \" + number);\n        if (number == 0) return \"0\";\n        StringBuilder buf = new StringBuilder();\n        while (number != 0) {\n            buf.append(digitsChar[(int) (number % BASE)]);\n            number /= BASE;\n        }\n        return buf.reverse().toString();\n    }\n\n    private static int getIndex(String s, int pos) {\n        char c = s.charAt(pos);\n        if (c > FAST_SIZE) {\n            throw new IllegalArgumentException(\"Unknow character for Base62: \" + s);\n        }\n        int index = digitsIndex[c];\n        if (index == -1) {\n            throw new IllegalArgumentException(\"Unknow character for Base62: \" + s);\n        }\n        return index;\n    }\n}\n\n\n// ./idcenter/IdWorker.java\npackage projecteval.idcenter;\n\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.Random;\n\n/**\n * from https://github.com/twitter/snowflake/blob/master/src/main/scala/com/twitter/service/snowflake/IdWorker.scala\n *\n * @author adyliu (imxylz@gmail.com)\n * @since 1.0\n */\npublic class IdWorker {\n\n    private final long workerId;\n    private final long datacenterId;\n    private final long idepoch;\n\n    private static final long workerIdBits = 5L;\n    private static final long datacenterIdBits = 5L;\n    private static final long maxWorkerId = -1L ^ (-1L << workerIdBits);\n    private static final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);\n\n    private static final long sequenceBits = 12L;\n    private static final long workerIdShift = sequenceBits;\n    private static final long datacenterIdShift = sequenceBits + workerIdBits;\n    private static final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;\n    private static final long sequenceMask = -1L ^ (-1L << sequenceBits);\n\n    private long lastTimestamp = -1L;\n    private long sequence;\n    private static final Random r = new Random();\n\n    public IdWorker() {\n        this(1344322705519L);\n    }\n\n    public IdWorker(long idepoch) {\n        this(r.nextInt((int) maxWorkerId), r.nextInt((int) maxDatacenterId), 0, idepoch);\n    }\n\n    public IdWorker(long workerId, long datacenterId, long sequence) {\n        this(workerId, datacenterId, sequence, 1344322705519L);\n    }\n\n    //\n    public IdWorker(long workerId, long datacenterId, long sequence, long idepoch) {\n        this.workerId = workerId;\n        this.datacenterId = datacenterId;\n        this.sequence = sequence;\n        this.idepoch = idepoch;\n        if (workerId < 0 || workerId > maxWorkerId) {\n            throw new IllegalArgumentException(\"workerId is illegal: \" + workerId);\n        }\n        if (datacenterId < 0 || datacenterId > maxDatacenterId) {\n            throw new IllegalArgumentException(\"datacenterId is illegal: \" + workerId);\n        }\n        if (idepoch >= System.currentTimeMillis()) {\n            throw new IllegalArgumentException(\"idepoch is illegal: \" + idepoch);\n        }\n    }\n\n    public long getDatacenterId() {\n        return datacenterId;\n    }\n\n    public long getWorkerId() {\n        return workerId;\n    }\n\n    public long getTime() {\n        return System.currentTimeMillis();\n    }\n\n    public long getId() {\n        long id = nextId();\n        return id;\n    }\n\n    private synchronized long nextId() {\n        long timestamp = timeGen();\n        if (timestamp < lastTimestamp) {\n            throw new IllegalStateException(\"Clock moved backwards.\");\n        }\n        if (lastTimestamp == timestamp) {\n            sequence = (sequence + 1) & sequenceMask;\n            if (sequence == 0) {\n                timestamp = tilNextMillis(lastTimestamp);\n            }\n        } else {\n            sequence = 0;\n        }\n        lastTimestamp = timestamp;\n        long id = ((timestamp - idepoch) << timestampLeftShift)//\n                | (datacenterId << datacenterIdShift)//\n                | (workerId << workerIdShift)//\n                | sequence;\n        return id;\n    }\n\n    /**\n     * get the timestamp (millis second) of id\n     * @param id the nextId\n     * @return the timestamp of id\n     */\n    public long getIdTimestamp(long id) {\n        return idepoch + (id >> timestampLeftShift);\n    }\n\n    private long tilNextMillis(long lastTimestamp) {\n        long timestamp = timeGen();\n        while (timestamp <= lastTimestamp) {\n            timestamp = timeGen();\n        }\n        return timestamp;\n    }\n\n    private long timeGen() {\n        return System.currentTimeMillis();\n    }\n\n    @Override\n    public String toString() {\n        final StringBuilder sb = new StringBuilder(\"IdWorker{\");\n        sb.append(\"workerId=\").append(workerId);\n        sb.append(\", datacenterId=\").append(datacenterId);\n        sb.append(\", idepoch=\").append(idepoch);\n        sb.append(\", lastTimestamp=\").append(lastTimestamp);\n        sb.append(\", sequence=\").append(sequence);\n        sb.append('}');\n        return sb.toString();\n    }\n}\n\n\n// ./idcenter/Main.java\npackage projecteval.idcenter;\n\nimport java.io.BufferedWriter;\nimport java.io.FileWriter;\nimport java.io.IOException;\n\npublic class Main {\n\n\n    public static void main(String[] args) {\n        if (args.length != 3) {\n            System.err.println(\"Usage: java -jar idcenter.jar <subcommand> <num> <output>\");\n            System.err.println(\"Subcommands\\nidworker: Sequential ID Creation\\nsidworker: Timestamp-based ID Creation\");\n            return;\n        }\n\n        String subcommand = args[0];\n        int num = Integer.parseInt(args[1]);\n        String output = args[2];\n\n        if (subcommand.equals(\"idworker\")) {\n            final long idepo = System.currentTimeMillis() - 3600 * 1000L;\n            IdWorker iw = new IdWorker(1, 1, 0, idepo);\n            IdWorker iw2 = new IdWorker(idepo);\n            try (BufferedWriter writer = new BufferedWriter(new FileWriter(output))) {\n                for (int i = 0; i < num; i++) {\n                    long id = iw.getId();\n                    long idTimeStamp = iw.getIdTimestamp(id);\n                    long id2 = iw2.getId();\n                    long idTimeStamp2 = iw2.getIdTimestamp(id2);\n                    writer.write(\"IdWorker1: \" + id + \", timestamp: \" + idTimeStamp + \"\\n\");\n                    writer.write(\"IdWorker2: \" + id2 + \", timestamp: \" + idTimeStamp2 + \"\\n\");\n                }\n            } catch (IOException e) {\n                e.printStackTrace();\n            }\n        } else if (subcommand.equals(\"sidworker\")) {\n            try (BufferedWriter writer = new BufferedWriter(new FileWriter(output))) {\n                for (int i = 0; i < num; i++) {\n                    long sid = SidWorker.nextSid();\n                    writer.write(\"SidWorker: \" + sid + \"\\n\");\n                }\n            } catch (IOException e) {\n                e.printStackTrace();\n            }\n        } else {\n            System.err.println(\"Usage: java -jar idcenter.jar <subcommand> <num> <output>\");\n            System.err.println(\"Subcommands\\nidworker: Sequential ID Creation\\nsidworker: Timestamp-based ID Creation\");\n        }\n    }\n}\n\n// ./idcenter/SidWorker.java\npackage projecteval.idcenter;\n\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\n\n/**\n * generator of 19 bits number with timestamp\n *\n * @author adyliu (imxylz@gmail.com)\n * @since 2016-06-28\n */\npublic class SidWorker {\n\n    private static long lastTimestamp = -1L;\n    private static int sequence = 0;\n    private static final long MAX_SEQUENCE = 100;\n    private static final SimpleDateFormat format = new SimpleDateFormat(\"yyyyMMddHHmmssSSS\");\n\n    /**\n     * 19 bits number with timestamp (20160628175532000002)\n     *\n     * @return 19 bits number with timestamp\n     */\n    public static synchronized long nextSid() {\n        long now = timeGen();\n        if (now == lastTimestamp) {\n            if (sequence++ > MAX_SEQUENCE) {\n                now = tilNextMillis(lastTimestamp);\n                sequence = 0;\n            }\n        } else {\n            sequence = 0;\n        }\n        lastTimestamp = now;\n        //\n        return 100L * Long.parseLong(format.format(new Date(now))) + sequence;\n    }\n\n    private static long tilNextMillis(long lastTimestamp) {\n        long timestamp = timeGen();\n        while (timestamp <= lastTimestamp) {\n            timestamp = timeGen();\n        }\n        return timestamp;\n    }\n\n    private static long timeGen() {\n        return System.currentTimeMillis();\n    }\n}\n", "num_file": 4, "num_lines": 295, "programming_language": "Java"}
{"class_name": "libraryApp", "id": "./MultiFileTest/Java/libraryApp.java", "original_code": "// ./libraryApp/Book.java\npackage projecteval.libraryApp;\n\npublic class Book {\n\t\n\tprivate int isbn;\n\tprivate String title;\n\tprivate String author;\n\tprivate String genre;\n\tprivate int quantity;\n\tprivate int checkedOut;\n\tprivate int checkedIn;\n\t\n\t//Constructor for book object\n\tpublic Book(int isbn, String title, String author, String genre, int quantity, int checkedOut) {\n\t\tthis.isbn = isbn;\n\t\tthis.title = title;\n\t\tthis.author = author;\n\t\tthis.genre = genre;\n\t\tthis.quantity = quantity;\n\t\tthis.checkedOut = checkedOut;\n\t\tthis.checkedIn = quantity-checkedOut;\n\t}\n\n\tpublic int getCheckedIn() {\n\t\treturn checkedIn;\n\t}\n\n\tpublic void setCheckedIn(int checkedIn) {\n\t\tthis.checkedIn = checkedIn;\n\t}\n\n\tpublic void setIsbn(int isbn) {\n\t\tthis.isbn = isbn;\n\t}\n\n\tpublic void setTitle(String title) {\n\t\tthis.title = title;\n\t}\n\n\tpublic void setAuthor(String author) {\n\t\tthis.author = author;\n\t}\n\n\tpublic void setGenre(String genre) {\n\t\tthis.genre = genre;\n\t}\n\n\tpublic void setQuantity(int quantity) {\n\t\tthis.quantity = quantity;\n\t}\n\n\tpublic void setCheckedOut(int checkedOut) {\n\t\tthis.checkedOut = checkedOut;\n\t}\n\n\t//Getter Methods\n\tpublic int getIsbn() {\n\t\treturn isbn;\n\t}\n\n\tpublic String getTitle() {\n\t\treturn title;\n\t}\n\n\tpublic String getAuthor() {\n\t\treturn author;\n\t}\n\n\tpublic String getGenre() {\n\t\treturn genre;\n\t}\n\n\tpublic int getQuantity() {\n\t\treturn quantity;\n\t}\n\n\tpublic int getCheckedOut() {\n\t\treturn checkedOut;\n\t}\n\n\t\n\t\n\t\n}\n\n \n\n\n// ./libraryApp/BookRepository.java\npackage projecteval.libraryApp;\n\nimport java.util.ArrayList;\n\npublic class BookRepository {\n\t\n\tprivate ArrayList<Book> books = new ArrayList<>();\n\tprivate int booksFound = 0;\n\t\n\t//Constructor to initialize books\n\tpublic BookRepository(){\n\t\tbooks.add(new Book(253910,\"Pride and Prejudice C\", \"Jane Austen\", \"Love\",10,7));\n\t\tbooks.add(new Book(391520,\"Programming in ANSI C\", \"E. Balagurusamy\", \"Educational\",15,10));\n\t\tbooks.add(new Book(715332,\"Shrimad Bhagavad Gita\", \"Krishna Dvaipayana\", \"Motivational\",20,18));\n\t\tbooks.add(new Book(935141,\"Java: The Complete Reference\", \"Herbert Schildt\", \"Educational\",12,9));\n\t\tbooks.add(new Book(459901,\"It\", \"Stephan King\", \"Horror\",7,5));\n\t\tbooks.add(new Book(855141,\"Disneyland\", \"Mickey & Minnie\", \"Love\",10,3));\n\t}\n\t\n\t\n\t//Searching books by Title Keyword\n\tpublic void searchByTitle(String title) {\n\t\tbooksFound = 0;\n\t\tfor(Book book : books) {\n\t\t\tString bookTitle = book.getTitle();\n\t\t\tif(bookTitle.toLowerCase().contains(title.toLowerCase())) {\n\t\t\t\tbookDetails(book);\n\t\t\t\tbooksFound++;\n\t\t\t}\n\t\t}\n\t\tSystem.out.printf(\"\\n%d Book%s Found.\\n\",booksFound,booksFound>1?\"s\":\"\");\n\t\treturn;\n\t}\n\t\n\n\t//Searching books by ISBN Number\n\tpublic void searchByISBN(int isbn) {\n\t\tbooksFound = 0;\n\t\tfor(Book book : books) {\n\t\t\tif(book.getIsbn()==isbn) {\n\t\t\t\tbookDetails(book);\n\t\t\t\tbooksFound++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\t\n\t\t}\n\t\tSystem.out.printf(\"\\n%d Book%s Found.\\n\",booksFound,booksFound>1?\"s\":\"\");\n\t\treturn;\n\t}\n\t\n\t\n\t//Searching books by Genre\n\tpublic boolean searchByGenre(String genre){\n\t\tbooksFound = 0;\n\t\tfor(Book book : books) {\n\t\t\tString bookGenre = book.getGenre();\n\t\t\tif(bookGenre.toLowerCase().equals(genre.toLowerCase())) {\n\t\t\t\tbookDetails(book);\n\t\t\t\tbooksFound++;\n\t\t\t}\n\t\t}\n\t\tSystem.out.printf(\"\\n%d Book%s Found.\\n\",booksFound,booksFound>1?\"s\":\"\");\n\t\tif(booksFound>0)\n\t\t\treturn true;\n\t\telse \n\t\t\treturn false;\n\t\t\t\n\t}\n\t\n\t\n\t// Display Book Details\n\tpublic void bookDetails(Book book) {\n\t\tSystem.out.println(\"\\n+> Book details: \\n\");\n\t\tSystem.out.println(\"\\tTitle: \"+book.getTitle()+\"\\n\\tAuthor: \"+ book.getAuthor()+\"\\n\\tGenre: \"+book.getGenre()+\"\\n\\tISBN: \"+book.getIsbn()+\"\\n\\tQuantity: \"+book.getQuantity()+\"\\n\\tChecked Out: \"+String.valueOf(book.getCheckedOut())+\"\\n\\tAvailable: \"+String.valueOf(book.getQuantity()-book.getCheckedOut()));\n\t}\n\t\n\t\n\t//Searching for ISBN number for checkIn and checkOut\n\tpublic int searchISBN(int isbn) {\n\t\tfor(Book book:books)\n\t\t\tif(book.getIsbn()==isbn)\n\t\t\t\treturn 1;\n\t\treturn 0;\n\t}\n\t\n\t\n\t//withdrawing book\n\tpublic boolean getBook(int isbn) {\n\t\tfor(Book book: books) {\n\t\t\tif(book.getIsbn()==isbn) {\n\t\t\t\tif((book.getQuantity()-book.getCheckedOut())>0) {\n\t\t\t\t\tbook.setCheckedOut(book.getCheckedOut()+1);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\t\n\t//submitting book\n\tpublic boolean submitBook(int isbn) {\n\t\tfor(Book book: books) {\n\t\t\tif(book.getQuantity()>book.getCheckedIn()) {\n\t\t\t\tbook.setCheckedOut(book.getCheckedOut()-1);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\t\n\t//Showing status of book\n\tpublic void bookStatus(int isbn) {\n\t\tfor(Book book: books) {\n\t\t\tif(book.getIsbn()==isbn) {\n\t\t\t\tbookDetails(book);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t\n}\n\n\n// ./libraryApp/LibraryApp.java\npackage projecteval.libraryApp;\n\npublic class LibraryApp {\n\t\n\tBookRepository repo = new BookRepository();\n\t\n\tpublic void findByTitle(String title) {\n\t\trepo.searchByTitle(title);\n\t\treturn;\n\t}\n\tpublic void findByISBN(int isbn) {\n\t\trepo.searchByISBN(isbn);\n\t\treturn;\n\t}\n\tpublic boolean findByGenre(String genre) {\n\t\tif(repo.searchByGenre(genre))\n\t\t\treturn true;\n\t\telse \n\t\t\treturn false;\n\t}\n\t\n\t\n\tpublic int findISBN(int isbn) {\n\t\treturn repo.searchISBN(isbn);\n\t}\n\t\n\tpublic boolean withdrawBook(int isbn) {\n\t\treturn repo.getBook(isbn);\n\t}\n\t\n\tpublic boolean depositBook(int isbn) {\n\t\treturn repo.submitBook(isbn);\n\t}\n\n\tpublic void getStatus(int isbn) {\n\t\trepo.bookStatus(isbn);\n\t}\n}\n\n\n// ./libraryApp/Main.java\npackage projecteval.libraryApp;\n\nimport java.util.Scanner;\n\npublic class  Main{\n\tstatic Scanner scan = new Scanner(System.in);\n    static LibraryApp app = new LibraryApp();\n\n\t\n\tpublic static void main(String[] args) {\n       \n\t\tint userChoice=0;\n        System.out.println(\"-----Welcome to the Library!-----\\n\");\n        do{\n        \tSystem.out.println(\"\\n-----------------------------------\");\n        \tSystem.out.println(\"1. Search book by Title keyword.\");\n            System.out.println(\"2. Search book by ISBN number.\");\n            System.out.println(\"3. Search book by Genre.\");\n    \t\tSystem.out.println(\"4. Book Check In\");\n    \t\tSystem.out.println(\"5. Book Check Out\");\n    \t\tSystem.out.println(\"6. Exit from the library.\");\n    \t\tSystem.out.println(\"-----------------------------------\");\n    \t\tSystem.out.print(\"\\nChoose any option: \");\n            \n            userChoice = scan.nextInt();\n            scan.nextLine();\n            \n            switch(userChoice){\n            \tcase 1:\n            \t\t\tSystem.out.print(\"Enter the Title of Book: \");\n            \t\t\tapp.findByTitle(scan.nextLine());\n            \t\t\tbreak;\n            \tcase 2: \n            \t\t\tSystem.out.println(\"Enter ISBN number: \");\n            \t\t\tapp.findByISBN(scan.nextInt());\n            \t\t\tbreak;\n            \tcase 3:\n            \t\t\tSystem.out.println(\"Enter Genre: \");\n            \t\t\tapp.findByGenre(scan.nextLine());\n            \t\t\tbreak;\n            \tcase 4:\n            \t\t\tcheckIn();\n            \t\t\tbreak;\n            \tcase 5:\n            \t\t\tcheckOut();\n            \t\t\tbreak;\n            \tcase 6:\n            \t\t\tSystem.out.println(\"\\nThanks for visiting. \\nSee you again.\");\n            \t\t\tbreak;\n            \tdefault:\n            \t\t\tSystem.out.println(\"\\nInvalid Choice!\");\t\n            }    \n        }while(userChoice!=6);\n        \n    }\n    \n\t\n\t\t//Checking book In\n    \tprivate static void checkIn() {\n    \t\tSystem.out.println(\"Enter Book's ISBN number : \");\n    \t\tint isbnNum = scan.nextInt();\n    \t\tgetStatus(isbnNum);\n    \t\tint bookAvailable = app.findISBN(isbnNum);\n    \t\tif(bookAvailable==1) {\n    \t\t\tSystem.out.println(isbnNum);\n    \t\t\tapp.withdrawBook(isbnNum);\n    \t\t\tSystem.out.println(\"Book CheckIn successful.\");\n    \t\t\tgetStatus(isbnNum);\n    \t\t}\n    \t\telse\n    \t\t\tSystem.out.printf(\"Book with %d ISBN number not Found in inventory.\",isbnNum);\n    \t}\n    \t\n    \t\n    \t//Checking book Out\n    \tprivate static void checkOut() {\n    \t\tSystem.out.println(\"\\nEnter Book's ISBN number : \");\n    \t\tint isbnNum = scan.nextInt();\n    \t\tint bookAvailable = app.findISBN(isbnNum);\n    \t\tif(bookAvailable==1) {\n    \t\t\tif(app.depositBook(isbnNum))\n    \t\t\tSystem.out.println(\"Book CheckOut successful.\");\n    \t\t\telse\n    \t\t\t\tSystem.out.println(\"No Space for more Books.\");\n    \t\t}\n    \t\telse\n    \t\t\tSystem.out.printf(\"Book with %d ISBN number not Found in inventory.\",isbnNum);\n    \t}\n    \t\n    \tprivate static void getStatus(int isbn) {\n    \t\tapp.getStatus(isbn);\n    \t}\n}", "num_file": 4, "num_lines": 340, "programming_language": "Java"}
{"class_name": "libraryManagement", "id": "./MultiFileTest/Java/libraryManagement.java", "original_code": "// ./libraryManagement/AddBookMenu.java\npackage projecteval.libraryManagement;\n\nimport java.sql.Connection;\nimport java.sql.Statement;\nimport java.util.Scanner;\n\n/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\n/**\n *\n * @author testuser\n */\npublic class AddBookMenu {\n\n    public static void addBookMenu() {\n        System.out.println(\"Reached the add book menu\");\n        Book b = new Book();\n        Scanner sc = new Scanner(System.in);\n        int addStatus = 0;\n\n        while (addStatus == 0) {\n            try {\n                System.out.println(\"Enter the isbn code\");\n                b.setIsbnCode(sc.nextLine().toString());\n                System.out.println(\"Enter the book name\");\n                b.setBookName(sc.nextLine().toString());\n                System.out.println(\"Enter the book desc\");\n                b.setBookDesc(sc.nextLine().toString());\n                System.out.println(\"Enter the author name\");\n                b.setAuthorName(sc.nextLine().toString());\n                System.out.println(\"Enter the subject \");\n                b.setSubjectName(sc.nextLine().toString());\n                System.out.println(\"Enter the units available\");\n                b.setUnitsAvailable(Integer.parseInt(sc.nextLine().toString()));\n\n                addBook(b);\n                addStatus = 1;\n                \n            } catch (Exception e) {\n                addStatus=0;\n            }\n\n        }\n\n    }\n\n    public static void addBook(Book b) { \n        System.out.println(\"Reached inside addBook for book \"+b.getIsbnCode());\n        Connection conn = LibUtil.getConnection();\n        try {\n            Statement stmt = conn.createStatement();\n            int k = stmt.executeUpdate(\"insert into books values ('\"+b.getIsbnCode()+\"','\"+b.getBookName()+\"','\"+b.getBookDesc()+\"',\"\n                    + \"'\"+b.getAuthorName()+\"','\"+b.getSubjectName()+\"',\"+b.getUnitsAvailable()+\")\");\n            if(k>0){\n                System.out.println(\"Added Book successfully\");\n                conn.commit();\n            }else{\n                conn.rollback();\n            }\n            conn.close();\n        } catch (Exception e) {\n        }\n        \n        \n\n    }\n\n}\n\n\n// ./libraryManagement/AddMemberMenu.java\npackage projecteval.libraryManagement;\n\nimport java.sql.Connection;\nimport java.sql.Statement;\nimport java.util.Scanner;\n\n/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\n/**\n *\n * @author testuser\n */\npublic class AddMemberMenu {\n\n    public static void addMemberMenu() {\n        System.out.println(\"Reached the add member menu\");\n        Member m = new Member();\n        Scanner sc = new Scanner(System.in);\n        int addStatus = 0;\n\n        while (addStatus == 0) {\n            try {\n                System.out.println(\"Enter the member id \");\n                m.setMemberId(Integer.parseInt(sc.nextLine().toString()));\n                System.out.println(\"Enter the member name\");\n                m.setMemberName(sc.nextLine().toString());\n                \n                addMember(m);\n                addStatus = 1;\n                \n            } catch (Exception e) {\n                addStatus=0;\n            }\n\n        }\n\n    }\n\n    public static void addMember(Member m) { \n        System.out.println(\"Reached inside add member for member \"+m.getMemberId());\n        Connection conn = LibUtil.getConnection();\n        try {\n            Statement stmt = conn.createStatement();\n            int k = stmt.executeUpdate(\"insert into members values (\"+m.getMemberId()+\",'\"+m.getMemberName()+\"',sysdate)\");\n            if(k>0){\n                System.out.println(\"Added Member successfully\");\n                conn.commit();\n            }else{\n                conn.rollback();\n            }\n            conn.close();\n        } catch (Exception e) {\n        }\n        \n        \n\n    }\n\n}\n\n\n// ./libraryManagement/Book.java\npackage projecteval.libraryManagement;\n\n/**\n *\n * @author testuser\n */\npublic class Book {\n    private String isbnCode;\n    private String bookName;\n    private String bookDesc;\n    private String authorName;\n    private String subjectName;\n    private Integer unitsAvailable;\n    \n    public Book(){\n        \n    }\n    public Book(String isbnCode, String bookName, String bookDesc, String authorName, String subjectName, Integer unitsAvailable) {\n        this.isbnCode = isbnCode;\n        this.bookName = bookName;\n        this.bookDesc = bookDesc;\n        this.authorName = authorName;\n        this.subjectName = subjectName;\n        this.unitsAvailable = unitsAvailable;\n    }\n\n    public Integer getUnitsAvailable() {\n        return unitsAvailable;\n    }\n\n    public void setUnitsAvailable(Integer unitsAvailable) {\n        this.unitsAvailable = unitsAvailable;\n    }\n\n    public String getIsbnCode() {\n        return isbnCode;\n    }\n\n    public void setIsbnCode(String isbnCode) {\n        this.isbnCode = isbnCode;\n    }\n\n    public String getBookName() {\n        return bookName;\n    }\n\n    public void setBookName(String bookName) {\n        this.bookName = bookName;\n    }\n\n    public String getBookDesc() {\n        return bookDesc;\n    }\n\n    public void setBookDesc(String bookDesc) {\n        this.bookDesc = bookDesc;\n    }\n\n    public String getAuthorName() {\n        return authorName;\n    }\n\n    public void setAuthorName(String authorName) {\n        this.authorName = authorName;\n    }\n\n    public String getSubjectName() {\n        return subjectName;\n    }\n\n    public void setSubjectName(String subjectName) {\n        this.subjectName = subjectName;\n    }\n\n\n}\n\n\n// ./libraryManagement/LibFunctions.java\npackage projecteval.libraryManagement;\n\nimport java.sql.Connection;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\nimport java.util.Scanner;\n\npublic class LibFunctions {\n\n    public static void callIssueMenu() {\n        System.out.println(\"Reached inside issue book menu\");\n        Member m = new Member();\n        Book b = new Book();\n        Scanner sc = new Scanner(System.in);\n        int addStatus = 0;\n\n        while (addStatus == 0) {\n            try {\n                System.out.println(\"Enter the member id \");\n                m.setMemberId(Integer.parseInt(sc.nextLine().toString()));\n                System.out.println(\"Enter the isbn code \");\n                b.setIsbnCode(sc.nextLine().toString());\n                issueBook(m, b);\n                addStatus = 1;\n\n            } catch (Exception e) {\n                addStatus = 0;\n            }\n\n        }\n\n    }\n    \n\n    public static void issueBook(Member m, Book b) {\n        Connection conn = LibUtil.getConnection();\n        try {\n            Statement stmt = conn.createStatement();\n            ResultSet rs = null;\n            String qry = \"select m.member_id, b.isbn_code, mbr.rec_id from members m,books b,member_book_record mbr\\n\"\n                    + \"where m.member_id= \" + m.getMemberId() + \" \\n\"\n                    + \"and b.isbn_code = '\" + b.getIsbnCode() + \"' \\n\"\n                    + \"and m.member_id=mbr.member_id\\n\"\n                    + \"and b.isbn_code=mbr.isbn_code and mbr.dor is null \";\n            rs=stmt.executeQuery(qry);\n            if (rs.next()) {\n                System.out.println(\"The book is already issued and cannot be issued again\");\n            } else {\n                int k = stmt.executeUpdate(\"insert into member_book_record values(lib_seq.nextval,\" + m.getMemberId() + \",'\" + b.getIsbnCode() + \"',sysdate,null)\");\n                if(k > 0){\n                    k = stmt.executeUpdate(\"update books set units_available= (units_available-1) where isbn_code = '\"+ b.getIsbnCode() +\"' \"); \n                    conn.commit();\n                    System.out.println(\"The book is issued successfully\");\n                }else{\n                    conn.rollback();\n                }\n\n            }\n            conn.close();\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n    \n    public static void callReturnMenu() {\n        System.out.println(\"Reached inside return book menu\");\n        Member m = new Member();\n        Book b = new Book();\n        Scanner sc = new Scanner(System.in);\n        int addStatus = 0;\n\n        while (addStatus == 0) {\n            try {\n                System.out.println(\"Enter the member id \");\n                m.setMemberId(Integer.parseInt(sc.nextLine().toString()));\n                System.out.println(\"Enter the isbn code \");\n                b.setIsbnCode(sc.nextLine().toString());\n                returnBook(m, b);\n                addStatus = 1;\n\n            } catch (Exception e) {\n                addStatus = 0;\n            }\n\n        }\n\n    }\n    \n    public static void returnBook(Member m, Book b) {\n        Connection conn = LibUtil.getConnection();\n        try {\n            Statement stmt = conn.createStatement();\n            ResultSet rs = null;\n            String qry = \"select m.member_id, b.isbn_code, mbr.rec_id from members m,books b,member_book_record mbr\\n\"\n                    + \"where m.member_id= \" + m.getMemberId() + \" \\n\"\n                    + \"and b.isbn_code = '\" + b.getIsbnCode() + \"' \\n\"\n                    + \"and m.member_id=mbr.member_id\\n\"\n                    + \"and b.isbn_code=mbr.isbn_code and mbr.dor is null \";\n            rs=stmt.executeQuery(qry);\n            if (rs.next()) {\n                Integer recId= rs.getInt(3);\n                System.out.println(\"The book is already issued and starting the process to return \");\n                int k = stmt.executeUpdate(\"update books set units_available= (units_available+1) where isbn_code = '\"+ b.getIsbnCode() +\"' \"); \n                if(k > 0){\n                    k = stmt.executeUpdate(\"update member_book_record set dor= sysdate where rec_id = \"+ recId +\" \"); \n                    conn.commit();\n                    System.out.println(\"The book is returned successfully\");\n                }else{\n                    conn.rollback();\n                }\n\n            } else{\n                System.out.println(\"This book is not issued for the user\");\n            }\n            conn.close();\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n    \n        \n        \n}\n\n\n// ./libraryManagement/LibUtil.java\npackage projecteval.libraryManagement;\n\nimport java.io.FileInputStream;\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.util.Properties;\n\n/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\n\n/**\n *\n * @author testuser\n */\npublic class LibUtil {\n    public static Connection getConnection() {\n        Connection conn = null;\n        try {\n            Properties prop = new Properties();\n            FileInputStream in = new FileInputStream(\"src/DBProperties\");\n            prop.load(in);\n            \n            String driverName= prop.getProperty(\"DBDriver\");\n            Class.forName(driverName);\n            \n            String dbName,user,password;\n            dbName= prop.getProperty(\"DBName\");\n            user = prop.getProperty(\"User\");\n            password= prop.getProperty(\"Password\");\n            \n            conn= DriverManager.getConnection(dbName, user, password);\n            return conn;\n        } catch (Exception e) {\n        }\n        return conn;\n        \n    }\n}\n\n\n// ./libraryManagement/Member.java\npackage projecteval.libraryManagement;\n\nimport java.sql.Date;\n\n\n/**\n *\n * @author testuser\n */\npublic class Member {\n\n    private Integer memberId;\n    private String memberName;\n    private Date dateOfJoining;\n\n    public Member() {\n\n    }\n\n    public Member(Integer memberId, String memberName, Date dateOfJoining) {\n        this.memberId = memberId;\n        this.memberName = memberName;\n        this.dateOfJoining = dateOfJoining;\n    }\n\n    public Date getDateOfJoining() {\n        return dateOfJoining;\n    }\n\n    public void setDateOfJoining(Date dateOfJoining) {\n        this.dateOfJoining = dateOfJoining;\n    }\n\n    public Integer getMemberId() {\n        return memberId;\n    }\n\n    public void setMemberId(Integer memberId) {\n        this.memberId = memberId;\n    }\n\n    public String getMemberName() {\n        return memberName;\n    }\n\n    public void setMemberName(String memberName) {\n        this.memberName = memberName;\n    }\n\n}\n\n\n// ./libraryManagement/UserMenu.java\npackage projecteval.libraryManagement;\n\nimport java.util.Scanner;\n\n\n/**\n *\n * @author testuser\n */\npublic class UserMenu {\n    public static void main(String[] args) {\n        String input=\"\";\n        Scanner sc = new Scanner(System.in);\n        \n        while(input != \"5\"){\n            System.out.println(\"---------------------------------------------------------\");\n            System.out.println(\"---------------------------------------------------------\");\n            System.out.println(\"---------------------------------------------------------\");\n\n            System.out.println(\"Select the following options\");\n            System.out.println(\"Enter 1 for adding a book\");\n            System.out.println(\"Enter 2 for adding a member\");\n            System.out.println(\"Enter 3 for issuing a book \");\n            System.out.println(\"Enter 4 for returning  a book \");\n            System.out.println(\"Enter 5 to exit\");\n            input = processUserInput(sc.nextLine().toString());\n            \n        }\n    }\n    public static String processUserInput(String in) {\n        String retVal=\"5\";\n        switch(in){\n            case \"1\":\n                System.out.println(\"---------------------------------------------------------\");\n                System.out.println(\"You have selected option 1 to add a book\");\n                AddBookMenu.addBookMenu();\n                return \"1\";\n            case \"2\":\n                System.out.println(\"---------------------------------------------------------\");\n                System.out.println(\"You have selected option 2 to add a member\");\n                AddMemberMenu.addMemberMenu();\n                return \"2\";\n            case \"3\":\n                System.out.println(\"---------------------------------------------------------\");\n                System.out.println(\"You have selected option 3 to issue a book\");\n                LibFunctions.callIssueMenu();\n                return \"3\";\n            case \"4\":\n                System.out.println(\"---------------------------------------------------------\");\n                System.out.println(\"You have selected option 4 to return a book\");\n                LibFunctions.callReturnMenu();\n                return \"4\";\n            default:\n                System.out.println(\"---------------------------------------------------------\");\n                System.out.println(\"Thanks for working on this!!\");\n                return \"5\";\n        }\n        \n    }\n}\n", "num_file": 7, "num_lines": 483, "programming_language": "Java"}
{"class_name": "logrequestresponseundertow", "id": "./MultiFileTest/Java/logrequestresponseundertow.java", "original_code": "// ./logrequestresponseundertow/Application.java\npackage projecteval.logrequestresponseundertow;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;\nimport org.springframework.context.annotation.Bean;\n\nimport io.undertow.server.handlers.RequestDumpingHandler;\nimport lombok.extern.log4j.Log4j2;\n\n@SpringBootApplication\n@Log4j2\npublic class Application {\n    \n    public static void main(String[] args) {\n        SpringApplication.run(Application.class, args);\n    }\n    \n    @Bean\n    public UndertowServletWebServerFactory undertowServletWebServerFactory() {\n        UndertowServletWebServerFactory factory = new UndertowServletWebServerFactory();\n        factory.addDeploymentInfoCustomizers(deploymentInfo ->\n                deploymentInfo.addInitialHandlerChainWrapper(handler -> {\n            return new RequestDumpingHandler(handler);\n        }));\n        \n        return factory;\n    }\n    \n    \n    @Bean\n    public UndertowServletWebServerFactory UndertowServletWebServerFactory() {\n        UndertowServletWebServerFactory UndertowServletWebServerFactory = new UndertowServletWebServerFactory();\n\n        UndertowServletWebServerFactory.addDeploymentInfoCustomizers(deploymentInfo -> deploymentInfo.addInitialHandlerChainWrapper(handler -> {\n            return new RequestDumpingHandler(handler);\n        }));\n\n        return UndertowServletWebServerFactory;\n    }\n}\n\n// ./logrequestresponseundertow/Song.java\npackage projecteval.logrequestresponseundertow;\n\nimport lombok.*;\n\n@Getter\n@Setter\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class Song {\n\n    private Long id;\n    private String name;\n    private String author;\n}\n\n\n// ./logrequestresponseundertow/SongController.java\npackage projecteval.logrequestresponseundertow;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Random;\n\nimport org.springframework.web.bind.annotation.*;\n\n@RestController\npublic class SongController {\n    \n    @PostMapping(\"/songs\")\n    public Song createSong(@RequestBody Song song) {\n        song.setId(new Random().nextLong());\n        \n        return song;\n    }\n    \n    @GetMapping(\"/songs\")\n    public List<Song> getSongs() {\n        List<Song> songs = new ArrayList<>();\n\n        songs.add(Song.builder().id(1L).name(\"name1\").author(\"author2\").build());\n        songs.add(Song.builder().id(2L).name(\"name2\").author(\"author2\").build());\n\n        return songs;\n    }\n\n}\n", "num_file": 3, "num_lines": 85, "programming_language": "Java"}
{"class_name": "passwordGenerator", "id": "./MultiFileTest/Java/passwordGenerator.java", "original_code": "// ./passwordGenerator/Alphabet.java\npackage projecteval.passwordGenerator;\n\n\npublic class Alphabet {\n\t\n\tpublic static final String UPPERCASE_LETTERS = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\tpublic static final String LOWERCASE_LETTERS = \"abcdefghijklmnopqrstuvwxyz\";\n\tpublic static final String NUMBERS = \"1234567890\";\n\tpublic static final String SYMBOLS = \"!@#$%^&*()-_=+\\\\/~?\";\n\t\n\tprivate final StringBuilder pool;\n\n\n\tpublic Alphabet(boolean uppercaseIncluded, boolean lowercaseIncluded, boolean numbersIncluded, boolean specialCharactersIncluded) {\n\t\t\n\t\tpool = new StringBuilder();\n\t\t\n\t\tif (uppercaseIncluded) pool.append(UPPERCASE_LETTERS);\n\t\t\n\t\tif (lowercaseIncluded) pool.append(LOWERCASE_LETTERS);\n\t\t\n\t\tif (numbersIncluded) pool.append(NUMBERS);\n\t\t\n\t\tif (specialCharactersIncluded) pool.append(SYMBOLS);\n\t\t\n\t}\n\t\n\tpublic String getAlphabet() {\n\t\treturn pool.toString();\n\t}\n}\n\n\n// ./passwordGenerator/Generator.java\npackage projecteval.passwordGenerator;\n\nimport java.util.Objects;\nimport java.util.Scanner;\n\npublic class Generator {\n    Alphabet alphabet;\n    public static Scanner keyboard;\n\n    public Generator(Scanner scanner) {\n        keyboard = scanner;\n    }\n\n    public Generator(boolean IncludeUpper, boolean IncludeLower, boolean IncludeNum, boolean IncludeSym) {\n        alphabet = new Alphabet(IncludeUpper, IncludeLower, IncludeNum, IncludeSym);\n    }\n\n    public void mainLoop() {\n        System.out.println(\"Welcome to Ziz Password Services :)\");\n        printMenu();\n\n        String userOption = \"-1\";\n\n        while (!userOption.equals(\"4\")) {\n\n            userOption = keyboard.next();\n\n            switch (userOption) {\n                case \"1\": {\n                    requestPassword();\n                    printMenu();\n                }\n                case \"2\": {\n                    checkPassword();\n                    printMenu();\n                }\n                case \"3\": {\n                    printUsefulInfo();\n                    printMenu();\n                }\n                case \"4\": printQuitMessage();\n                default: {\n                    System.out.println();\n                    System.out.println(\"Kindly select one of the available commands\");\n                    printMenu();\n                }\n            }\n        }\n    }\n\n    private Password GeneratePassword(int length) {\n        final StringBuilder pass = new StringBuilder(\"\");\n\n        final int alphabetLength = alphabet.getAlphabet().length();\n\n        int max = alphabetLength - 1;\n        int min = 0;\n        int range = max - min + 1;\n\n        for (int i = 0; i < length; i++) {\n            int index = (int) (Math.random() * range) + min;\n            pass.append(alphabet.getAlphabet().charAt(index));\n        }\n\n        return new Password(pass.toString());\n    }\n\n    private void printUsefulInfo() {\n        System.out.println();\n        System.out.println(\"Use a minimum password length of 8 or more characters if permitted\");\n        System.out.println(\"Include lowercase and uppercase alphabetic characters, numbers and symbols if permitted\");\n        System.out.println(\"Generate passwords randomly where feasible\");\n        System.out.println(\"Avoid using the same password twice (e.g., across multiple user accounts and/or software systems)\");\n        System.out.println(\"Avoid character repetition, keyboard patterns, dictionary words, letter or number sequences,\" +\n                \"\\nusernames, relative or pet names, romantic links (current or past) \" +\n                \"and biographical information (e.g., ID numbers, ancestors' names or dates).\");\n        System.out.println(\"Avoid using information that the user's colleagues and/or \" +\n                \"acquaintances might know to be associated with the user\");\n        System.out.println(\"Do not use passwords which consist wholly of any simple combination of the aforementioned weak components\");\n    }\n\n    private void requestPassword() {\n        boolean IncludeUpper = false;\n        boolean IncludeLower = false;\n        boolean IncludeNum = false;\n        boolean IncludeSym = false;\n\n        boolean correctParams = false;\n\n        System.out.println();\n        System.out.println(\"Hello, welcome to the Password Generator :) answer\"\n                + \" the following questions by Yes or No \\n\");\n\n        do {\n            System.out.println(\"Do you want Lowercase letters \\\"abcd...\\\" to be used? \");\n            String input = keyboard.nextLine();\n\n            if (isInclude(input)) IncludeLower = true;\n\n            System.out.println(\"Do you want Uppercase letters \\\"ABCD...\\\" to be used? \");\n            input = keyboard.nextLine();\n\n            if (isInclude(input)) IncludeUpper = true;\n\n            System.out.println(\"Do you want Numbers \\\"1234...\\\" to be used? \");\n            input = keyboard.nextLine();\n\n            if (isInclude(input)) IncludeNum = true;\n\n            System.out.println(\"Do you want Symbols \\\"!@#$...\\\" to be used? \");\n            input = keyboard.nextLine();\n\n            if (isInclude(input)) IncludeSym = true;\n\n            //No Pool Selected\n            if (!IncludeUpper && !IncludeLower && !IncludeNum && !IncludeSym) {\n                System.out.println(\"You have selected no characters to generate your \" +\n                        \"password at least one of your answers should be Yes\");\n                correctParams = true;\n            }\n\n            System.out.println(\"Great! Now enter the length of the password\");\n            int length = keyboard.nextInt();\n\n            final Generator generator = new Generator(IncludeUpper, IncludeLower, IncludeNum, IncludeSym);\n            final Password password = generator.GeneratePassword(length);\n\n            System.err.println(\"Your generated password -> \" + password);\n\n        } while (correctParams);\n    }\n\n    private boolean isInclude(String Input) {\n        if (Input.equalsIgnoreCase(\"yes\")) {\n            return true;\n        } else {\n            if (!Input.equalsIgnoreCase(\"no\")) {\n                PasswordRequestError();\n            }\n            return false;\n        }\n    }\n\n    private void PasswordRequestError() {\n        System.out.println(\"You have entered something incorrect let's go over it again \\n\");\n    }\n\n    private void checkPassword() {\n        String input;\n        final Scanner in = new Scanner(System.in);\n\n        System.out.print(\"\\nEnter your password:\");\n        input = in.nextLine();\n\n        final Password p = new Password(input);\n\n        System.out.println(p.calculateScore());\n\n        in.close();\n    }\n\n    private void printMenu() {\n        System.out.println();\n        System.out.println(\"Enter 1 - Password Generator\");\n        System.out.println(\"Enter 2 - Password Strength Check\");\n        System.out.println(\"Enter 3 - Useful Information\");\n        System.out.println(\"Enter 4 - Quit\");\n        System.out.print(\"Choice:\");\n    }\n\n    private void printQuitMessage() {\n        System.out.println(\"Closing the program bye bye!\");\n    }\n}\n\n\n// ./passwordGenerator/GeneratorTest.java\npackage projecteval.passwordGenerator;\n\nimport static org.junit.jupiter.api.Assertions.*;\n\nimport org.junit.jupiter.api.Test;\n\nclass GeneratorTest {\n\t\n\tprivate final Password password= new Password(\"Secret\");\n\tprivate final Alphabet firstAlphabet = new Alphabet(true,false,false,false);\n\tprivate final Alphabet secondAlphabet = new Alphabet(false,true,true,true);\n\tprivate final Generator generator = new Generator(true,false,false,false);\n//\tprivate final Password generatedPassword = generator.GeneratePassword(4);\n\t\n\t@Test\n\tvoid test1() {\n\t\tassertEquals(\"Secret\", password.toString());\n\t}\n\n\t@Test\n\tvoid test2() {\n\t\tassertEquals(firstAlphabet.getAlphabet(), Alphabet.UPPERCASE_LETTERS);\n\t}\n\n\t@Test\n\tvoid test3() {\n\t\tassertEquals(secondAlphabet.getAlphabet(), Alphabet.LOWERCASE_LETTERS + Alphabet.NUMBERS + Alphabet.SYMBOLS);\n\t}\n\t\n\t@Test\n\tvoid test4() {\n\t\tassertEquals(generator.alphabet.getAlphabet(), Alphabet.UPPERCASE_LETTERS);\n\t}\n\t\n\t@Test\n\tvoid test5() {\n\t\tassertEquals(generator.alphabet.getAlphabet().length(), 26);\n\t}\n\n}\n\n\n// ./passwordGenerator/Main.java\npackage projecteval.passwordGenerator;\n\nimport java.util.Scanner;\n\npublic class Main {\n\n    public static final Scanner keyboard = new Scanner(System.in);\n\n    public static void main(String[] args) {\n        Generator generator = new Generator(keyboard);\n        generator.mainLoop();\n        keyboard.close();\n    }\n}\n\n\n// ./passwordGenerator/Password.java\npackage projecteval.passwordGenerator;\n\npublic class Password {\n    String Value;\n    int Length;\n\n    public Password(String s) {\n        Value = s;\n        Length = s.length();\n    }\n\n    public int CharType(char C) {\n        int val;\n\n        // Char is Uppercase Letter\n        if ((int) C >= 65 && (int) C <= 90)\n            val = 1;\n\n        // Char is Lowercase Letter\n        else if ((int) C >= 97 && (int) C <= 122) {\n            val = 2;\n        }\n\n        // Char is Digit\n        else if ((int) C >= 60 && (int) C <= 71) {\n            val = 3;\n        }\n\n        // Char is Symbol\n        else {\n            val = 4;\n        }\n\n        return val;\n    }\n\n    public int PasswordStrength() {\n        String s = this.Value;\n        boolean UsedUpper = false;\n        boolean UsedLower = false;\n        boolean UsedNum = false;\n        boolean UsedSym = false;\n        int type;\n        int Score = 0;\n\n        for (int i = 0; i < s.length(); i++) {\n            char c = s.charAt(i);\n            type = CharType(c);\n\n            if (type == 1) UsedUpper = true;\n            if (type == 2) UsedLower = true;\n            if (type == 3) UsedNum = true;\n            if (type == 4) UsedSym = true;\n        }\n\n        if (UsedUpper) Score += 1;\n        if (UsedLower) Score += 1;\n        if (UsedNum) Score += 1;\n        if (UsedSym) Score += 1;\n\n        if (s.length() >= 8) Score += 1;\n        if (s.length() >= 16) Score += 1;\n\n        return Score;\n    }\n\n    public String calculateScore() {\n        int Score = this.PasswordStrength();\n\n        if (Score == 6) {\n            return \"This is a very good password :D check the Useful Information section to make sure it satisfies the guidelines\";\n        } else if (Score >= 4) {\n            return \"This is a good password :) but you can still do better\";\n        } else if (Score >= 3) {\n            return \"This is a medium password :/ try making it better\";\n        } else {\n            return \"This is a weak password :( definitely find a new one\";\n        }\n    }\n\n    @Override\n    public String toString() {\n        return Value;\n    }\n}\n", "num_file": 5, "num_lines": 344, "programming_language": "Java"}
{"class_name": "redis", "id": "./MultiFileTest/Java/redis.java", "original_code": "// ./redis/DummyReadWriteLock.java\npackage projecteval.redis;\n\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.locks.Condition;\nimport java.util.concurrent.locks.Lock;\nimport java.util.concurrent.locks.ReadWriteLock;\n\n/**\n * @author Iwao AVE!\n */\nclass DummyReadWriteLock implements ReadWriteLock {\n\n  private Lock lock = new DummyLock();\n\n  @Override\n  public Lock readLock() {\n    return lock;\n  }\n\n  @Override\n  public Lock writeLock() {\n    return lock;\n  }\n\n  static class DummyLock implements Lock {\n\n    @Override\n    public void lock() {\n      // Not implemented\n    }\n\n    @Override\n    public void lockInterruptibly() throws InterruptedException {\n      // Not implemented\n    }\n\n    @Override\n    public boolean tryLock() {\n      return true;\n    }\n\n    @Override\n    public boolean tryLock(long paramLong, TimeUnit paramTimeUnit) throws InterruptedException {\n      return true;\n    }\n\n    @Override\n    public void unlock() {\n      // Not implemented\n    }\n\n    @Override\n    public Condition newCondition() {\n      return null;\n    }\n  }\n\n}\n\n\n// ./redis/JDKSerializer.java\npackage projecteval.redis;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\n\nimport org.apache.ibatis.cache.CacheException;\n\npublic enum JDKSerializer implements Serializer {\n  // Enum singleton, which is preferred approach since Java 1.5\n  INSTANCE;\n\n  private JDKSerializer() {\n    // prevent instantiation\n  }\n\n  @Override\n  public byte[] serialize(Object object) {\n    try (ByteArrayOutputStream baos = new ByteArrayOutputStream();\n        ObjectOutputStream oos = new ObjectOutputStream(baos)) {\n      oos.writeObject(object);\n      return baos.toByteArray();\n    } catch (Exception e) {\n      throw new CacheException(e);\n    }\n  }\n\n  @Override\n  public Object unserialize(byte[] bytes) {\n    if (bytes == null) {\n      return null;\n    }\n    try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);\n        ObjectInputStream ois = new ObjectInputStream(bais)) {\n      return ois.readObject();\n    } catch (Exception e) {\n      throw new CacheException(e);\n    }\n  }\n\n}\n\n\n// ./redis/KryoSerializer.java\npackage projecteval.redis;\n\nimport com.esotericsoftware.kryo.kryo5.Kryo;\nimport com.esotericsoftware.kryo.kryo5.io.Input;\nimport com.esotericsoftware.kryo.kryo5.io.Output;\n\nimport java.util.Arrays;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\n\n/**\n * SerializeUtil with Kryo, which is faster and less space consuming.\n *\n * @author Lei Jiang(ladd.cn@gmail.com)\n */\npublic enum KryoSerializer implements Serializer {\n  // Enum singleton, which is preferred approach since Java 1.5\n  INSTANCE;\n\n  /**\n   * kryo is thread-unsafe, use ThreadLocal.\n   */\n  private ThreadLocal<Kryo> kryos = ThreadLocal.withInitial(Kryo::new);\n\n  /**\n   * Classes which can not resolved by default kryo serializer, which occurs very\n   * rare(https://github.com/EsotericSoftware/kryo#using-standard-java-serialization) For these classes, we will use\n   * fallbackSerializer(use JDKSerializer now) to resolve.\n   */\n  private Set<Class<?>> unnormalClassSet;\n\n  /**\n   * Hash codes of unnormal bytes which can not resolved by default kryo serializer, which will be resolved by\n   * fallbackSerializer\n   */\n  private Set<Integer> unnormalBytesHashCodeSet;\n  private Serializer fallbackSerializer;\n\n  private KryoSerializer() {\n    unnormalClassSet = ConcurrentHashMap.newKeySet();\n    unnormalBytesHashCodeSet = ConcurrentHashMap.newKeySet();\n    fallbackSerializer = JDKSerializer.INSTANCE;// use JDKSerializer as fallback\n  }\n\n  @Override\n  public byte[] serialize(Object object) {\n    if (unnormalClassSet.contains(object.getClass())) {\n      // For unnormal class\n      return fallbackSerializer.serialize(object);\n    }\n\n    /**\n     * In the following cases: 1. This class occurs for the first time. 2. This class have occurred and can be resolved\n     * by default kryo serializer\n     */\n    try (Output output = new Output(200, -1)) {\n      kryos.get().writeClassAndObject(output, object);\n      return output.toBytes();\n    } catch (Exception e) {\n      // For unnormal class occurred for the first time, exception will be thrown\n      unnormalClassSet.add(object.getClass());\n      return fallbackSerializer.serialize(object);// use fallback Serializer to resolve\n    }\n  }\n\n  @Override\n  public Object unserialize(byte[] bytes) {\n    if (bytes == null) {\n      return null;\n    }\n    int hashCode = Arrays.hashCode(bytes);\n    if (unnormalBytesHashCodeSet.contains(hashCode)) {\n      // For unnormal bytes\n      return fallbackSerializer.unserialize(bytes);\n    }\n\n    /**\n     * In the following cases: 1. This bytes occurs for the first time. 2. This bytes have occurred and can be resolved\n     * by default kryo serializer\n     */\n    try (Input input = new Input()) {\n      input.setBuffer(bytes);\n      return kryos.get().readClassAndObject(input);\n    } catch (Exception e) {\n      // For unnormal bytes occurred for the first time, exception will be thrown\n      unnormalBytesHashCodeSet.add(hashCode);\n      return fallbackSerializer.unserialize(bytes);// use fallback Serializer to resolve\n    }\n  }\n\n}\n\n\n// ./redis/Main.java\npackage projecteval.redis;\n\nimport java.io.BufferedWriter;\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\n/**\n * @author 11293\n */\npublic class Main {\n    private static final String DEFAULT_ID = \"REDIS\";\n    private static RedisCache cache = new RedisCache(DEFAULT_ID);\n\n\n    public static void main(String[] args) throws IOException {\n        if (args.length != 2) {\n            System.err.println(\"Error: Two arguments required, the first is the path to the input file, and the second is the path to the output file.\");\n            System.exit(1);\n        }\n\n        String inputFile = args[0];\n        String outputFile = args[1];\n\n        List<String> lines = Files.readAllLines(Paths.get(inputFile));\n        Map<String, String> localCache = new HashMap<>();\n        for (String line : lines) {\n            String[] parts = line.split(\"\\\\s+\");\n            if (parts.length == 2) {\n                String key = parts[0];\n                String value = parts[1];\n                cache.putObject(key, value);\n                localCache.put(key, value);\n            }\n        }\n        try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputFile))) {\n            for (String line : lines) {\n                String[] parts = line.split(\"\\\\s+\");\n                if (parts.length == 2) {\n                    String key = parts[0];\n                    String value = (String) cache.getObject(key);\n                    assert value.equals(localCache.get(key));\n                    writer.write(key + \" \" + value);\n                    writer.newLine();\n                }\n            }\n        }\n    }\n}\n\n// ./redis/RedisCache.java\npackage projecteval.redis;\n\nimport org.apache.ibatis.cache.Cache;\nimport redis.clients.jedis.Jedis;\nimport redis.clients.jedis.JedisPool;\n\nimport java.util.Map;\nimport java.util.concurrent.locks.ReadWriteLock;\n\n/**\n * Cache adapter for Redis.\n *\n * @author Eduardo Macarron\n */\npublic final class RedisCache implements Cache {\n\n    private final ReadWriteLock readWriteLock = new DummyReadWriteLock();\n\n    private String id;\n\n    private static JedisPool pool;\n\n    private final RedisConfig redisConfig;\n\n    private Integer timeout;\n\n    public RedisCache(final String id) {\n        if (id == null) {\n            throw new IllegalArgumentException(\"Cache instances require an ID\");\n        }\n        this.id = id;\n        redisConfig = RedisConfigurationBuilder.getInstance().parseConfiguration();\n        pool = new JedisPool(redisConfig, redisConfig.getHost(), redisConfig.getPort(), redisConfig.getConnectionTimeout(),\n                redisConfig.getSoTimeout(), redisConfig.getPassword(), redisConfig.getDatabase(), redisConfig.getClientName(),\n                redisConfig.isSsl(), redisConfig.getSslSocketFactory(), redisConfig.getSslParameters(),\n                redisConfig.getHostnameVerifier());\n    }\n\n    private Object execute(RedisCallback callback) {\n        Jedis jedis = pool.getResource();\n        try {\n            return callback.doWithRedis(jedis);\n        } finally {\n            jedis.close();\n        }\n    }\n\n    @Override\n    public String getId() {\n        return this.id;\n    }\n\n    @Override\n    public int getSize() {\n        return (Integer) execute(jedis -> {\n            Map<byte[], byte[]> result = jedis.hgetAll(id.getBytes());\n            return result.size();\n        });\n    }\n\n    @Override\n    public void putObject(final Object key, final Object value) {\n        execute(jedis -> {\n            final byte[] idBytes = id.getBytes();\n            jedis.hset(idBytes, key.toString().getBytes(), redisConfig.getSerializer().serialize(value));\n            if (timeout != null && jedis.ttl(idBytes) == -1) {\n                jedis.expire(idBytes, timeout);\n            }\n            return null;\n        });\n    }\n\n    @Override\n    public Object getObject(final Object key) {\n        return execute(\n                jedis -> redisConfig.getSerializer().unserialize(jedis.hget(id.getBytes(), key.toString().getBytes())));\n    }\n\n    @Override\n    public Object removeObject(final Object key) {\n        return execute(jedis -> jedis.hdel(id, key.toString()));\n    }\n\n    @Override\n    public void clear() {\n        execute(jedis -> {\n            jedis.del(id);\n            return null;\n        });\n    }\n\n    @Override\n    public ReadWriteLock getReadWriteLock() {\n        return readWriteLock;\n    }\n\n    @Override\n    public String toString() {\n        return \"Redis {\" + id + \"}\";\n    }\n\n    public void setTimeout(Integer timeout) {\n        this.timeout = timeout;\n    }\n\n}\n\n\n// ./redis/RedisCallback.java\npackage projecteval.redis;\n\nimport redis.clients.jedis.Jedis;\n\npublic interface RedisCallback {\n\n  Object doWithRedis(Jedis jedis);\n}\n\n\n// ./redis/RedisConfig.java\npackage projecteval.redis;\n\nimport redis.clients.jedis.JedisPoolConfig;\nimport redis.clients.jedis.Protocol;\n\nimport javax.net.ssl.HostnameVerifier;\nimport javax.net.ssl.SSLParameters;\nimport javax.net.ssl.SSLSocketFactory;\n\npublic class RedisConfig extends JedisPoolConfig {\n    private String host = Protocol.DEFAULT_HOST;\n    private int port = Protocol.DEFAULT_PORT;\n    private int connectionTimeout = Protocol.DEFAULT_TIMEOUT;\n    private int soTimeout = Protocol.DEFAULT_TIMEOUT;\n    private String password;\n    private int database = Protocol.DEFAULT_DATABASE;\n    private String clientName;\n    private boolean ssl;\n    private SSLSocketFactory sslSocketFactory;\n    private SSLParameters sslParameters;\n    private HostnameVerifier hostnameVerifier;\n    private Serializer serializer = JDKSerializer.INSTANCE;\n\n    public boolean isSsl() {\n        return ssl;\n    }\n\n    public void setSsl(boolean ssl) {\n        this.ssl = ssl;\n    }\n\n    public SSLSocketFactory getSslSocketFactory() {\n        return sslSocketFactory;\n    }\n\n    public void setSslSocketFactory(SSLSocketFactory sslSocketFactory) {\n        this.sslSocketFactory = sslSocketFactory;\n    }\n\n    public SSLParameters getSslParameters() {\n        return sslParameters;\n    }\n\n    public void setSslParameters(SSLParameters sslParameters) {\n        this.sslParameters = sslParameters;\n    }\n\n    public HostnameVerifier getHostnameVerifier() {\n        return hostnameVerifier;\n    }\n\n    public void setHostnameVerifier(HostnameVerifier hostnameVerifier) {\n        this.hostnameVerifier = hostnameVerifier;\n    }\n\n    public String getHost() {\n        return host;\n    }\n\n    public void setHost(String host) {\n        if (host == null || host.isEmpty()) {\n            host = Protocol.DEFAULT_HOST;\n        }\n        this.host = host;\n    }\n\n    public int getPort() {\n        return port;\n    }\n\n    public void setPort(int port) {\n        this.port = port;\n    }\n\n    public String getPassword() {\n        return password;\n    }\n\n    public void setPassword(String password) {\n        if (password == null || password.isEmpty()) {\n            password = null;\n        }\n        this.password = password;\n    }\n\n    public int getDatabase() {\n        return database;\n    }\n\n    public void setDatabase(int database) {\n        this.database = database;\n    }\n\n    public String getClientName() {\n        return clientName;\n    }\n\n    public void setClientName(String clientName) {\n        if (clientName == null || clientName.isEmpty()) {\n            clientName = null;\n        }\n        this.clientName = clientName;\n    }\n\n    public int getConnectionTimeout() {\n        return connectionTimeout;\n    }\n\n    public void setConnectionTimeout(int connectionTimeout) {\n        this.connectionTimeout = connectionTimeout;\n    }\n\n    public int getSoTimeout() {\n        return soTimeout;\n    }\n\n    public void setSoTimeout(int soTimeout) {\n        this.soTimeout = soTimeout;\n    }\n\n    public Serializer getSerializer() {\n        return serializer;\n    }\n\n    public void setSerializer(Serializer serializer) {\n        this.serializer = serializer;\n    }\n\n}\n\n\n// ./redis/RedisConfigurationBuilder.java\npackage projecteval.redis;\n\nimport org.apache.ibatis.cache.CacheException;\nimport org.apache.ibatis.io.Resources;\nimport org.apache.ibatis.reflection.MetaObject;\nimport org.apache.ibatis.reflection.SystemMetaObject;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.Arrays;\nimport java.util.Map;\nimport java.util.Properties;\n\n/**\n * Converter from the Config to a proper {@link RedisConfig}.\n *\n * @author Eduardo Macarron\n */\nfinal class RedisConfigurationBuilder {\n\n    /**\n     * This class instance.\n     */\n    private static final RedisConfigurationBuilder INSTANCE = new RedisConfigurationBuilder();\n\n    protected static final String SYSTEM_PROPERTY_REDIS_PROPERTIES_FILENAME = \"redis.properties.filename\";\n\n    protected static final String REDIS_RESOURCE = \"redis.properties\";\n\n    /**\n     * Hidden constructor, this class can't be instantiated.\n     */\n    private RedisConfigurationBuilder() {\n    }\n\n    /**\n     * Return this class instance.\n     *\n     * @return this class instance.\n     */\n    public static RedisConfigurationBuilder getInstance() {\n        return INSTANCE;\n    }\n\n    /**\n     * Parses the Config and builds a new {@link RedisConfig}.\n     *\n     * @return the converted {@link RedisConfig}.\n     */\n    public RedisConfig parseConfiguration() {\n        return parseConfiguration(getClass().getClassLoader());\n    }\n\n    /**\n     * Parses the Config and builds a new {@link RedisConfig}.\n     *\n     * @param the {@link ClassLoader} used to load the {@code memcached.properties} file in classpath.\n     * @return the converted {@link RedisConfig}.\n     */\n    public RedisConfig parseConfiguration(ClassLoader classLoader) {\n        Properties config = new Properties();\n\n        String redisPropertiesFilename = System.getProperty(SYSTEM_PROPERTY_REDIS_PROPERTIES_FILENAME, REDIS_RESOURCE);\n\n        try (InputStream input = classLoader.getResourceAsStream(redisPropertiesFilename)) {\n            if (input != null) {\n                config.load(input);\n            }\n        } catch (IOException e) {\n            throw new RuntimeException(\n                    \"An error occurred while reading classpath property '\" + redisPropertiesFilename + \"', see nested exceptions\",\n                    e);\n        }\n\n        RedisConfig jedisConfig = new RedisConfig();\n        setConfigProperties(config, jedisConfig);\n        return jedisConfig;\n    }\n\n    private void setConfigProperties(Properties properties, RedisConfig jedisConfig) {\n        if (properties != null) {\n            MetaObject metaCache = SystemMetaObject.forObject(jedisConfig);\n            for (Map.Entry<Object, Object> entry : properties.entrySet()) {\n                String name = (String) entry.getKey();\n                // All prefix of 'redis.' on property values\n                if (name != null && name.startsWith(\"redis.\")) {\n                    name = name.substring(6);\n                } else {\n                    // Skip non prefixed properties\n                    continue;\n                }\n                String value = (String) entry.getValue();\n                if (\"serializer\".equals(name)) {\n                    if (\"kryo\".equalsIgnoreCase(value)) {\n                        jedisConfig.setSerializer(KryoSerializer.INSTANCE);\n                    } else if (!\"jdk\".equalsIgnoreCase(value)) {\n                        // Custom serializer is not supported yet.\n                        throw new CacheException(\"Unknown serializer: '\" + value + \"'\");\n                    }\n                } else if (Arrays.asList(\"sslSocketFactory\", \"sslParameters\", \"hostnameVerifier\").contains(name)) {\n                    setInstance(metaCache, name, value);\n                } else if (metaCache.hasSetter(name)) {\n                    Class<?> type = metaCache.getSetterType(name);\n                    if (String.class == type) {\n                        metaCache.setValue(name, value);\n                    } else if (int.class == type || Integer.class == type) {\n                        metaCache.setValue(name, Integer.valueOf(value));\n                    } else if (long.class == type || Long.class == type) {\n                        metaCache.setValue(name, Long.valueOf(value));\n                    } else if (short.class == type || Short.class == type) {\n                        metaCache.setValue(name, Short.valueOf(value));\n                    } else if (byte.class == type || Byte.class == type) {\n                        metaCache.setValue(name, Byte.valueOf(value));\n                    } else if (float.class == type || Float.class == type) {\n                        metaCache.setValue(name, Float.valueOf(value));\n                    } else if (boolean.class == type || Boolean.class == type) {\n                        metaCache.setValue(name, Boolean.valueOf(value));\n                    } else if (double.class == type || Double.class == type) {\n                        metaCache.setValue(name, Double.valueOf(value));\n                    } else {\n                        throw new CacheException(\"Unsupported property type: '\" + name + \"' of type \" + type);\n                    }\n                }\n            }\n        }\n    }\n\n    protected void setInstance(MetaObject metaCache, String name, String value) {\n        if (value == null || value.isEmpty()) {\n            return;\n        }\n        Object instance;\n        try {\n            Class<?> clazz = Resources.classForName(value);\n            instance = clazz.getDeclaredConstructor().newInstance();\n        } catch (Exception e) {\n            throw new CacheException(\"Could not instantiate class: '\" + value + \"'.\", e);\n        }\n        metaCache.setValue(name, instance);\n    }\n\n}\n\n\n// ./redis/Serializer.java\npackage projecteval.redis;\n\npublic interface Serializer {\n\n  /**\n   * Serialize method\n   *\n   * @param object\n   *\n   * @return serialized bytes\n   */\n  byte[] serialize(Object object);\n\n  /**\n   * Unserialize method\n   *\n   * @param bytes\n   *\n   * @return unserialized object\n   */\n  Object unserialize(byte[] bytes);\n\n}\n", "num_file": 9, "num_lines": 651, "programming_language": "Java"}
{"class_name": "servlet", "id": "./MultiFileTest/Java/servlet.java", "original_code": "// ./servlet/DBUtilR.java\npackage projecteval.servlet;\n\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\n\npublic class DBUtilR {\n\t  static Connection conn = null;\n\tstatic\n\t {\t\n\t\ttry {\n\t\t\tClass.forName(\"com.mysql.jdbc.Driver\");\n\t\t\t\n\t\t\tconn = DriverManager.getConnection(\"jdbc:mysql://localhost:3306/votingdb\", \"Vaishnavi\", \"Nelavetla@537\");\n\t\t\t\n\t\t\tif(!conn.isClosed()) {\n\t\t\t\tSystem.out.println(\"Connection established\");\n\t\t\t}\n\t\t\t\n\t\t} catch (ClassNotFoundException | SQLException e) {\n\t\t\tSystem.out.println(\"Error in DBUtilFile\");\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\t\n\tpublic static  Connection getDBConnection() {\n\t\t// TODO Auto-generated method stub\n\t\treturn conn;\n\t}\n}\n\n// ./servlet/againvote.java\npackage projecteval.servlet;\n\nimport java.io.IOException;\n\nimport jakarta.servlet.ServletException;\nimport jakarta.servlet.http.HttpServlet;\nimport jakarta.servlet.http.HttpServletRequest;\nimport jakarta.servlet.http.HttpServletResponse;\n\npublic class againvote extends HttpServlet {\n\tprivate static final long serialVersionUID = 1L;\n       \n\tprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException \n\t{\n\t\tdoGet(request, response);\n\t}\n\n}\n\n\n// ./servlet/loginpage.java\npackage projecteval.servlet;\n\nimport jakarta.servlet.RequestDispatcher;\nimport jakarta.servlet.ServletException;\nimport jakarta.servlet.http.HttpServlet;\nimport jakarta.servlet.http.HttpServletRequest;\nimport jakarta.servlet.http.HttpServletResponse;\n\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.sql.Connection;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\n\npublic class loginpage extends HttpServlet {\n\tprivate static final long serialVersionUID = 1L;\n\t\n\tfinal static  Connection con=DBUtilR.getDBConnection();\n\tstatic PreparedStatement ps = null;\n       \n\tprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException \n\t{\n\t\tPrintWriter out = response.getWriter();  \n\t\tString card=request.getParameter(\"cardno\");\n\t\tInteger pin=Integer.parseInt(request.getParameter(\"pin\"));\n\t\t\n\t\ttry {\n\t\t\tif(check(card,pin))\n\t\t\t{\n\t\t\t\tout.print(\"Successful Login...You Can Vote Now\");\n\t\t\t\tRequestDispatcher rd=request.getRequestDispatcher(\"vote.html\");\n\t\t\t\t rd.include(request,response);\n\t\t\t}\t\n\t\t\telse {\n\t\t\t\t out.print(\"Sorry username or password error , Make new account\");  \n\t\t\t\t RequestDispatcher rd=request.getRequestDispatcher(\"registration.html\");  \n\t\t\t        rd.include(request,response);\n\t\t\t}\n\t\t}\n\t\tcatch (SQLException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\n\t\n\t}\n\tstatic boolean check(String card,Integer pin) throws SQLException\n\t {\n\t\t boolean r=false;\n\t\t ps=con.prepareStatement(\"Select * from register where cardno=? and pin=?\");\n\t\t ps.setString(1,card);\n\t\t ps.setInt(2,pin);\n\t\t ResultSet rs=ps.executeQuery();\n\t\t r=rs.next();\n\t\t \n\t\t return r;\n\t }\n\t\n\tstatic boolean checkvote(String card) throws SQLException\n\t {\n\t\t boolean r=false;\n\t\t ps=con.prepareStatement(\"Select * from vote where cardno=?\");\n\t\t ps.setString(1,card);\n\t\t \n\t\t ResultSet rs=ps.executeQuery();\n\t\t r=rs.next();\n\t\t \n\t\t return r;\n\t }\n\n}\n\n\n// ./servlet/registration.java\npackage projecteval.servlet;\n\nimport jakarta.servlet.RequestDispatcher;\nimport jakarta.servlet.ServletException;\nimport jakarta.servlet.http.HttpServlet;\nimport jakarta.servlet.http.HttpServletRequest;\nimport jakarta.servlet.http.HttpServletResponse;\n\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\n\npublic class registration extends HttpServlet {\n\tprivate static final long serialVersionUID = 1L;\n \n\tprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException \n\t{\n\t\tresponse.setContentType(\"text/html\");  \n\t\tPrintWriter out = response.getWriter();\n\t\t\n\t\t\n\t\tString f=request.getParameter(\"fname\");\n\t\t\n\t\tString c=request.getParameter(\"cardno\");\n\t\tString cn=request.getParameter(\"cono\");\n\t\tString ad=request.getParameter(\"add\");\n\t\tString dob=request.getParameter(\"dob\");\n\t\tString email=request.getParameter(\"email\");\n\t\tString pin=request.getParameter(\"pin\");\n\t\ttry\n\t\t{\n\t\t\n\t\tClass.forName(\"com.mysql.jdbc.Driver\");\n\t\tConnection con=(Connection) DriverManager.getConnection(\"jdbc:mysql://localhost:3306/votingdb\",\"Vaishnavi\",\"Nelavetla@537\");\n\t\tPreparedStatement ps=con.prepareStatement(\"insert into register values(?,?,?,?,?,?,?)\");\n\t\tps.setString(1,f);\n\t\t\n\t\tps.setString(2,c);\n\t\tps.setString(3,cn);\n\t\tps.setString(4,ad);\n\t\tps.setString(5,dob);\n\t\tps.setString(6,email);\n\t\tps.setString(7,pin);\n\t\tint i=ps.executeUpdate();\n\t\tif(i>0)\n\t\t{\n\t\t\tout.print(\"Successfully your account has been created...PLEASE LOGIN\");\n\t\t\t RequestDispatcher rd=request.getRequestDispatcher(\"loginpage.html\");  \n\t\t        rd.include(request,response);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tout.print(\"Failed account creation try again\");\n\t\t\t RequestDispatcher rd=request.getRequestDispatcher(\"registration.html\");  \n\t\t        rd.include(request,response);\n\t\t}\n\t\t\t\n\t\t}\n\t\tcatch (Exception e2) {\n\t\t\tout.print(\"Invalid , Failed account creation try again  \"+e2);\n\t\t\t RequestDispatcher rd=request.getRequestDispatcher(\"registration.html\");  \n\t\t        rd.include(request,response);\n\t\t}\n\t\t\n\t\tout.close();\n\t\n}\n\tprotected void service(HttpServletRequest request, HttpServletResponse   response) throws ServletException, IOException \n\t{\n        doPost(request, response);\n\t}\n\n}\n\n\n// ./servlet/thankyou.java\npackage projecteval.servlet;\n\nimport jakarta.servlet.ServletException;\nimport jakarta.servlet.http.HttpServlet;\nimport jakarta.servlet.http.HttpServletRequest;\nimport jakarta.servlet.http.HttpServletResponse;\nimport java.io.IOException;\n\npublic class thankyou extends HttpServlet {\n\tprivate static final long serialVersionUID = 1L;\n \n\tprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException \n\t{\n\t\t\n\t}\n\n}\n\n\n// ./servlet/vote.java\npackage projecteval.servlet;\n\nimport jakarta.servlet.RequestDispatcher;\nimport jakarta.servlet.ServletException;\nimport jakarta.servlet.http.HttpServlet;\nimport jakarta.servlet.http.HttpServletRequest;\nimport jakarta.servlet.http.HttpServletResponse;\n\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.SQLIntegrityConstraintViolationException;\n\npublic class vote extends HttpServlet {\n\tprivate static final long serialVersionUID = 1L;\n\t\n    final static Connection con=DBUtilR.getDBConnection();\n    static PreparedStatement ps = null;\n       \n\tprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException \n\t{\n\t\tresponse.setContentType(\"text/html\");  \n\t\tPrintWriter out = response.getWriter();\n\t\t\n\t\t\n\t\tString f=request.getParameter(\"cardno\");\n\t\tString l=request.getParameter(\"party\");\n\t\ttry\n\t\t{\n\t\t\n\t\tClass.forName(\"com.mysql.jdbc.Driver\");\n\t\tConnection con=(Connection) DriverManager.getConnection(\"jdbc:mysql://localhost:3306/votingdb\",\"Vaishnavi\",\"Nelavetla@537\");\n\n\t\tif(checkLogin(f))\n\t\t{\n\t\t\t\n\t\tps=con.prepareStatement(\"insert into vote values(?,?)\");\n\t\tps.setString(1,f);\n\t\tps.setString(2,l);\n\t\tint i=ps.executeUpdate();\n\t\tif(i>0)\n\t\t{\n\t\t\tout.print(\"Your Vote has been submitted successfully...\");\n\t\t\t RequestDispatcher rd=request.getRequestDispatcher(\"thankyou.html\");  \n\t\t        rd.include(request,response);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tout.print(\"Failed to submit vote, try again\");\n\t\t\t RequestDispatcher rd=request.getRequestDispatcher(\"vote.html\");  \n\t\t        rd.include(request,response);\n\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tout.print(\"Please enter correct card number\");\n\t\t\tRequestDispatcher rd=request.getRequestDispatcher(\"vote.html\");  \n\t        rd.include(request,response);\n\t\t}\n\t\t}\n\t\tcatch (SQLIntegrityConstraintViolationException e2) {\n\t\t\tout.print(\"Please select any party\");\n\t\t\t RequestDispatcher rd=request.getRequestDispatcher(\"vote.html\");  \n\t\t        rd.include(request,response);\n\t\t}\n\t\tcatch(Exception e)\n\t\t{\n\t\t\tout.print(\" \" +e);\n\t\t\tRequestDispatcher rd=request.getRequestDispatcher(\"vote.html\");  \n\t        rd.include(request,response);\n\t\t}\n\t\tout.close();\n\t\n\t\t\n}\n\tprotected void service(HttpServletRequest request, HttpServletResponse   response) throws ServletException, IOException {\n        doPost(request, response);\n}\n\t\n\n\nstatic boolean checkLogin(String card) throws SQLException\n{\n boolean r=false;\n ps=con.prepareStatement(\"Select * from register where cardno = ?\");\n ps.setString(1,card);\n \n ResultSet rs=ps.executeQuery();\n r=rs.next();\n \n return r;\n}\n}\n", "num_file": 6, "num_lines": 308, "programming_language": "Java"}
{"class_name": "springdatamongowithcluster", "id": "./MultiFileTest/Java/springdatamongowithcluster.java", "original_code": "// ./springdatamongowithcluster/Car.java\npackage projecteval.springdatamongowithcluster;\n\n\nimport org.springframework.data.annotation.Id;\n\nimport lombok.Builder;\n\n@Builder\npublic class Car {\n    \n    @Id\n    private String id;\n    \n    private String name;\n}\n\n\n// ./springdatamongowithcluster/SpringDataMongoWithClusterApplication.java\npackage projecteval.springdatamongowithcluster;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.CommandLineRunner;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.data.mongodb.core.MongoTemplate;\nimport org.springframework.data.mongodb.core.query.Query;\n\nimport lombok.extern.log4j.Log4j2;\n\n\n@SpringBootApplication\n@Log4j2\npublic class SpringDataMongoWithClusterApplication implements CommandLineRunner {\n    \n    @Autowired\n    MongoTemplate mongoTemplate;\n    \n    public static void main(String[] args) {\n        SpringApplication.run(SpringDataMongoWithClusterApplication.class, args);\n    }\n    \n    @Override\n    public void run(String... args) {\n        \n        mongoTemplate.dropCollection(Car.class);\n        \n        mongoTemplate.save(Car.builder().name(\"Tesla Model S\").build());\n        mongoTemplate.save(Car.builder().name(\"Tesla Model 3\").build());\n        \n        log.info(\"-------------------------------\");\n        log.info(\"Cards found: \" + mongoTemplate.count(new Query(), Car.class));\n        log.info(\"-------------------------------\");\n    }\n}\n", "num_file": 2, "num_lines": 51, "programming_language": "Java"}
{"class_name": "springmicrometerundertow", "id": "./MultiFileTest/Java/springmicrometerundertow.java", "original_code": "// ./springmicrometerundertow/SpringMicrometerUndertowApplication.java\npackage projecteval.springmicrometerundertow;\n\nimport io.micrometer.core.instrument.MeterRegistry;\nimport io.undertow.server.HandlerWrapper;\nimport io.undertow.server.handlers.MetricsHandler;\nimport io.undertow.servlet.api.MetricsCollector;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.boot.web.embedded.undertow.UndertowDeploymentInfoCustomizer;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.http.MediaType;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.bind.annotation.RestController;\n\n@SpringBootApplication\n@RestController\npublic class SpringMicrometerUndertowApplication {\n\n    public static void main(String[] args) {\n        SpringApplication.run(SpringMicrometerUndertowApplication.class, args);\n    }\n\n    @Bean\n    UndertowDeploymentInfoCustomizer undertowDeploymentInfoCustomizer(UndertowMetricsHandlerWrapper undertowMetricsHandlerWrapper) {\n\n        return deploymentInfo -> deploymentInfo.addOuterHandlerChainWrapper(undertowMetricsHandlerWrapper);\n        //return deploymentInfo -> deploymentInfo.addOuterHandlerChainWrapper(MetricsHandler.WRAPPER);\n    }\n\n    @Bean\n    MeterRegistryCustomizer<MeterRegistry> micrometerMeterRegistryCustomizer(@Value(\"${spring.application.name}\") String applicationName) {\n        return registry -> registry.config().commonTags(\"application.name\", applicationName);\n    }\n\n    @GetMapping(value = \"/hello\", produces = MediaType.APPLICATION_JSON_VALUE)\n    public String hello(@RequestParam(name = \"name\", required = true) String name) {\n        return \"Hello \" + name + \"!\";\n    }\n\n}\n\n\n// ./springmicrometerundertow/UndertowMeterBinder.java\npackage projecteval.springmicrometerundertow;\n\nimport io.micrometer.core.instrument.FunctionCounter;\nimport io.micrometer.core.instrument.FunctionTimer;\nimport io.micrometer.core.instrument.MeterRegistry;\nimport io.micrometer.core.instrument.TimeGauge;\nimport io.micrometer.core.instrument.binder.MeterBinder;\nimport io.undertow.server.handlers.MetricsHandler;\nimport org.springframework.boot.context.event.ApplicationReadyEvent;\nimport org.springframework.context.ApplicationListener;\nimport org.springframework.stereotype.Component;\n\nimport java.util.concurrent.TimeUnit;\nimport java.util.function.ToDoubleFunction;\nimport java.util.function.ToLongFunction;\n\n@Component\npublic class UndertowMeterBinder implements ApplicationListener<ApplicationReadyEvent> {\n\n    private final UndertowMetricsHandlerWrapper undertowMetricsHandlerWrapper;\n\n    public UndertowMeterBinder(UndertowMetricsHandlerWrapper undertowMetricsHandlerWrapper) {\n        this.undertowMetricsHandlerWrapper = undertowMetricsHandlerWrapper;\n    }\n\n    @Override\n    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {\n        bindTo(applicationReadyEvent.getApplicationContext().getBean(MeterRegistry.class));\n    }\n\n    public void bindTo(MeterRegistry meterRegistry) {\n        bind(meterRegistry, undertowMetricsHandlerWrapper.getMetricsHandler());\n    }\n\n    public void bind(MeterRegistry registry, MetricsHandler metricsHandler) {\n        bindTimer(registry, \"undertow.requests\", \"Number of requests\", metricsHandler,\n                m -> m.getMetrics().getTotalRequests(), m2 -> m2.getMetrics().getMinRequestTime());\n        bindTimeGauge(registry, \"undertow.request.time.max\", \"The longest request duration in time\", metricsHandler,\n                m -> m.getMetrics().getMaxRequestTime());\n        bindTimeGauge(registry, \"undertow.request.time.min\", \"The shortest request duration in time\", metricsHandler,\n                m -> m.getMetrics().getMinRequestTime());\n        bindCounter(registry, \"undertow.request.errors\", \"Total number of error requests \", metricsHandler,\n                m -> m.getMetrics().getTotalErrors());\n\n    }\n\n    private void bindTimer(MeterRegistry registry, String name, String desc, MetricsHandler metricsHandler,\n                           ToLongFunction<MetricsHandler> countFunc, ToDoubleFunction<MetricsHandler> consumer) {\n        FunctionTimer.builder(name, metricsHandler, countFunc, consumer, TimeUnit.MILLISECONDS)\n                .description(desc).register(registry);\n    }\n\n    private void bindTimeGauge(MeterRegistry registry, String name, String desc, MetricsHandler metricResult,\n                               ToDoubleFunction<MetricsHandler> consumer) {\n        TimeGauge.builder(name, metricResult, TimeUnit.MILLISECONDS, consumer).description(desc)\n                .register(registry);\n    }\n\n    private void bindCounter(MeterRegistry registry, String name, String desc, MetricsHandler metricsHandler,\n                             ToDoubleFunction<MetricsHandler> consumer) {\n        FunctionCounter.builder(name, metricsHandler, consumer).description(desc)\n                .register(registry);\n    }\n}\n\n// ./springmicrometerundertow/UndertowMetricsHandlerWrapper.java\npackage projecteval.springmicrometerundertow;\n\nimport io.undertow.server.HandlerWrapper;\nimport io.undertow.server.HttpHandler;\nimport io.undertow.server.handlers.MetricsHandler;\nimport org.springframework.stereotype.Component;\n\n@Component\npublic class UndertowMetricsHandlerWrapper implements HandlerWrapper {\n\n    private MetricsHandler metricsHandler;\n\n    @Override\n    public HttpHandler wrap(HttpHandler handler) {\n        metricsHandler = new MetricsHandler(handler);\n        return metricsHandler;\n    }\n\n    public MetricsHandler getMetricsHandler() {\n        return metricsHandler;\n    }\n}\n", "num_file": 3, "num_lines": 130, "programming_language": "Java"}
{"class_name": "springreactivenonreactive", "id": "./MultiFileTest/Java/springreactivenonreactive.java", "original_code": "// ./springreactivenonreactive/SpringMvcVsWebfluxApplication.java\npackage projecteval.springreactivenonreactive;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class SpringMvcVsWebfluxApplication {\n\n\tpublic static void main(String[] args) {\n\t\tSpringApplication.run(SpringMvcVsWebfluxApplication.class, args);\n\t}\n\n}\n\n\n// ./springreactivenonreactive/controller/MVCAsyncController.java\npackage projecteval.springreactivenonreactive.controller;\n\nimport java.util.concurrent.CompletableFuture;\n\nimport javax.validation.Valid;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport projecteval.springreactivenonreactive.model.Message;\nimport projecteval.springreactivenonreactive.repository.NonReactiveRepository;\n\n@RestController\npublic class MVCAsyncController {\n    \n    @Autowired\n    NonReactiveRepository nonReactiveRepository;\n    \n    @RequestMapping(\"/mvcasync/{id}\")\n    public CompletableFuture<Message> findById(@PathVariable(value = \"id\") String id) {\n        return CompletableFuture.supplyAsync(() -> nonReactiveRepository.findById(id).orElse(null));\n    }\n    \n    @PostMapping(\"/mvcasync\")\n    public CompletableFuture<Message> post(@Valid @RequestBody Message message) {\n        return CompletableFuture.supplyAsync(() -> nonReactiveRepository.save(message));\n    }\n}\n\n\n\n// ./springreactivenonreactive/controller/MVCSyncController.java\npackage projecteval.springreactivenonreactive.controller;\n\nimport javax.validation.Valid;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport projecteval.springreactivenonreactive.model.Message;\nimport projecteval.springreactivenonreactive.repository.NonReactiveRepository;\n\n@RestController\npublic class MVCSyncController {\n    \n    @Autowired\n    NonReactiveRepository nonReactiveRepository;\n    \n    @RequestMapping(\"/mvcsync/{id}\")\n    public Message findById(@PathVariable(value = \"id\") String id) {\n        return nonReactiveRepository.findById(id).orElse(null);\n    }\n    \n    @PostMapping(\"/mvcsync\")\n    public Message post(@Valid @RequestBody Message message) {\n        return nonReactiveRepository.save(message);\n    }\n}\n\n\n\n// ./springreactivenonreactive/controller/WebFluxController.java\npackage projecteval.springreactivenonreactive.controller;\n\nimport javax.validation.Valid;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.DeleteMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport projecteval.springreactivenonreactive.model.Message;\nimport projecteval.springreactivenonreactive.repository.ReactiveRepository;\n\nimport reactor.core.publisher.Mono;\n\n@RestController\npublic class WebFluxController {\n    \n    @Autowired\n    ReactiveRepository reactiveRepository;\n    \n    @RequestMapping(\"/webflux/{id}\")\n    public Mono<Message> findByIdReactive(@PathVariable(value = \"id\") String id) {\n        return reactiveRepository.findById(id);\n    }\n    \n    @PostMapping(\"/webflux\")\n    public Mono<Message> postReactive(@Valid @RequestBody Message message) {\n        return reactiveRepository.save(message);\n    }\n    \n    @DeleteMapping(\"/webflux\")\n    public Mono<Void> deleteAllReactive() {\n        return reactiveRepository.deleteAll();\n    }\n}\n\n\n\n// ./springreactivenonreactive/model/Message.java\npackage projecteval.springreactivenonreactive.model;\n\nimport java.util.Date;\n\nimport javax.validation.constraints.NotBlank;\nimport javax.validation.constraints.NotNull;\n\nimport org.springframework.data.annotation.Id;\nimport org.springframework.data.mongodb.core.mapping.Document;\n\nimport lombok.Getter;\nimport lombok.NoArgsConstructor;\nimport lombok.Setter;\nimport lombok.ToString;\n\n@Document(collection = \"messages\")\n@Getter\n@Setter\n@NoArgsConstructor\n@ToString\npublic class Message {\n    \n    @Id\n    private String id;\n    \n    @NotBlank\n    private String content;\n    \n    @NotNull\n    private Date createdAt = new Date();\n    \n}\n\n// ./springreactivenonreactive/repository/NonReactiveRepository.java\npackage projecteval.springreactivenonreactive.repository;\n\nimport org.springframework.data.mongodb.repository.MongoRepository;\nimport org.springframework.stereotype.Repository;\n\nimport projecteval.springreactivenonreactive.model.Message;\n\n@Repository\npublic interface NonReactiveRepository extends MongoRepository<Message, String> {\n\n}\n\n\n// ./springreactivenonreactive/repository/ReactiveRepository.java\npackage projecteval.springreactivenonreactive.repository;\n\nimport org.springframework.data.mongodb.repository.ReactiveMongoRepository;\nimport org.springframework.stereotype.Repository;\n\nimport projecteval.springreactivenonreactive.model.Message;\n\n@Repository\npublic interface ReactiveRepository extends ReactiveMongoRepository<Message, String> {\n\n}\n", "num_file": 7, "num_lines": 170, "programming_language": "Java"}
{"class_name": "springuploads3", "id": "./MultiFileTest/Java/springuploads3.java", "original_code": "// ./springuploads3/SpringUploadS3Application.java\npackage projecteval.springuploads3;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class SpringUploadS3Application {\n\n\tpublic static void main(String[] args) {\n\t\tSpringApplication.run(SpringUploadS3Application.class, args);\n\t}\n\n}\n\n\n// ./springuploads3/configuration/S3ClientConfiguration.java\npackage projecteval.springuploads3.configuration;\n\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\n\nimport com.amazonaws.client.builder.AwsClientBuilder;\nimport com.amazonaws.regions.Regions;\nimport com.amazonaws.services.s3.AmazonS3;\nimport com.amazonaws.services.s3.AmazonS3ClientBuilder;\n\n@Configuration\npublic class S3ClientConfiguration {\n    \n    @Value(\"${aws.s3.endpoint-url}\")\n    private String endpointUrl;\n    \n    @Bean\n    AmazonS3 amazonS3() {\n        AwsClientBuilder.EndpointConfiguration endpointConfiguration = new AwsClientBuilder.EndpointConfiguration(endpointUrl,\n                Regions.US_EAST_1.getName());\n        return AmazonS3ClientBuilder.standard().withEndpointConfiguration(endpointConfiguration).withPathStyleAccessEnabled(true).build();\n    }\n}\n\n\n// ./springuploads3/controller/FileDownloadController.java\npackage projecteval.springuploads3.controller;\n\nimport projecteval.springuploads3.service.model.DownloadedResource;\nimport org.springframework.core.io.InputStreamResource;\nimport org.springframework.core.io.Resource;\nimport org.springframework.http.HttpHeaders;\nimport org.springframework.http.MediaType;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.GetMapping;\n\nimport projecteval.springuploads3.service.StorageService;\nimport lombok.extern.log4j.Log4j2;\n\n@Controller\n@Log4j2\npublic class FileDownloadController {\n    \n    private final StorageService storageService;\n    \n    public FileDownloadController(StorageService storageService) {\n        this.storageService = storageService;\n    }\n    \n    @GetMapping(\"/download\")\n    public ResponseEntity<Resource> download(String id) {\n        DownloadedResource downloadedResource = storageService.download(id);\n        \n        return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, \"attachment; filename=\" + downloadedResource.getFileName())\n                .contentLength(downloadedResource.getContentLength()).contentType(MediaType.APPLICATION_OCTET_STREAM)\n                .body(new InputStreamResource(downloadedResource.getInputStream()));\n    }\n}\n\n\n// ./springuploads3/controller/FileUploadController.java\npackage projecteval.springuploads3.controller;\n\nimport projecteval.springuploads3.service.StorageService;\nimport lombok.extern.log4j.Log4j2;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.multipart.MultipartFile;\n\n@Controller\n@Log4j2\npublic class FileUploadController {\n    \n    private final StorageService storageService;\n    \n    public FileUploadController(StorageService storageService) {\n        this.storageService = storageService;\n    }\n    \n    @PostMapping(value = \"/upload\", produces = \"application/json\")\n    public ResponseEntity<String> upload(@RequestParam(\"file\") MultipartFile file) {\n        String key = storageService.upload(file);\n        return new ResponseEntity<>(key, HttpStatus.OK);\n    }\n}\n\n\n// ./springuploads3/service/S3StorageService.java\npackage projecteval.springuploads3.service;\n\nimport org.apache.commons.io.FilenameUtils;\nimport org.apache.commons.lang3.RandomStringUtils;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.stereotype.Service;\nimport org.springframework.web.multipart.MultipartFile;\n\nimport com.amazonaws.services.s3.AmazonS3;\nimport com.amazonaws.services.s3.model.ObjectMetadata;\nimport com.amazonaws.services.s3.model.S3Object;\n\nimport projecteval.springuploads3.service.model.DownloadedResource;\nimport lombok.SneakyThrows;\n\n@Service\npublic class S3StorageService implements StorageService {\n    \n    private static final String FILE_EXTENSION = \"fileExtension\";\n    \n    private final AmazonS3 amazonS3;\n    private final String bucketName;\n    \n    public S3StorageService(AmazonS3 amazonS3, @Value(\"${aws.s3.bucket-name}\") String bucketName) {\n        this.amazonS3 = amazonS3;\n        this.bucketName = bucketName;\n        \n        initializeBucket();\n    }\n    \n    @SneakyThrows\n    @Override\n    public String upload(MultipartFile multipartFile) {\n        String key = RandomStringUtils.randomAlphanumeric(50);\n        \n        amazonS3.putObject(bucketName, key, multipartFile.getInputStream(), extractObjectMetadata(multipartFile));\n        \n        return key;\n    }\n    \n    @Override\n    public DownloadedResource download(String id) {\n        S3Object s3Object = amazonS3.getObject(bucketName, id);\n        String filename = id + \".\" + s3Object.getObjectMetadata().getUserMetadata().get(FILE_EXTENSION);\n        Long contentLength = s3Object.getObjectMetadata().getContentLength();\n        \n        return DownloadedResource.builder().id(id).fileName(filename).contentLength(contentLength).inputStream(s3Object.getObjectContent())\n                .build();\n    }\n    \n    private ObjectMetadata extractObjectMetadata(MultipartFile file) {\n        ObjectMetadata objectMetadata = new ObjectMetadata();\n        \n        objectMetadata.setContentLength(file.getSize());\n        objectMetadata.setContentType(file.getContentType());\n        \n        objectMetadata.getUserMetadata().put(FILE_EXTENSION, FilenameUtils.getExtension(file.getOriginalFilename()));\n        \n        return objectMetadata;\n    }\n    \n    private void initializeBucket() {\n        if (!amazonS3.doesBucketExistV2(bucketName)) {\n            amazonS3.createBucket(bucketName);\n        }\n    }\n}\n\n\n// ./springuploads3/service/StorageService.java\npackage projecteval.springuploads3.service;\n\nimport org.springframework.web.multipart.MultipartFile;\n\nimport projecteval.springuploads3.service.model.DownloadedResource;\n\npublic interface StorageService {\n    \n    String upload(MultipartFile multipartFile);\n    \n    DownloadedResource download(String id);\n}\n\n\n// ./springuploads3/service/model/DownloadedResource.java\npackage projecteval.springuploads3.service.model;\n\nimport lombok.Builder;\nimport lombok.Data;\n\nimport java.io.InputStream;\n\n@Data\n@Builder\npublic class DownloadedResource {\n    \n    private String id;\n    private String fileName;\n    private Long contentLength;\n    private InputStream inputStream;\n}\n", "num_file": 7, "num_lines": 192, "programming_language": "Java"}