file_id
stringlengths
4
9
content
stringlengths
41
35k
repo
stringlengths
7
113
path
stringlengths
5
90
token_length
int64
15
4.07k
original_comment
stringlengths
3
9.88k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
excluded
bool
2 classes
63283_8
class Solution { public boolean validUtf8(int[] data) { // Number of bytes in the current UTF-8 character int numberOfBytesToProcess = 0; // For each integer in the data array. for (int i = 0; i < data.length; i++) { // Get the binary representation. We only need the least significant 8 bits // for any given number. String binRep = Integer.toBinaryString(data[i]); binRep = binRep.length() >= 8 ? binRep.substring(binRep.length() - 8) : "00000000".substring(binRep.length() % 8) + binRep; // If this is the case then we are to start processing a new UTF-8 character. if (numberOfBytesToProcess == 0) { // Get the number of 1s in the beginning of the string. for (int j = 0; j < binRep.length(); j++) { if (binRep.charAt(j) == '0') { break; } numberOfBytesToProcess += 1; } // 1 byte characters if (numberOfBytesToProcess == 0) { continue; } // Invalid scenarios according to the rules of the problem. if (numberOfBytesToProcess > 4 || numberOfBytesToProcess == 1) { return false; } } else { // Else, we are processing integers which represent bytes which are a part of // a UTF-8 character. So, they must adhere to the pattern `10xxxxxx`. if (!(binRep.charAt(0) == '1' && binRep.charAt(1) == '0')) { return false; } } // We reduce the number of bytes to process by 1 after each integer. numberOfBytesToProcess -= 1; } // This is for the case where we might not have the complete data for // a particular UTF-8 character. return numberOfBytesToProcess == 0; } }
Gourav1695/SDE-Sheet_challenge
UTF-8.java
464
// Else, we are processing integers which represent bytes which are a part of
line_comment
en
true
63416_7
import java.util.Comparator; /** * The {@code Selection} class provides static methods for sorting an * array using selection sort. * <p> * For additional documentation, see <a href="http://algs4.cs.princeton.edu/21elementary">Section 2.1</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class Selection { // This class should not be instantiated. // private Selection() { } /** * Rearranges the array in ascending order, using the natural order. * @param a the array to be sorted */ public static void sort(Comparable[] a, String []imageList) { int n = a.length; for (int i = 0; i < n; i++) { int min = i; for (int j = i+1; j < n; j++) { if (less(a[j], a[min])) min = j; } exch(a, i, min, imageList); assert isSorted(a, 0, i); } assert isSorted(a); } /*************************************************************************** * Helper sorting functions. ***************************************************************************/ // is v < w ? private static boolean less(Comparable v, Comparable w) { return v.compareTo(w) < 0; } // is v < w ? // private static boolean less(Comparator comparator, Object v, Object w) { // return comparator.compare(v, w) < 0; // } // exchange a[i] and a[j] private static void exch(Object[] a, int i, int j, String []imageList) { Object swap = a[i]; a[i] = a[j]; a[j] = swap; // 3 lines Added for implementation [Bhekimpilo Ndhlela] String temp = imageList[i]; imageList[i] = imageList[j]; imageList[j] = temp; } /*************************************************************************** * Check if array is sorted - useful for debugging. ***************************************************************************/ // is the array a[] sorted? private static boolean isSorted(Comparable[] a) { return isSorted(a, 0, a.length - 1); } // is the array sorted from a[lo] to a[hi] private static boolean isSorted(Comparable[] a, int lo, int hi) { for (int i = lo + 1; i <= hi; i++) if (less(a[i], a[i-1])) return false; return true; } } /****************************************************************************** * Copyright 2002-2016, Robert Sedgewick and Kevin Wayne. * * This file is part of algs4.jar, which accompanies the textbook * * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. * http://algs4.cs.princeton.edu * * * algs4.jar is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * algs4.jar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with algs4.jar. If not, see http://www.gnu.org/licenses. ******************************************************************************/
BhekimpiloNdhlela/ImageSorter
src/Selection.java
934
// private static boolean less(Comparator comparator, Object v, Object w) {
line_comment
en
true
63425_0
import java.util.stream.Stream; import java.math.*; /** * Implements tail-call using Java 8 Stream. * * @author adavis */ @FunctionalInterface public interface Tail<T> { Tail<T> apply(); default boolean isDone() { return false; } default T result() { throw new UnsupportedOperationException("Not done yet."); } default T invoke() { return Stream.iterate(this, Tail::apply) .filter(Tail::isDone) .findFirst() .get() .result(); } static <T> Tail<T> done(final T value) { return new Tail<T>() { @Override public T result() { return value; } @Override public boolean isDone() { return true; } @Override public Tail<T> apply() { throw new UnsupportedOperationException("Not supported."); } }; } static BigInteger streamFactorial(int n) { return streamFactorial(BigInteger.ONE, n).invoke(); } static Tail<BigInteger> streamFactorial(BigInteger x, int n) { return () -> { switch (n) { case 1: return Tail.done(x); default: return streamFactorial(x.multiply(BigInteger.valueOf(n)), n - 1); } }; } static BigInteger stackFactorial(int n) { return stackFactorial(BigInteger.ONE, n); } static BigInteger stackFactorial(BigInteger x, int n) { if (n==1) return x; else return stackFactorial(x.multiply(BigInteger.valueOf(n)), n - 1); } public static void main(String...args) { long start = System.currentTimeMillis(); final int num = 55555; System.out.println("calculating " + num + "!"); try { stackFactorial(num); System.out.println("stack: " + (System.currentTimeMillis() - start)); } catch (StackOverflowError e) { System.err.println(e); } streamFactorial(num); System.out.println("stream: " + (System.currentTimeMillis() - start) + "ms"); } }
adamldavis/hellojava8
Tail.java
518
/** * Implements tail-call using Java 8 Stream. * * @author adavis */
block_comment
en
false
63894_3
/** *LSArray.java - Reads in Load Shedding Data from file to a binary search tree *Provides method to search through it *@ThaddeusOwl, 01-03-2020 *Use Tree(int,string) if you want to change the dataset length or input file *else use Tree() for default settings */ import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Tree{ BinarySearchTree<Data> bst; String fileName="Load_Shedding_All_Areas_Schedule_and_Map.clean.final.txt"; int n=2976; /**reads in default file with default dataset lenth into bst */ public Tree() throws FileNotFoundException{ bst = new BinarySearchTree<Data>(); Scanner file=new Scanner(new File(fileName)); for(int i=0; i<n; i++){ String line = file.nextLine(); String[] lineSplit = line.split(" ", 2); bst.insert(new Data(lineSplit[0],lineSplit[1])); } } /**reads in specified dataset length of specified file into bst */ public Tree(int a, String b) throws FileNotFoundException{ this.n=a; if(b.equals("default")){ }else{this.fileName=b;} bst = new BinarySearchTree<Data>(); Scanner file=new Scanner(new File(fileName)); for(int i=0; i<n; i++){ String line = file.nextLine(); String[] lineSplit = line.split(" ", 2); bst.insert(new Data(lineSplit[0],lineSplit[1])); } } /**Searches for the given parameter's match in the tree and outputs the corresponding area*/ public String search(String details){ Data a = new Data(details); BinaryTreeNode<Data> b = bst.find(a); if(b!=null){ return b.data.getAreas(); }else{return "Areas not found";} } /**prints all details/parameters with their corresponding areas */ public void allAreas(){ bst.inOrder(); } /**Returns number of operations counted when inserting */ public int getInsertOpCount(){ return bst.insertOpCount; } /** Returns operations counted when searching*/ public int getSearchOpCount(){ return bst.searchOpCount; } }
ThaddeusOwl/loadshedding_program
src/Tree.java
578
/**Searches for the given parameter's match in the tree and outputs the corresponding area*/
block_comment
en
false
63996_0
import java.util.concurrent.Future; public abstract interface ajj<A> extends Future<A> {} /* Location: * Qualified Name: ajj * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
reverseengineeringer/com.ubercab
src/ajj.java
71
/* Location: * Qualified Name: ajj * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
block_comment
en
true
64638_4
import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.RadioButton; import javafx.stage.Stage; import java.io.IOException; import java.util.*; /** * The controller class of the map panel * * @author Berke Muftuoglu, Jakub Mrozcek, Zhen-Chien Ong, Mairaj Khalid * @version 08/04/2021 */ public class MapPanel { //FXML components, buttons @FXML private RadioButton hillingdonButton; @FXML private RadioButton harrowButton; @FXML private RadioButton barnetButton; @FXML private RadioButton enfieldButton; @FXML private RadioButton walthamForestButton; @FXML private RadioButton redBridgeButton; @FXML private RadioButton haveringButton; @FXML private RadioButton bexleyButton; @FXML private RadioButton bromleyButton; @FXML private RadioButton croydonButton; @FXML private RadioButton suttonButton; @FXML private RadioButton kingstonUponThamesButton; @FXML private RadioButton richmondUponThamesButton; @FXML private RadioButton hounslowButton; @FXML private RadioButton ealingButton; @FXML private RadioButton brentButton; @FXML private RadioButton camdenButton; @FXML private RadioButton haringeyButton; @FXML private RadioButton islingtonButton; @FXML private RadioButton hackneyButton; @FXML private RadioButton newhamButton; @FXML private RadioButton barkingandDagenhamButton; @FXML private RadioButton greenwichButton; @FXML private RadioButton lewishamButton; @FXML private RadioButton southwarkButton; @FXML private RadioButton cityOfLondonButton; @FXML private RadioButton lambethButton; @FXML private RadioButton wandsworthButton; @FXML private RadioButton mertonButton; @FXML private RadioButton hammersmithAndFulhamButton; @FXML private RadioButton kensingtonAndChelseaButton; @FXML private RadioButton westminsterButton; @FXML private RadioButton towerHamletsButton; @FXML private Button nextPage; @FXML private Button previousPage; private ArrayList<AirbnbListing> boroughList; private ArrayList<RadioButton> mapButtons; private HashMap<String, Integer> boroughProperties; private int currentFromPrice; private int currentToPrice; /** * Constructor. */ public MapPanel() { boroughList = new ArrayList<>(); boroughProperties = new HashMap<>(); boroughProperties = Main.getBoroughNumbers(); mapButtons = new ArrayList<>(); } /** * Initialize components. */ @FXML private void initialize() { mapButtons.add(hackneyButton); mapButtons.add(cityOfLondonButton); mapButtons.add(haringeyButton); mapButtons.add(harrowButton); mapButtons.add(haveringButton); mapButtons.add(hounslowButton); mapButtons.add(hammersmithAndFulhamButton); mapButtons.add(barnetButton); mapButtons.add(barkingandDagenhamButton); mapButtons.add(bexleyButton); mapButtons.add(brentButton); mapButtons.add(bromleyButton); mapButtons.add(camdenButton); mapButtons.add(ealingButton); mapButtons.add(enfieldButton); mapButtons.add(greenwichButton); mapButtons.add(hillingdonButton); mapButtons.add(islingtonButton); mapButtons.add(kingstonUponThamesButton); mapButtons.add(kensingtonAndChelseaButton); mapButtons.add(lambethButton); mapButtons.add(lewishamButton); mapButtons.add(mertonButton); mapButtons.add(newhamButton); mapButtons.add(redBridgeButton); mapButtons.add(richmondUponThamesButton); mapButtons.add(southwarkButton); mapButtons.add(suttonButton); mapButtons.add(towerHamletsButton); mapButtons.add(walthamForestButton); mapButtons.add(wandsworthButton); mapButtons.add(westminsterButton); mapButtons.add(croydonButton); refactorButtons(); } /** * Opens a new window containing the description of the selected property. * @param e ActionEvent * @throws IOException When IO operation fails. */ @FXML private void secondWindow(ActionEvent e) throws IOException { FXMLLoader loader = new FXMLLoader(getClass().getResource("PropertyList.fxml")); Stage stage = new Stage(); stage.setScene(new Scene(loader.load())); PropertyList propController = loader.getController(); RadioButton selected = (RadioButton) e.getSource(); String boroughName = selected.getId().replace("Button", ""); ArrayList<AirbnbListing> filteredListOfProperties; filteredListOfProperties = filteredArrayList(boroughName); propController.setBoroughList(filteredListOfProperties); if (!filteredListOfProperties.isEmpty()) { stage.setTitle(filteredListOfProperties.get(0).getNeighbourhood()); stage.show(); } } /** * Assigns the properties within the price range selected by the user to a local variable. * @param input ArrayList of properties in the specified price range. */ public void setFilteredProperties(ArrayList<AirbnbListing> input) { boroughList = input; } /** * Filters through the properties in the price range with the selected borough. * @param boroughName The name of the borough. * @return ArrayList of properties. */ private ArrayList<AirbnbListing> filteredArrayList(String boroughName){ ArrayList<AirbnbListing> result = new ArrayList<>(); for(AirbnbListing value : boroughList){ if(value.getNeighbourhood().toLowerCase() .replaceAll("\\s+",""). equals(boroughName.toLowerCase(). replaceAll("\\s+",""))){ result.add(value); } } return result; } /** * Changes the stage to the next right panel. (Statistics Page) * @throws IOException When IO operation fails. */ @FXML private void goToNextPage() throws IOException{ FXMLLoader loader = new FXMLLoader(getClass().getResource("StatisticsPanel.fxml")); Stage state = (Stage) nextPage.getScene().getWindow(); state.setScene(new Scene(loader.load())); state.setTitle("Statistics Panel"); state.show(); StatisticsPanel statisticsController = loader.getController(); statisticsController.loadStatisticsPanel(boroughList); statisticsController.setPriceRange(currentFromPrice, currentToPrice); } /** * Changes the stage to the next left panel. (Welcome Panel) * @throws IOException When IO operation fails. */ @FXML private void goToPreviousPage() throws IOException{ FXMLLoader loader = new FXMLLoader(getClass().getResource("WelcomePage.fxml")); Stage state = (Stage) previousPage.getScene().getWindow(); state.setScene(new Scene(loader.load())); state.setTitle("AirBnB London Welcome Page"); state.show(); } /** * Stores the current from and to prices, as selected by the user. */ public void setPriceRange(int fromPrice, int toPrice) { currentFromPrice = fromPrice; currentToPrice = toPrice; } /** * Method called at the intiialization of the map panel to resize the buttons * based on how many properties are valid in each borough within the given price range. */ private void refactorButtons(){ Iterator it = boroughProperties.entrySet().iterator(); while (it.hasNext()) { HashMap.Entry pair = (HashMap.Entry)it.next(); String boroughName = (String) pair.getKey(); System.out.println(boroughName); int boroughCount = (Integer) pair.getValue(); for (RadioButton borough : mapButtons){ String nameOfBorough = borough.getId().replace("Button", ""); if (boroughName.toLowerCase().replaceAll("\\s+","").equals(nameOfBorough.toLowerCase().replaceAll("\\s+","")) ){ if (boroughCount >= 1750){ borough.getStyleClass().add("huge"); } else if(boroughCount >= 1250 && boroughCount < 1750){ borough.getStyleClass().add("upmid"); } else if(boroughCount >= 750 && boroughCount < 1250){ borough.getStyleClass().add("mid"); } else if (boroughCount > 250 && boroughCount < 750){ borough.getStyleClass().add("low"); } else if (boroughCount > 0 && boroughCount <= 250){ borough.getStyleClass().add("minimal"); } } } } } }
berkemuftuoglu/airbnb_clone
MapPanel.java
2,148
/** * Opens a new window containing the description of the selected property. * @param e ActionEvent * @throws IOException When IO operation fails. */
block_comment
en
true
64856_0
import java.util.Calendar; import java.util.Set; /** * A class to represent meetings * * Meetings have unique IDs, scheduled date and a list of participating contacts * * @auhor PiJ Team */ public interface Meeting { /** * Returns the id of the meeting. * * @return the id of the meeting. */ int getId(); /** * Return the date of the meeting. * * @return the date of the meeting. */ Calendar getDate(); /** * Return the details of people that attended the meeting. * * The list contains a minimum of one contact (if there were * just two people: the user and the contact) and may contain an * arbitrary number of them. * * @return the details of people that attended the meeting. */ Set<Contact> getContacts(); }
cgroc/cw-cm
Meeting.java
226
/** * A class to represent meetings * * Meetings have unique IDs, scheduled date and a list of participating contacts * * @auhor PiJ Team */
block_comment
en
false
65098_0
import java.util.*; public class giv { public static void main(String[] args) { // ques: given two binary numbers in the form of strings find whether there is a possibility of the given strings to become equal by rearranging the strings value // (0's and 1's) // 101 & 110 Scanner sc = new Scanner(System.in); String s1 = sc.nextLine(); String s2 = sc.nextLine(); } }
sharmapuneet20/100days_code_challenge
giv.java
118
// ques: given two binary numbers in the form of strings find whether there is a possibility of the given strings to become equal by rearranging the strings value
line_comment
en
true
65516_1
/** * This Pit class is use MouseAdapter to * identify each pit on the board to keep track of each pit when mouse is pressed * */ import java.util.*; import java.awt.event.MouseAdapter; public class Pit extends MouseAdapter { private int identify; /** * @param identify This is the identify parameter */ public Pit(int identify) { super(); this.identify = identify; } /** * @return This will return the identify */ public int getMouseListenerID() { return identify; } }
MarkSaweres/ManclaMakers
Pit.java
134
/** * @param identify This is the identify parameter */
block_comment
en
false
65999_2
package org.fleen.maximilian; import java.util.ArrayList; import java.util.List; import org.fleen.geom_2D.DYard; /* * A polygonal shape pierced by 1..n polygonal shapes (holes) * It can come in several varieties. Specifics are denoted by tag. * ie : * "bagel" : a polygon pierced by 1 similar polygon creating a bagel-like shape with a uniform wraparound shape * "sponge" " a polygon pierced in such a way, by 1 or more polygons, as to create a pretty irregular space * */ public class MYard extends MShape{ private static final long serialVersionUID=-726090849488448340L; /* * ################################ * CONSTRUCTORS * ################################ */ /* * the first polygon is the outer edge, the rest are holes * There is only ever at most just 1 yard in a jig-generated geometry * system, so we assign the chorus index automatically. * We use our reserved chorus index for yards */ public MYard(List<MPolygon> mpolygons,int chorusindex,List<String> tags){ super(MYARDCHORUSINDEX,tags); //create a new list to decouple param, for safety this.mpolygons=new ArrayList<MPolygon>(mpolygons);} public MYard(MPolygon outer,List<MPolygon> inner,int chorusindex,List<String> tags){ super(MYARDCHORUSINDEX,tags); this.mpolygons=new ArrayList<MPolygon>(inner.size()+1); this.mpolygons.add(outer); this.mpolygons.addAll(inner);} /* * ################################ * GEOMETRY * ################################ */ public List<MPolygon> mpolygons; public DYard getDYard(){ DYard y=new DYard(mpolygons.size()); for(MPolygon p:mpolygons) y.add(p.dpolygon); return y;} /* * ++++++++++++++++++++++++++++++++ * DETAIL SIZE * smallest distance between component polygons * ++++++++++++++++++++++++++++++++ */ Double detailsize=null; public double getDetailSize(){ if(detailsize==null)initDetailSize(); return detailsize;} private void initDetailSize(){ double smallest=Double.MAX_VALUE,test; for(MPolygon p0:mpolygons){ for(MPolygon p1:mpolygons){ if(p0!=p1){ test=p0.getDistance(p1); if(test<smallest) smallest=test;}}} detailsize=smallest;} /* * ++++++++++++++++++++++++++++++++ * DISTORTION LEVEL * the distortion level of this yard's most distorted component polygon * ++++++++++++++++++++++++++++++++ */ Double distortionlevel=null; public double getDistortionLevel(){ if(distortionlevel==null) initDistortionLevel(); return distortionlevel;} private void initDistortionLevel(){ double largest=Double.MIN_VALUE,test; for(MPolygon p:mpolygons){ test=p.getDistortionLevel(); if(test>largest) largest=test;} distortionlevel=largest;} /* * ################################ * CHORUS INDEX * ################################ */ public static final int MYARDCHORUSINDEX=Integer.MAX_VALUE; }
johnalexandergreene/Maximilian
MYard.java
840
/* * the first polygon is the outer edge, the rest are holes * There is only ever at most just 1 yard in a jig-generated geometry * system, so we assign the chorus index automatically. * We use our reserved chorus index for yards */
block_comment
en
false
66162_5
package Lab10; import java.util.ArrayList; //import java.lang.Math.*; import java.util.Arrays; import java.util.Collections; public class Solution { public static boolean debugString = false; static int earth = 6371; static double[][] schools = { {51.62497513, -8.887028344}, {51.94026835, -10.24088642}, {52.178285, -8.911617}, {52.268, -7.0945}, {52.33356304, -6.463963364}, {52.4736608, -8.4346524}, {52.86618127, -6.942840109}, {52.909722, -6.839167}, {53.1699938, -6.914885591}, {53.17901778, -7.719844209}, {53.18436564, -6.792525445}, {53.19490793, -6.670261667}, {53.1953312, -6.670313902}, {53.21575053, -6.661529073}, {53.27663886, -6.48044077}, {53.29179685, -6.698044529}, {53.31827917, -6.389738373}, {53.32421, -6.33366}, {53.33655618, -6.462126917}, {53.3579, -6.441}, {53.36407274, -6.498749584}, {53.36838522, -6.274938564}, {53.37006, -6.58208}, {53.3717, -6.3905}, {53.37484, -6.40909}, {53.3888, -6.39608}, {53.389153, -6.169552409}, {53.3945937, -6.5985973}, {53.3977573, -6.4348173}, {53.50413322, -6.387552494}, {53.52695407, -7.346691823}, {53.552384, -6.790148}, {53.64314, -6.64577}, {53.80115134, -9.512749602}, {54.1795236, -7.225463119}, {54.26405697, -6.956248402}, {54.648672, -8.112425}, {54.655499, -8.632717}, {55.09671038, -8.278657422} }; public static void main(String[] args) { // TODO Auto-generated method stub int index = getEpicentre(schools); System.out.println("The epicentre is school " + (index + 1) + ", at coordinates " + schools[index][0] + ", " + schools[index][1]); } public static int getEpicentre(double[][] arr) { double bestDistance = Double.MAX_VALUE; int bestIndex = -1; for (int i = 0; i < arr.length; i++) { ArrayList<Double> schoolArr = new ArrayList<Double>(); int x = 0; for (int j = 0; j < arr.length; j++) { if (j != i) { schoolArr.add((Double) getGPSDistance(arr[i][0], arr[j][0], arr[i][1], arr[j][1])); } } if (debugString) { System.out.println("School " + i + ":"); for (int y = 0; y < schoolArr.size(); y++) { System.out.print(Math.round(schoolArr.get(y)) + " "); } System.out.println(); } Collections.sort(schoolArr, Collections.reverseOrder()); if (debugString) { for (int y = 0; y < schoolArr.size(); y++) { System.out.print(Math.round(schoolArr.get(y)) + " "); } System.out.println(); } if (schoolArr.get(9) < bestDistance) { if (debugString) System.out.println("New best distance: " + schoolArr.get(9)); bestDistance = schoolArr.get(9); bestIndex = i; } if (debugString) System.out.println(); } return bestIndex; } public static double getGPSDistance(double lat1, double lat2, double long1, double long2) { //distance between two points on a sphere: radius * central angle //we must solve for central angle, which involves the haversine function //haversine formula: calculate the haversine of 0 (hav(0)) from the lat and long //hav(0) = hav(lat2 - lat1) + cos(lat1) * cos(lat2) * hav(long2 - long1) Double latDist = Math.toRadians(lat2 - lat1); Double latSum = Math.toRadians(lat1 + lat2); Double longDist = Math.toRadians(long2 - long1); //haversine function = sin^2(theta / 2) = (1 - cos(theta))/2 Double havLat = haversineFunction(latDist); Double havLong = haversineFunction(longDist); Double havLatSum = haversineFunction(latSum); //solve for central angle, Double centralAngle = 2 * Math.asin(Math.sqrt( (havLat + (1 - havLat - havLatSum)*havLong) )); Double distance = earth * centralAngle; return distance; } public static double haversineFunction(double theta) { // return Math.sin(theta / 2) * Math.sin(theta / 2); return Math.pow(Math.sin(theta/2), 2); } }
e-oneill/CS211
Lab10/Solution.java
1,986
//hav(0) = hav(lat2 - lat1) + cos(lat1) * cos(lat2) * hav(long2 - long1)
line_comment
en
true
66194_10
import java.util.*; class Student{ protected int rollNo; protected float percentage; Student(){ rollNo = 0; percentage=0.0f; } // SUPER CLASS CONSTRUCTOR (CHAINED IN THE TWO SUB-CLASSES) Student(int rollNo, float percentage){ this.rollNo=rollNo; this.percentage=percentage; } public void show(){ // System.out.println("Student class show() method called"); System.out.println("Roll No : "+this.rollNo); System.out.println("Percentage : "+this.percentage); } } class CollegeStudent extends Student{ protected int semester; CollegeStudent(){ super(); semester = 1;//DEFAULT INITIALISATION } CollegeStudent(int rollNo, float percentage, int semester){ super(rollNo, percentage);//CALL TO CONSTRUCTOR OF SUPER CLASS this.semester=semester; } public void show(){ super.show();//CALL TO THE SHOW OF SUPER CLASS // System.out.println("CollegeStudent class show() method called"); System.out.println("Semester : "+this.semester); } } class SchoolStudent extends Student{ protected int className; SchoolStudent(){ super(); className = 1; //DEFAULT INITIALISATION } SchoolStudent(int rollNo, float percentage,int className){ super(rollNo, percentage);//CALL TO CONSTRUCTOR OF SUPER CLASS this.className=className; } //OVER RIDDEN METHOD public void show(){ super.show();//CALL TO THE SHOW OF SUPER CLASS System.out.println("Class : "+this.className); } } class Demo{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); //creating an array of student because the super can hold the ref variable of the sub class (UPCASTING) Student students[] = new Student[5]; //TO ENTER THE OBJ AND THEIR DETAILS INTO AN ARRAY for(int i=0; i<students.length; i++){ if(i < 2){ System.out.println("\nEnter details for College Students : "); System.out.print("Enter Roll No : "); int rollNo = sc.nextInt(); System.out.print("Enter Percentage : "); float percentage = sc.nextFloat(); System.out.print("Enter Semester : "); int semester = sc.nextInt(); Student cs = new CollegeStudent(rollNo,percentage,semester); students[i]=cs; } else{ System.out.println("\nEnter details for School Students : "); System.out.print("Enter Roll No : "); int rollNo = sc.nextInt(); System.out.print("Enter Percentage : "); float percentage = sc.nextFloat(); System.out.print("Enter Class : "); int className = sc.nextInt(); Student ss = new SchoolStudent(rollNo,percentage,className); students[i]=ss; } } System.out.println("\n\n\nTO PRINT THE DETAILS OF ARRAY \n"); for(int i=0; i<students.length; i++){ if(i < 2){ System.out.println("Details for College Students : "); students[i].show(); } else{ System.out.println("Details for College Students : "); students[i].show(); } } //TO SEARCH THE ROLL NO IN THE ARRAY System.out.println("\n\n\nSEARCHING ROLL NO IN ARRAY =>\n"); System.out.println("Enter Roll no to search : "); int roll = sc.nextInt(); for(int i=0; i<students.length; i++){ if(students[i].rollNo == roll){ System.out.println("Details for Roll No "+roll+" : "); students[i].show(); } else continue; } //TO FIND THE NO OF STUDENTS WITH GRADE A (GRADE > 75) int studentCount=0; for(int i=0; i<students.length; i++){ if(students[i].percentage > 75){ studentCount++; } else continue; } System.out.println("\n\nNumber of Students with grade A : "+studentCount); } }
Anushree-Gawali/CORE-JAVA
Assignment5/Demo.java
1,015
//creating an array of student because the super can hold the ref variable of the sub class (UPCASTING)
line_comment
en
false
66213_11
package math_genealogy; import com.vaticle.typeql.lang.query.TypeQLDelete; import mjson.Json; import java.io.IOException; import java.nio.file.Files; import java.util.*; import java.nio.file.Path; import java.nio.file.Paths; import static mjson.Json.read; import com.vaticle.typedb.client.api.TypeDBClient; import com.vaticle.typedb.client.api.TypeDBSession; import com.vaticle.typedb.client.api.TypeDBTransaction; import com.vaticle.typedb.client.TypeDB; import com.vaticle.typeql.lang.TypeQL; import static com.vaticle.typeql.lang.TypeQL.*; import com.vaticle.typeql.lang.query.TypeQLInsert; class DataMigrator { public static int sz=0; public static int getId(Json file, int idx) { return file.at("nodes").at(idx).at("id").asInteger(); } public static String getName(Json file, int idx) { return file.at("nodes").at(idx).at("name").asString(); } public static String getSchool(Json file, int idx) { return file.at("nodes").at(idx).at("school").asString(); } public static int getYear(Json file, int idx) { if (!file.at("nodes").at(idx).at("year").isNull()) return file.at("nodes").at(idx).at("year").asInteger(); else return 0; } public static String getSpeciality(Json file, int idx) { if (!file.at("nodes").at(idx).at("subject").isNull()) { return file.at("nodes").at(idx).at("subject").asString(); } else return "Unknown"; } public static List getAdvisors(Json file, int idx) { List<Object> ls = file.at("nodes").at(idx).at("advisors").asList(); return ls; } public static void instantiateMathematicians(TypeDBSession session, Json file) { for (int z = 0; z < sz; z++) { try (TypeDBTransaction writeTransaction = session.transaction(TypeDBTransaction.Type.WRITE)) { // Insert a person using a WRITE transaction TypeQLInsert insertQuery = TypeQL.insert (var("x").isa("mathematician") .has("id", getId(file, z)) .has("name", getName(file, z)) .has("year_of_degree", getYear(file, z)) ); writeTransaction.query().insert(insertQuery); // to persist changes, a write-transaction must always be committed (closed) writeTransaction.commit(); } } } public static void instantiateSchools(TypeDBSession session, Json file) { Set<String> school_set = new HashSet<String>(); for (int z = 0; z < sz; z++) { try (TypeDBTransaction writeTransaction = session.transaction(TypeDBTransaction.Type.WRITE)) { // Insert a person using a WRITE transaction String school = getSchool(file, z); if (!school_set.contains(school)) { school_set.add(school); TypeQLInsert insertQuery = TypeQL.insert (var("x").isa("school") .has("name", school) ); writeTransaction.query().insert(insertQuery); writeTransaction.commit(); } } } } public static void instantiateSpecialities(TypeDBSession session, Json file) { Set<String> speciality_set = new HashSet<String>(); for (int z = 0; z < sz; z++) { try (TypeDBTransaction writeTransaction = session.transaction(TypeDBTransaction.Type.WRITE)) { // Insert a person using a WRITE transaction String speciality = getSpeciality(file, z); if (!speciality_set.contains(speciality)) { speciality_set.add(speciality); TypeQLInsert insertQuery = TypeQL.insert (var("x").isa("speciality") .has("name", speciality) ); writeTransaction.query().insert(insertQuery); writeTransaction.commit(); } } } } public static void instantiateRelationships(TypeDBSession session, Json file) { Set<ArrayList<String>> offerSet = new HashSet<>(); for (int z = 0; z < sz; z++) { int m_id = getId(file, z); String school = getSchool(file, z); //add studentship relationship try (TypeDBTransaction writeTransaction = session.transaction(TypeDBTransaction.Type.WRITE)) { TypeQLInsert insertQuery = TypeQL.match( var("m1").isa("mathematician").has("id", m_id), var("s").isa("school").has("name", school) ).insert( var("new-studentship").rel("student", "m1").rel("school", "s").isa("studentship") ); writeTransaction.query().insert(insertQuery); writeTransaction.commit(); } //offer relationship String speciality = getSpeciality(file, z); try (TypeDBTransaction writeTransaction = session.transaction(TypeDBTransaction.Type.WRITE)) { ArrayList<String> a = new ArrayList<>(); a.add(school); a.add("mathematics"); a.add(speciality); if (!offerSet.contains(a)) { TypeQLInsert insertQuery = TypeQL.match( var("s").isa("school").has("name", school), var("s2").isa("subject").has("name", "mathematics"), var("s3").isa("speciality").has("name", speciality) ).insert( var("new-offer").rel("school", "s").rel("subject", "s2").rel("speciality", "s3").isa("offer") ); offerSet.add(a); writeTransaction.query().insert(insertQuery); writeTransaction.commit(); System.out.println("Offer Relationship added\n" + " school: " + school + " speciality = " + speciality); System.out.println("size = " + offerSet.size()); } } //add mastery relationship try (TypeDBTransaction writeTransaction = session.transaction(TypeDBTransaction.Type.WRITE)) { TypeQLInsert insertQuery = TypeQL.match( var("m").isa("mathematician").has("id", m_id), var("s").isa("speciality").has("name", speciality) ).insert( var("new-mastery").rel("master", "m").rel("speciality", "s").isa("mastery") ); writeTransaction.query().insert(insertQuery); writeTransaction.commit(); } List advisor_list = getAdvisors(file, z); int len = advisor_list.size(); //add research relationship for (int j = 0; j < len; j++) { java.lang.Long a_id = (java.lang.Long) advisor_list.get(j); //research relationship try (TypeDBTransaction writeTransaction = session.transaction(TypeDBTransaction.Type.WRITE)) { TypeQLInsert insertQuery = TypeQL.match( var("m1").isa("mathematician").has("id", m_id), var("m2").isa("mathematician").has("id", a_id), var("s").isa("school").has("name", school) ).insert( var("new-research").rel("advisor", "m2").rel("advisee", "m1").rel("school", "s").isa("research") ); writeTransaction.query().insert(insertQuery); writeTransaction.commit(); } } } } public static void instantiateSubjects(TypeDBSession session, Json file) { try (TypeDBTransaction writeTransaction = session.transaction(TypeDBTransaction.Type.WRITE)) { // Insert a person using a WRITE transaction TypeQLInsert insertQuery = TypeQL.insert (var("x").isa("subject") .has("name", "mathematics") ); writeTransaction.query().insert(insertQuery); writeTransaction.commit(); } } private static void defineSchema(String databaseName, String schemaFileName, TypeDBClient client) { try (TypeDBSession session = client.session(databaseName, TypeDBSession.Type.SCHEMA)) { try (TypeDBTransaction transaction = session.transaction(TypeDBTransaction.Type.WRITE)) { String typeQLSchemaQuery = Files.readString(Paths.get(schemaFileName)); System.out.println("Defining schema..."); transaction.query().define(TypeQL.parseQuery(typeQLSchemaQuery).asDefine()); transaction.commit(); } catch (IOException e) { throw new RuntimeException(e); } } } public static void main(String[] args) { Path filePath=Paths.get("datalite.json"); TypeDBClient client = TypeDB.coreClient("localhost:1729"); String contents=""; try { contents = Files.readString(filePath); } catch(IOException e) { System.out.println("IO Exception in file: "+e.getMessage()); e.printStackTrace(); } Json file=read(contents); List mylist=file.at("nodes").asList(); sz=mylist.size(); System.out.println("Size = "+sz); String dbName="onboarding"; String schemaFileName="schema.tql"; if (client.databases().contains(dbName)) { client.databases().get(dbName).delete(); } client.databases().create(dbName); defineSchema(dbName, schemaFileName, client); try (TypeDBSession session = client.session(dbName, TypeDBSession.Type.DATA)) { //first purge existing data try (TypeDBTransaction writeTransaction = session.transaction(TypeDBTransaction.Type.WRITE)) { TypeQLDelete query = TypeQL.match( var("p").isa("thing") ).delete(var("p").isa("thing")); writeTransaction.query().delete(query); // to persist changes, a write-transaction must always be committed (closed) writeTransaction.commit(); } instantiateMathematicians(session, file); instantiateSchools(session, file); instantiateSubjects(session, file); instantiateSpecialities(session, file); instantiateRelationships(session, file); } client.close(); } }
shiladitya-mukherjee/math-genealogy-typedb
DataMigrator.java
2,474
// to persist changes, a write-transaction must always be committed (closed)
line_comment
en
false
66267_7
package rsn170330.sp07; import java.util.Set; import java.util.HashSet; import java.util.Random; /** * CS 5V81.001: Implementation of Data Structures and Algorithms * Short Project SP07: Comparison of Hashing Implementations * @author Rahul Nalawade * * Date: January 4, 2019 */ public class HashingDriver2 { public static Random random = new Random(); public static int numTrials = 10; /** * Calculate distinct elements in an array * @param arr: Array of Integers which may or may not have duplicates. * @return: returns the count of distinct elements in the provided array. */ public static int distinctElements(Integer[] arr){ Set<Integer> hs = new HashSet<>(); for (Integer e : arr) { hs.add(e); } return hs.size(); } public static void main(String[] args) { int Million = 1000000; int n = Million; int choice = 0; long result = 0; if (args.length > 0) { n = Integer.parseInt(args[0]); } if (args.length > 1) { choice = Integer.parseInt(args[1]); } Integer[] arr = new Integer[n]; for (int i = 0; i < n; i++) { arr[i] = random.nextInt(n); } Timer timer = new Timer(); switch (choice) { case 1: //numTrials = 1; // Uncomment to Test for (int i = 0; i < numTrials; i++) { Shuffle.shuffle(arr); result = DoubleHashing.distinctElements(arr); } //System.out.println("Double Hashing: " + result); break; case 2: //numTrials = 1; // Uncomment to Test for (int i = 0; i < numTrials; i++) { Shuffle.shuffle(arr); result = RobinHood.distinctElements(arr); } //System.out.println("Robin Hood Hashing: " + result); break; case 3: //numTrials = 1; // Uncomment to Test for (int i = 0; i < numTrials; i++) { Shuffle.shuffle(arr); result = Cuckoo.distinctElements(arr); } //System.out.println("Cuckoo Hashing: " + result); break; default: //numTrials = 1; for (int i = 0; i < numTrials; i++) { Shuffle.shuffle(arr); result = distinctElements(arr); } //System.out.println("Java HashSet: " + result); break; } timer.end(); timer.scale(numTrials); System.out.println("Choice: " + choice + "\n" + timer); } /** * Shuffle the elements of an array arr[from..to] randomly * @author rbk : based on algorithm described in CLRS book */ public static class Shuffle { public static void shuffle(int[] arr) { shuffle(arr, 0, arr.length - 1); } public static <T> void shuffle(T[] arr) { shuffle(arr, 0, arr.length - 1); } public static void shuffle(int[] arr, int from, int to) { int n = to - from + 1; for (int i = 1; i < n; i++) { int j = random.nextInt(i); swap(arr, i + from, j + from); } } public static <T> void shuffle(T[] arr, int from, int to) { int n = to - from + 1; Random random = new Random(); for (int i = 1; i < n; i++) { int j = random.nextInt(i); swap(arr, i + from, j + from); } } static void swap(int[] arr, int x, int y) { int tmp = arr[x]; arr[x] = arr[y]; arr[y] = tmp; } static <T> void swap(T[] arr, int x, int y) { T tmp = arr[x]; arr[x] = arr[y]; arr[y] = tmp; } public static <T> void printArray(T[] arr, String message) { printArray(arr, 0, arr.length - 1, message); } public static <T> void printArray(T[] arr, int from, int to, String message) { System.out.print(message); for (int i = from; i <= to; i++) { System.out.print(" " + arr[i]); } System.out.println(); } } }
rahul1947/SP07-Comparison-of-Hashing-Implementations
HashingDriver2.java
1,273
//System.out.println("Cuckoo Hashing: " + result);
line_comment
en
true
66429_5
/* * Copyright 2015 Ben Manes. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.benmanes.caffeine.cache; import java.lang.ref.ReferenceQueue; import org.checkerframework.checker.index.qual.NonNegative; import org.checkerframework.checker.nullness.qual.Nullable; import com.github.benmanes.caffeine.cache.AccessOrderDeque.AccessOrder; import com.github.benmanes.caffeine.cache.WriteOrderDeque.WriteOrder; import com.google.errorprone.annotations.concurrent.GuardedBy; /** * An entry in the cache containing the key, value, weight, access, and write metadata. The key * or value may be held weakly or softly requiring identity comparison. * * @author [email protected] (Ben Manes) */ abstract class Node<K, V> implements AccessOrder<Node<K, V>>, WriteOrder<Node<K, V>> { /** Return the key or {@code null} if it has been reclaimed by the garbage collector. */ @Nullable public abstract K getKey(); /** * Returns the reference that the cache is holding the entry by. This is either the key if * strongly held or a {@link java.lang.ref.WeakReference} to that key. */ public abstract Object getKeyReference(); /** Return the value or {@code null} if it has been reclaimed by the garbage collector. */ @Nullable public abstract V getValue(); /** * Returns the reference to the value. This is either the value if strongly held or a * {@link java.lang.ref.Reference} to that value. */ public abstract Object getValueReference(); /** * Sets the value, which may be held strongly, weakly, or softly. This update may be set lazily * and rely on the memory fence when the lock is released. */ @GuardedBy("this") public abstract void setValue(V value, @Nullable ReferenceQueue<V> referenceQueue); /** * Returns {@code true} if the given objects are considered equivalent. A strongly held value is * compared by equality and a weakly or softly held value is compared by identity. */ public abstract boolean containsValue(Object value); /** Returns the weight of this entry from the entry's perspective. */ @NonNegative @GuardedBy("this") public int getWeight() { return 1; } /** Sets the weight from the entry's perspective. */ @GuardedBy("this") public void setWeight(@NonNegative int weight) {} /** Returns the weight of this entry from the policy's perspective. */ @NonNegative // @GuardedBy("evictionLock") public int getPolicyWeight() { return 1; } /** Sets the weight from the policy's perspective. */ // @GuardedBy("evictionLock") public void setPolicyWeight(@NonNegative int weight) {} /* --------------- Health --------------- */ /** If the entry is available in the hash-table and page replacement policy. */ public abstract boolean isAlive(); /** * If the entry was removed from the hash-table and is awaiting removal from the page * replacement policy. */ @GuardedBy("this") public abstract boolean isRetired(); /** If the entry was removed from the hash-table and the page replacement policy. */ @GuardedBy("this") public abstract boolean isDead(); /** Sets the node to the <tt>retired</tt> state. */ @GuardedBy("this") public abstract void retire(); /** Sets the node to the <tt>dead</tt> state. */ @GuardedBy("this") public abstract void die(); /* --------------- Variable order --------------- */ /** Returns the variable expiration time, in nanoseconds. */ public long getVariableTime() { return 0L; } /** * Sets the variable expiration time in nanoseconds. This update may be set lazily and rely on the * memory fence when the lock is released. */ public void setVariableTime(long time) {} /** * Atomically sets the variable time to the given updated value if the current value equals the * expected value and returns if the update was successful. */ public boolean casVariableTime(long expect, long update) { throw new UnsupportedOperationException(); } // @GuardedBy("evictionLock") public Node<K, V> getPreviousInVariableOrder() { throw new UnsupportedOperationException(); } // @GuardedBy("evictionLock") public void setPreviousInVariableOrder(@Nullable Node<K, V> prev) { throw new UnsupportedOperationException(); } // @GuardedBy("evictionLock") public Node<K, V> getNextInVariableOrder() { throw new UnsupportedOperationException(); } // @GuardedBy("evictionLock") public void setNextInVariableOrder(@Nullable Node<K, V> prev) { throw new UnsupportedOperationException(); } /* --------------- Access order --------------- */ public static final int WINDOW = 0; public static final int PROBATION = 1; public static final int PROTECTED = 2; /** Returns if the entry is in the Window or Main space. */ public boolean inWindow() { return getQueueType() == WINDOW; } /** Returns if the entry is in the Main space's probation queue. */ public boolean inMainProbation() { return getQueueType() == PROBATION; } /** Returns if the entry is in the Main space's protected queue. */ public boolean inMainProtected() { return getQueueType() == PROTECTED; } /** Sets the status to the Window queue. */ public void makeWindow() { setQueueType(WINDOW); } /** Sets the status to the Main space's probation queue. */ public void makeMainProbation() { setQueueType(PROBATION); } /** Sets the status to the Main space's protected queue. */ public void makeMainProtected() { setQueueType(PROTECTED); } /** Returns the queue that the entry's resides in (window, probation, or protected). */ public int getQueueType() { return WINDOW; } /** Set queue that the entry resides in (window, probation, or protected). */ public void setQueueType(int queueType) { throw new UnsupportedOperationException(); } /** Returns the time that this entry was last accessed, in ns. */ public long getAccessTime() { return 0L; } /** * Sets the access time in nanoseconds. This update may be set lazily and rely on the memory fence * when the lock is released. */ public void setAccessTime(long time) {} @Override // @GuardedBy("evictionLock") public @Nullable Node<K, V> getPreviousInAccessOrder() { return null; } @Override // @GuardedBy("evictionLock") public void setPreviousInAccessOrder(@Nullable Node<K, V> prev) { throw new UnsupportedOperationException(); } @Override // @GuardedBy("evictionLock") public @Nullable Node<K, V> getNextInAccessOrder() { return null; } @Override // @GuardedBy("evictionLock") public void setNextInAccessOrder(@Nullable Node<K, V> next) { throw new UnsupportedOperationException(); } /* --------------- Write order --------------- */ /** Returns the time that this entry was last written, in ns. */ public long getWriteTime() { return 0L; } /** * Sets the write-time in nanoseconds. This update may be set lazily and rely on the memory fence * when the lock is released. */ public void setWriteTime(long time) {} /** * Atomically sets the write-time to the given updated value if the current value equals the * expected value and returns if the update was successful. */ public boolean casWriteTime(long expect, long update) { throw new UnsupportedOperationException(); } @Override // @GuardedBy("evictionLock") public @Nullable Node<K, V> getPreviousInWriteOrder() { return null; } @Override // @GuardedBy("evictionLock") public void setPreviousInWriteOrder(@Nullable Node<K, V> prev) { throw new UnsupportedOperationException(); } @Override // @GuardedBy("evictionLock") public @Nullable Node<K, V> getNextInWriteOrder() { return null; } @Override // @GuardedBy("evictionLock") public void setNextInWriteOrder(@Nullable Node<K, V> next) { throw new UnsupportedOperationException(); } @Override @SuppressWarnings("GuardedBy") public final String toString() { return String.format("%s=[key=%s, value=%s, weight=%d, queueType=%,d, accessTimeNS=%,d, " + "writeTimeNS=%,d, varTimeNs=%,d, prevInAccess=%s, nextInAccess=%s, prevInWrite=%s, " + "nextInWrite=%s]", getClass().getSimpleName(), getKey(), getValue(), getWeight(), getQueueType(), getAccessTime(), getWriteTime(), getVariableTime(), getPreviousInAccessOrder() != null, getNextInAccessOrder() != null, getPreviousInWriteOrder() != null, getNextInWriteOrder() != null); } }
rohankumardubey/faker
Node.java
2,286
/** * Returns the reference to the value. This is either the value if strongly held or a * {@link java.lang.ref.Reference} to that value. */
block_comment
en
true
66431_0
import java.sql.Timestamp; import java.util.Calendar; /** * A page in memory. */ public class Page { private final int number; private int referencedPage; private Process referencedProcess; private int useCount; private int oldestRef; private Timestamp time; public Page(int number) { this.number = number; referencedPage = -1; useCount = 0; oldestRef = -1; time = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime()); } public Timestamp getTime() { return time; } public void setTime(Timestamp time) { this.time = time; } public void setOldestRef(int o) { this.oldestRef = 0; } public int getOldestRef() { return this.oldestRef; } /** * Gets the page number. * @return the page number */ public int getNumber() { return number; } /** * Gets the page number of the process that this page is referencing. * @return the referenced page number */ public int getReferencedPage() { return referencedPage; } /** * Sets the page number of the process' page that this page is referencing. * @param referencedPage the page number of the referenced page */ public void setReferencedPage(int referencedPage) { this.referencedPage = referencedPage; } /** * Sets the process that this page is now referencing. * @param process the process to reference */ public void setReferencedProcess(Process process) { this.referencedProcess = process; useCount = 1; incrementOldestRef(); setTime(new java.sql.Timestamp(Calendar.getInstance().getTime().getTime())); } /** * Gets the process that this page is currently referencing. * @return the process that is referenced */ public Process getReferencedProcess() { return referencedProcess; } public int getUseCount() { return useCount; } public void incrementUseCount() { useCount++; } public void incrementOldestRef() { oldestRef++; } @Override public boolean equals(Object o) { if (!(o instanceof Page)) return false; if (o == this) return true; Page page = (Page) o; return page.getNumber() == this.getNumber(); } }
gdhuper/CS149-HW4
Page.java
563
/** * A page in memory. */
block_comment
en
true
66530_2
import java.util.ArrayList; /** * @author Berk Gulay [email protected] * * @since 2016.04.12 * */ public class Game { Players player1=new Player1("Player 1",15000,1); Players player2=new Player2("Player 2",15000,1); Banker banker=new Banker("Banker",100000,0); Cards chances = new Chance(); Cards communityChests = new CommunityChest(); Lands lands = new Lands(); RailRoads railRoads = new RailRoads(); Companies companies = new Companies(); ListJsonReader cards=new ListJsonReader(); PropertyJsonReader properties=new PropertyJsonReader(); Output output=new Output(); private Boolean bankruptController=false; /** * * This is the getter of bankrupt controller boolean value * @return Bankrupt Controller for this game's end situation */ public Boolean getBankruptController() {return bankruptController;} /** * This is the setter of bankrupt controller boolean value */ public void setBankruptController(Boolean bankruptController) {this.bankruptController = bankruptController;} /** * * This method is checking the players position and directing him/her to the right function or doing some operations according to place and money * * @since 2016.04.12 * * @param p This method takes an player which is playing at that turn * @param dice This method takes an dice number as integer * @param game This is the game object which we have been playing */ public void game(Players p,int dice,Game game){ int initialPosition=p.getPosition(); Players p1; Players p2; if(p.getName().equals("Player 1")){p1=p;p2=player2;} else{p1=player1;p2=p;} if(p.getPosition()==11){ if(p.getCounter()==3){ p.setCounter(0);; p.setPosition(11+dice); output.writeMethod((action(p,ps,dice,game)));//OTHER PART } else{ p.setCounter(p.getCounter()+1);; output.writeMethod(p.getName()+"\t"+dice+"\t"+p.getPosition()+"\t"+p1.getMoney()+"\t"+p2.getMoney()+"\t"+p.getName()+" in jail "+"(count="+p.getCounter()+")"); } } else{ p.setPosition((p.getPosition()+dice)%40); if(p.getPosition()==0){p.setPosition(40);} if(p.getPosition()==11){ output.writeMethod(p.getName()+"\t"+dice+"\t"+p.getPosition()+"\t"+p1.getMoney()+"\t"+p2.getMoney()+"\t"+p.getName()+" went to jail"); } else if(properties.getLandsNumber().contains(p.getPosition())){ if(initialPosition>p.getPosition()){ p.setMoney(p.getMoney()+200); banker.setMoney(banker.getMoney()-200); } output.writeMethod(lands.propertyFunc(p, ps, banker, p.getPosition(), dice, properties.getLandsNumber(), properties.getLandsName(), properties.getLandsCost(),game)); } else if(properties.getRailRoadsNumber().contains(p.getPosition())){ if(initialPosition>p.getPosition()){ p.setMoney(p.getMoney()+200); banker.setMoney(banker.getMoney()-200); } output.writeMethod(railRoads.propertyFunc(p, ps, banker, p.getPosition(), dice, properties.getRailRoadsNumber(), properties.getRailRoadsName(), properties.getRailRoadsCost(),game)); } else if(properties.getCompaniesNumber().contains(p.getPosition())){ if(initialPosition>p.getPosition()){ p.setMoney(p.getMoney()+200); banker.setMoney(banker.getMoney()-200); } output.writeMethod(companies.propertyFunc(p, ps, banker, p.getPosition(), dice, properties.getCompaniesNumber(), properties.getCompaniesName(), properties.getCompaniesCost(),game)); } else if(p.getPosition()==8 || p.getPosition()==23 || p.getPosition()==37){ if(initialPosition>p.getPosition()){ p.setMoney(p.getMoney()+200); banker.setMoney(banker.getMoney()-200); } chances.cardFunc(p,ps, banker,dice, cards.getChances(),output,game); } else if(p.getPosition()==3 || p.getPosition()==18 || p.getPosition()==34){ if(initialPosition>p.getPosition()){ p.setMoney(p.getMoney()+200); banker.setMoney(banker.getMoney()-200); } communityChests.cardFunc(p, ps, banker,dice, cards.getCommunityChests(),output,game); } else if(p.getPosition()==5 || p.getPosition()==39){ if(initialPosition>p.getPosition()){ p.setMoney(p.getMoney()+200); banker.setMoney(banker.getMoney()-200); } if(p.getMoney()<100){ output.writeMethod(p.getName()+"\t"+dice+"\t"+p.getPosition()+"\t"+p1.getMoney()+"\t"+p2.getMoney()+"\t"+p.getName()+" goes bankrupt!"); setBankruptController(true); } else{ p.setMoney(p.getMoney()-100); banker.setMoney(banker.getMoney()+100); output.writeMethod(p.getName()+"\t"+dice+"\t"+p.getPosition()+"\t"+p1.getMoney()+"\t"+p2.getMoney()+"\t"+p.getName()+" paid tax"); } } else if(p.getPosition()==21){ if(initialPosition>p.getPosition()){ p.setMoney(p.getMoney()+200); banker.setMoney(banker.getMoney()-200); } output.writeMethod(p.getName()+"\t"+dice+"\t"+p.getPosition()+"\t"+p1.getMoney()+"\t"+p2.getMoney()+"\t"+p.getName()+" is in Free Parking"); } else if(p.getPosition()==1){ if(initialPosition>p.getPosition()){ p.setMoney(p.getMoney()+200); banker.setMoney(banker.getMoney()-200); } output.writeMethod(p.getName()+"\t"+dice+"\t"+p.getPosition()+"\t"+p1.getMoney()+"\t"+p2.getMoney()+"\t"+p.getName()+" is in Go Square"); } else if(p.getPosition()==31){ p.setPosition(11); //JAIL output.writeMethod(p.getName()+"\t"+dice+"\t"+p.getPosition()+"\t"+p1.getMoney()+"\t"+p2.getMoney()+"\t"+p.getName()+" went to jail"); } } } /** * * This method is checking the players position after the jail part and directing him/her to the right function or doing some operations according to place and money * * @since 2016.04.12 * * @param p This method takes an player which is playing at that turn * @param po This method takes an player which is not playing at that turn(enemy player) * @param dice This method takes an dice number as integer * @param game This is the game object which we have been playing * * @return It returns an output string for write it in game function */ public String action(Players p,Players po,int dice,Game game){ int initialPosition=p.getPosition(); Players p1; Players p2; if(p.getName().equals("Player 1")){p1=p;p2=po;} else{p1=po;p2=p;} if(properties.getLandsNumber().contains(p.getPosition())){ if(initialPosition>p.getPosition()){ p.setMoney(p.getMoney()+200); banker.setMoney(banker.getMoney()-200); } return(lands.propertyFunc(p, po, banker, p.getPosition(), dice, properties.getLandsNumber(), properties.getLandsName(), properties.getLandsCost(),game)); } else if(properties.getRailRoadsNumber().contains(p.getPosition())){ if(initialPosition>p.getPosition()){ p.setMoney(p.getMoney()+200); banker.setMoney(banker.getMoney()-200); } return(railRoads.propertyFunc(p, po, banker, p.getPosition(), dice, properties.getRailRoadsNumber(), properties.getRailRoadsName(), properties.getRailRoadsCost(),game)); } else if(properties.getCompaniesNumber().contains(p.getPosition())){ if(initialPosition>p.getPosition()){ p.setMoney(p.getMoney()+200); banker.setMoney(banker.getMoney()-200); } return(companies.propertyFunc(p, po, banker, p.getPosition(), dice, properties.getCompaniesNumber(), properties.getCompaniesName(), properties.getCompaniesCost(),game)); } else if(p.getPosition()==23){ if(initialPosition>p.getPosition()){ p.setMoney(p.getMoney()+200); banker.setMoney(banker.getMoney()-200); } chances.cardFunc(p,po, banker,dice, cards.getChances(),output,game); } else if(p.getPosition()==18){ if(initialPosition>p.getPosition()){ p.setMoney(p.getMoney()+200); banker.setMoney(banker.getMoney()-200); } communityChests.cardFunc(p, po, banker,dice, cards.getCommunityChests(),output,game); } else if(p.getPosition()==21){ if(initialPosition>p.getPosition()){ p.setMoney(p.getMoney()+200); banker.setMoney(banker.getMoney()-200); } return(p.getName()+"\t"+dice+"\t"+p.getPosition()+"\t"+p1.getMoney()+"\t"+p2.getMoney()+"\t"+p.getName()+" is in Free Parking"); } return ""; } /** * * This method is checking the players name and taking the right dice number for this player and directing the player to game function for operations * * @since 2016.04.12 * * @param commandArray This method takes an array list that includes the command lines for this game * @param game This is the game object which we have been playing */ public void play(ArrayList<String> commandArray,Game game){ cards.listJsonReader("list.json"); properties.propertyJsonReader("property.json"); for (int i=0;i<commandArray.size();i++){ if(bankruptController){} else{ if (commandArray.get(i).split(";")[0].equals("Player 1")){ game(player1,Integer.parseInt(commandArray.get(i).split(";")[1]),game); } else if(commandArray.get(i).split(";")[0].equals("Player 2")){ game(player2,Integer.parseInt(commandArray.get(i).split(";")[1]),game); } else{ String winner=""; if (player1.getMoney()<player2.getMoney()){winner+="Winner " + player2.getName();} else if(player1.getMoney()>player2.getMoney()){winner+="Winner " + player1.getName();} else if(player1.getMoney()==player2.getMoney()){winner+=player1.getName()+" is draw with "+player2.getName();} output.writeMethod("--------------------------------------------------------------------------------------------------------------------------------"); output.writeMethod(player1.show()); output.writeMethod(player2.show()); output.writeMethod(banker.show()); output.writeMethod(winner); output.writeMethod("--------------------------------------------------------------------------------------------------------------------------------"); } } } String winner=""; if (player1.getMoney()<player2.getMoney()){winner+="Winner " + player2.getName();} else if(player1.getMoney()>player2.getMoney()){winner+="Winner " + player1.getName();} else if(player1.getMoney()==player2.getMoney()){winner+=player1.getName()+" is draw with "+player2.getName();} output.writeMethod("--------------------------------------------------------------------------------------------------------------------------------"); output.writeMethod(player1.show()); output.writeMethod(player2.show()); output.writeMethod(banker.show()); output.writeMethod(winner); } }
berkgulay/monopoly
src/Game.java
3,320
/** * This is the setter of bankrupt controller boolean value */
block_comment
en
false
66574_0
/* * DANH SÁCH DOANH NGHIỆP NHẬN SINH VIÊN THỰC TẬP - 1 * @since 04/12/2021 * @author TaDuy */ import java.util.ArrayList; import java.util.Comparator; import java.util.Scanner; public class J05028 { static class Company { String id; String name; int slot; public Company(String name, String fullName, int numberOfStudent) { this.id = name; this.name = fullName; this.slot = numberOfStudent; } public int getSlot() { return slot; } public String getId() { return id; } @Override public String toString() { return id + " " + name + " " + slot; } } public static void main(String args[]) { Scanner sc = new Scanner(System.in); ArrayList<Company> companies = new ArrayList<>(); int t = sc.nextInt(); sc.nextLine(); while (t-- > 0) { String name = sc.nextLine(); String fullName = sc.nextLine(); int numberOfStudent = Integer.parseInt(sc.nextLine()); companies.add(new Company(name, fullName, numberOfStudent)); } companies.sort(Comparator.comparing(Company::getSlot).reversed() .thenComparing(Company::getId)); for (Company c : companies) { System.out.println(c); } } }
DuyTaDinh/Code.ptit.TaDuy
Java/J05028.java
361
/* * DANH SÁCH DOANH NGHIỆP NHẬN SINH VIÊN THỰC TẬP - 1 * @since 04/12/2021 * @author TaDuy */
block_comment
en
true
66724_2
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class baby here. * * @author (arteddy) * @version (a version number or a date) */ public class baby extends Hero { /** * Act - do whatever the baby wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public baby() { setRotation(180); } public baby(int speed) { setRotation(180); this.speed = speed; } private int speed = 5; public void act() { move(speed); edge(); } public void edge() { if(isAtEdge()) { getWorld().removeObject(this); } } }
arteddybukit/PROJECT-OOP
ALIEN_A/baby.java
209
/** * Act - do whatever the baby wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */
block_comment
en
true
66819_0
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; /** * CCC '06 S1 - Maternity * Question type: Implementation * 3/3 on DMOJ * @author Tommy Pang */ public class CCC06S1 { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static String mother, farther; public static void main(String[] args) throws IOException { mother = br.readLine(); farther = br.readLine(); int N = Integer.parseInt(br.readLine()); for (int i = 0; i < N; i++) { String s = br.readLine(); evaluate(mother, farther, s); } } static void evaluate(String a, String b, String s){ for (int i = 0; i < 5; i++) { switch (s.charAt(i)){ case 'A': if (!a.contains("A") && !b.contains("A")){ System.out.println("Not their baby!"); return; } break; case 'a': if (!check(s, "a")) { System.out.println("Not their baby!"); return; } break; case 'B': if (!a.contains("B") && !b.contains("B")){ System.out.println("Not their baby!"); return; } break; case 'b': if (!check(s, "b")) { System.out.println("Not their baby!"); return; } break; case 'C': if (!a.contains("C") && !b.contains("C")){ System.out.println("Not their baby!"); return; } break; case 'c': if (!check(s, "c")) { System.out.println("Not their baby!"); return; } break; case 'D': if (!a.contains("D") && !b.contains("D")){ System.out.println("Not their baby!"); return; } break; case 'd': if (!check(s, "d")) { System.out.println("Not their baby!"); return; } break; case 'E': if (!a.contains("E") && !b.contains("E")){ System.out.println("Not their baby!"); return; } break; case 'e': if (!check(s, "e")) { System.out.println("Not their baby!"); return; } break; } } System.out.println("Possible baby."); } static boolean check(String s, String letter){ return mother.contains(letter) && farther.contains(letter); } }
TommyPang/CCC-Solutions
CCC06S1.java
684
/** * CCC '06 S1 - Maternity * Question type: Implementation * 3/3 on DMOJ * @author Tommy Pang */
block_comment
en
true
66965_0
import java.awt.*; /** * Created by Alberto on 11/11/2015. */ public class Plant { private int energy; //how much energy it will give to the herbivore private int life; //how much life before the plant dies private Point location; public Plant() { energy = (int)(Math.random() * 20); life = 5; location = new Point(); } public Plant(int x, int y) { energy = (int)(Math.random() * 20); life = 5; location = new Point(x, y); } public int getEnergy() { return energy; } public int getLife() { return life; } public Point getLocation() { return location; } public void decreaseLife() { life--; } }
afranco07/animalSimulation
Plant.java
215
/** * Created by Alberto on 11/11/2015. */
block_comment
en
true
67016_5
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Slilder here. * * @author (your name) * @version (a version number or a date) */ public class Slider{ public static final int CONSUMER_BAR = 0; public static final int MANA_BAR = 1; public static final int ENERGY_BAR = 2; public static final int SETTING_BAR = 3; private boolean hideAtMax; private int maxVal; private int currVal; private double scale; private int width; private int height; private int borderThickness; private Color borderColor; private Color fillColor; private Color emptyColor; public Slider(int width, int height, int maxVal, int preset){ this(width, height, maxVal); switch(preset){ case CONSUMER_BAR: fillColor = new Color(255,194,15,255); //golden yellow borderThickness = 3; break; case MANA_BAR: fillColor = Color.BLUE; borderThickness = 1; break; default: break; } } public Slider(int width, int height, int maxVal){ borderThickness = 0; this.width = width; this.height = height; //currVal is set default to max this.maxVal = maxVal; this.currVal = maxVal; scale = (double) this.width/this.maxVal; borderColor = Color.BLACK; fillColor = Color.GREEN; emptyColor = new Color(179,59,60,255);//red } public Slider makeDeepCopy(){ Slider newSlider= new Slider(this.width, this.height, this.maxVal); newSlider.setBorderThickness(this.borderThickness); newSlider.setBorderColor(this.borderColor); newSlider.setFillColor(this.fillColor); newSlider.setEmptyColor(this.emptyColor); return newSlider; } public boolean isFull(){ //if currVal is equal to maxVal return true return (currVal == maxVal); } public boolean isHidden(){ return hideAtMax; } public void hideAtMax(){ hideAtMax = true; } public void showAtMax(){ hideAtMax = false; } //setters and getters! public void setMaxVal (int maxVal){ this.maxVal = maxVal; } public void setCurrVal (int currVal){ this.currVal = currVal; } public void setBorderThickness (int borderThickness){ this.borderThickness = borderThickness; } public void setBorderColor (Color borderColor){ this.borderColor = borderColor; } public void setFillColor (Color fillColor){ this.fillColor = fillColor; } public void setEmptyColor (Color emptyColor){ this.emptyColor = emptyColor; } public void changeDimensions (int width, int height){ this.width = width; this.height = height; } public int getMaxVal (){ return maxVal; } public int getCurrVal (){ return currVal; } public double getScale(){ return scale; } public int getBorderThickness (){ return borderThickness; } public Color getBorderColor (){ return borderColor; } public Color getFillColor (){ return fillColor; } public Color getEmptyColor (){ return emptyColor; } public int getWidth (){ return width; } public int getHeight(){ return height; } //find percent fill public double getPercentFill(){ return (double) currVal/maxVal; } }
Evonek/FarmIsland
Slider.java
871
//if currVal is equal to maxVal return true
line_comment
en
true
67564_1
import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; public class UsunFilm extends JFrame { JButton bPowrot; JLabel lTitle; BazaDanych b; Color tekstLabel = new Color(15, 29, 68); Color tekstForm = new Color(248, 249, 241); Color tloForm = new Color(234, 158, 156); Color tloButton = new Color(5, 166, 218); public UsunFilm() throws FileNotFoundException { setSize(500, 1200); setTitle("DVDelfin"); JPanel deletePanel = new JPanel(new GridLayout(0, 2, 10, 10)); bPowrot = new JButton("<-"); //bPowrot.setBounds(10,10,45,20); deletePanel.add(bPowrot); bPowrot.setBackground(tloButton); bPowrot.setForeground(tekstForm); lTitle = new JLabel("Filmy"); //lTitle.setBounds(200,20,100,20); lTitle.setHorizontalAlignment(JLabel.CENTER); deletePanel.add(lTitle); lTitle.setForeground(tekstLabel); b = new BazaDanych(); final String[][] filmy = b.odczytZPliku(6, "filmy.txt"); if(filmy.length > 0){ deletePanel.setLayout(new GridLayout(0, 2, 10, 10)); int rozmiar = filmy.length; int index; for (int i = 1; i<rozmiar; i++) { JLabel nazwa = new JLabel(filmy[i][0]); nazwa.setHorizontalAlignment(JLabel.CENTER); deletePanel.add(nazwa); JButton deleteButton = new JButton("Usuń"); //imageButton.setIcon(icon); ImageIcon icon = resizeImage("filmy/"+filmy[i][1],120,240); System.out.println("filmy/"+filmy[i][1]); JButton imageButton = new JButton(icon); deletePanel.add(deleteButton); int finalI = i; deleteButton.addActionListener(new ActionListener(){ @Override public void actionPerformed (ActionEvent e){ String[][] nowaTablica; //JOptionPane.showMessageDialog(imageButton,wypozyczoneFilmy.elementAt(finalI)); nowaTablica = b.usunZTablicy(filmy, finalI); try { b.zastapPlik(nowaTablica,"filmy.txt"); } catch (IOException ex) { throw new RuntimeException(ex); } } }); deletePanel.add(deleteButton); add(deletePanel); bPowrot.addActionListener(e -> Admin.closeUsunFilmWindow()); JScrollPane scrollPane = new JScrollPane(deletePanel); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); add(scrollPane); } } } private static ImageIcon resizeImage(String imagePath, int width, int height) { try { File file = new File(imagePath); BufferedImage originalImage = ImageIO.read(file); Image scaledImage = originalImage.getScaledInstance(width, height, Image.SCALE_SMOOTH); return new ImageIcon(scaledImage); } catch (IOException e) { e.printStackTrace(); return null; } } }
piotrek1kons/DVDelfin
UsunFilm.java
899
//lTitle.setBounds(200,20,100,20);
line_comment
en
true
67603_9
package fc; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.HashMap; import fc.Dao.ClientDao; import fc.Dao.ClientDaoImp; /** * Classe représentant un client anonyme.<br> * Un client sera notamment identifié par son adresse de facturation.<br> * Il dispose de méthodes d'emprunt, de rendu et de recherche de film.<br> * Il peut souscrire à un abonnement, payer une location et vérifier s'il a une * location en cours sur un film. */ public class Client { private String adresseFacturation; private CarteBancaire carteBancaire; private static ClientDao clientDao = ClientDaoImp.getInstance();; /** * Constructeur de la classe client. * * @param adresseFacturation L'adresse de facturation du client * @param carteBancaire La carte bancaire du client */ public Client(String adresseFacturation, CarteBancaire carteBancaire) { this.adresseFacturation = adresseFacturation; this.carteBancaire = carteBancaire; } /** * Constructeur d'un client copiant les attributs d'un autre client. * * @param c Le client dont les attributs sont copiés */ protected Client(Client c) { this.adresseFacturation = c.adresseFacturation; this.carteBancaire = c.carteBancaire; } /** * Méthode d'emprunt d'un film.<br> * Elle a pour effet de créer une nouvelle location pour le client et le film. * * @param film Le film que le client souhaite emprunter et pour lequel une * éventuelle nouvelle location sera créée. * @return le code de la location ou -1 si la location a échouée. */ public int emprunter(Support film) { LocalDateTime dateEmprunt = LocalDateTime.now(); Location location = new Location(dateEmprunt, tarif(), this, film); if (film.calculerDuree() != -1) { // Alors il s'agit d'un QRCode car au moment de l'emprunt une seule durée peut être définie location.setFin(dateEmprunt.plusHours(film.calculerDuree())); Double prix = location.calculerPrix(); if (prix == -1) // Erreur au moment du calcul du prix return -1; int code = location.sauvegarder(); if(code != -1 && paiement(prix)) { //On ne paie que si la sauvegarde dans la base fonctionne location.genererFacture(); return code; } return -1; } return location.sauvegarder(); } /** * @return double */ protected double tarif() { return 5.0; } /** * Méthode de rendu d'un film.<br> * Elle vérifie si une location est en cours pour le film et générera une * facture que le client paiera.<br> * Le client peut aussi indiquer si le film est endommagé ou non. * * @param film Le film qui est rendu * @param endommage Renvoie le booléen indiquant si le film est endommagé ou non * @return boolean, true si l'opération s'est bien passé sinon false */ public boolean rendre(CD film, Boolean endommage) { /* * if (!estEnCours(film)) return false; * * Location l = getLocation(film); */ Location l = getLocationEnCours(film); if (l == null) return false; l.setFin(LocalDateTime.now()); Double prix = l.calculerPrix(); if (prix == -1) // Erreur au moment du calcul du prix return false; l.getSupport().setEndommage(endommage); l.miseAJour(); l.genererFacture(); if(endommage) { System.out.println("Vous serez remboursé après constatation par un technicien."); } return paiement(prix); } /** * Methode qui permet de savoir si le client a une location en cour * @param film * @return Location */ private Location getLocationEnCours(CD film) { return Location.trouverLocation(this, film); } /** * Méthode de recherche de films.<br> * Une requête sera notamment effectuée à la base de données en traitant les * filtres. * @param titre titre du film recherché * @return Renvoie la liste des films obtenue par la recherche */ public ArrayList<Film> rechercherFilm(String titre) { HashMap<String, String> filtres = new HashMap<String, String>(); filtres.put("titre", titre); return Film.rechercherFilm(filtres); } /** * Méthode de souscription à un nouvel abonnement.<br> * Un nouvel adhérent sera créé avec son nom, prénom, date de naissance, adresse * de facturation, carte bancaire.<br> * Une carte d'abonnement sera aussi créée pour le nouvel adhérent créé. * @param nom du nouvel adherent * @param prenom du nouvel adherent * @param dateNaissance du nouvel adherent * @param courriel du nouvel adherent * @return Adherent le nouvel adhérent créé */ public Adherent souscrire(String nom, String prenom, LocalDate dateNaissance, String courriel) { Adherent tmp = new Adherent(this, nom, prenom, dateNaissance, courriel); majClientAdherent(tmp); return tmp; } /** * Méthode de paiement d'une facture.<br> * @param prix Le prix de la facture à payer * @return Renvoie un booléen indiquant si le paiement a réussi ou non */ public Boolean paiement(double prix) { return carteBancaire.debiterCarte(prix); } /** * Méthode de recherche d'une location en cours sur le film. * @param cd le cd pour le quel on veut vérifier si il est en cours de location * @return Renvoie un booléen indiquant si une location est en cours pour le * film et le client ou non. */ public Boolean estEnCours(CD cd) { return Location.estEnCours(this,cd); } /** * methode qui va comparer deux clients au travers de leur carte bancaire * @see CarteBancaire voir la méthode equals. * @param c le client. * @return boolean true si la comparaison est positive, false sinon. */ public boolean egale(Client c){ return c.carteBancaire.equals(this.carteBancaire); } /** * Methode qui va se connecter a la BDD pour sauvegarder le client s'il n'existe pas déjà */ public void sauvegarder() { clientDao.ajouterClient(this); } /** * Methode qui va ajouter un adherent a la bdd * @param adherent l'adhérent qu'on rajoute à la BD et on supprime le client qu'il était. */ private void majClientAdherent(Adherent adherent) { clientDao.miseAJourClient(adherent); } /** * Fonction qui redefini la fonction tostring.<br> * Permet d'avoir un affichage plus comprehensible * @see Object pour voir la methode toString() * @return String String représentant l'objet */ @Override public String toString() { return "{" + " adresseFacturation = '" + getAdresseFacturation() + "'" + ", carteBancaire = '" + getCarteBancaire() + "'" + "}"; } /** * Methode qui retourne la carte * @return CarteBancaire retourne la carte bancaire du client */ public CarteBancaire getCarteBancaire() { return carteBancaire; } /** * Methode qui retourne l adresse de facturation * @return String représentant l'adresse de facturation */ public String getAdresseFacturation() { return adresseFacturation; } }
Dorian-Gray73/AL2000
fc/Client.java
2,239
/* * if (!estEnCours(film)) return false; * * Location l = getLocation(film); */
block_comment
en
true
68757_1
package com.live.action; import java.io.IOException; import java.sql.SQLException; import java.util.Enumeration; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.live.dao.NoticeDAO; import com.live.dao.ProfileDAO; import com.live.dao.SecurityDAO; import com.live.form.NoticeForm; public class AddNoticeAction1 extends HttpServlet { /** * Constructor of the object. */ public AddNoticeAction() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { NoticeForm nf=new NoticeForm(); String target=""; boolean flag=false; nf.setNotice(request.getParameter("notice")); nf.setNotby(request.getParameter("notby")); flag=new NoticeDAO().AddNotice(nf); if(flag) { target="AddNotice.jsp"; System.out.println("Success"); } else target="AddNotice.jsp"; RequestDispatcher rd=request.getRequestDispatcher(target); rd.forward(request, response); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }
ashwiniahire888/Java-Programs
att1.java
640
/** * Destruction of the servlet. <br> */
block_comment
en
true
68820_0
package com.fishercoder.solutions; import java.util.HashMap; import java.util.Map; /**Given a string, determine if a permutation of the string could form a palindrome. For example, "code" -> False, "aab" -> True, "carerac" -> True. Hint: Consider the palindromes of odd vs even length. What difference do you notice? Count the frequency of each character. If each character occurs even number of times, then it must be a palindrome. How about character which occurs odd number of times?*/ public class _266 { public boolean canPermutePalindrome(String s) { char[] chars = s.toCharArray(); Map<Character, Integer> map = new HashMap<Character, Integer>(); for (char c : chars) { if (!map.containsKey(c)) { map.put(c, 1); } else { map.put(c, map.get(c) + 1); } } int evenCount = 0; for (Map.Entry<Character, Integer> e : map.entrySet()) { if (e.getValue() % 2 != 0) { evenCount++; } if (evenCount > 1) { return false; } } return true; } }
codingwhite/Leetcode-4
src/main/java/com/fishercoder/solutions/_266.java
304
/**Given a string, determine if a permutation of the string could form a palindrome. For example, "code" -> False, "aab" -> True, "carerac" -> True. Hint: Consider the palindromes of odd vs even length. What difference do you notice? Count the frequency of each character. If each character occurs even number of times, then it must be a palindrome. How about character which occurs odd number of times?*/
block_comment
en
true
69847_0
/************************************************************************************************* * Java binding of Tokyo Cabinet * Copyright (C) 2006-2010 FAL Labs * This file is part of Tokyo Cabinet. * Tokyo Cabinet is free software; you can redistribute it and/or modify it under the terms of * the GNU Lesser General Public License as published by the Free Software Foundation; either * version 2.1 of the License or any later version. Tokyo Cabinet is distributed in the hope * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * You should have received a copy of the GNU Lesser General Public License along with Tokyo * Cabinet; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA. *************************************************************************************************/ package tokyocabinet; import java.util.*; /** * Query is a mechanism to search for and retrieve records corresponding conditions from table * database. */ public class TDBQRY { //---------------------------------------------------------------- // static initializer //---------------------------------------------------------------- static { System.loadLibrary("jtokyocabinet"); init(); } //---------------------------------------------------------------- // public constants //--------------------------------------------------------------- /** query condition: string is equal to */ public static final int QCSTREQ = 0; /** query condition: string is included in */ public static final int QCSTRINC = 1; /** query condition: string begins with */ public static final int QCSTRBW = 2; /** query condition: string ends with */ public static final int QCSTREW = 3; /** query condition: string includes all tokens in */ public static final int QCSTRAND = 4; /** query condition: string includes at least one token in */ public static final int QCSTROR = 5; /** query condition: string is equal to at least one token in */ public static final int QCSTROREQ = 6; /** query condition: string matches regular expressions of */ public static final int QCSTRRX = 7; /** query condition: number is equal to */ public static final int QCNUMEQ = 8; /** query condition: number is greater than */ public static final int QCNUMGT = 9; /** query condition: number is greater than or equal to */ public static final int QCNUMGE = 10; /** query condition: number is less than */ public static final int QCNUMLT = 11; /** query condition: number is less than or equal to */ public static final int QCNUMLE = 12; /** query condition: number is between two tokens of */ public static final int QCNUMBT = 13; /** query condition: number is equal to at least one token in */ public static final int QCNUMOREQ = 14; /** query condition: full-text search with the phrase of */ public static final int QCFTSPH = 15; /** query condition: full-text search with all tokens in */ public static final int QCFTSAND = 16; /** query condition: full-text search with at least one token in */ public static final int QCFTSOR = 17; /** query condition: full-text search with the compound expression of */ public static final int QCFTSEX = 18; /** query condition: negation flag */ public static final int QCNEGATE = 1 << 24; /** query condition: no index flag */ public static final int QCNOIDX = 1 << 25; /** order type: string ascending */ public static final int QOSTRASC = 0; /** order type: string descending */ public static final int QOSTRDESC = 1; /** order type: number ascending */ public static final int QONUMASC = 2; /** order type: number descending */ public static final int QONUMDESC = 3; /** set operation type: union */ public static final int MSUNION = 0; /** set operation type: intersection */ public static final int MSISECT = 1; /** set operation type: difference */ public static final int MSDIFF = 2; /** KWIC option: mark up by tabs */ public static final int KWMUTAB = 1 << 0; /** KWIC option: mark up by control characters */ public static final int KWMUCTRL = 1 << 1; /** KWIC option: mark up by square brackets */ public static final int KWMUBRCT = 1 << 2; /** KWIC option: do not overlap */ public static final int KWNOOVER = 1 << 24; /** KWIC option: pick up the lead string */ public static final int KWPULEAD = 1 << 25; //---------------------------------------------------------------- // private static methods //---------------------------------------------------------------- /** * Initialize the class. */ private static native void init(); //---------------------------------------------------------------- // private fields //---------------------------------------------------------------- /** pointer to the native object */ private long ptr = 0; /** host database object */ private TDB tdb = null; //---------------------------------------------------------------- // constructors and finalizers //---------------------------------------------------------------- /** * Create a query object. * @param tdb the table database object. */ public TDBQRY(TDB tdb){ initialize(tdb); this.tdb = tdb; } /** * Release resources. */ protected void finalize(){ destruct(); } //---------------------------------------------------------------- // public methods //---------------------------------------------------------------- /** * Add a narrowing condition. * @param name the name of a column. An empty string means the primary key. * @param op an operation type: `TDBQRY.QCSTREQ' for string which is equal to the expression, * `TDBQRY.QCSTRINC' for string which is included in the expression, `TDBQRY.QCSTRBW' for * string which begins with the expression, `TDBQRY.QCSTREW' for string which ends with the * expression, `TDBQRY.QCSTRAND' for string which includes all tokens in the expression, * `TDBQRY.QCSTROR' for string which includes at least one token in the expression, * `TDBQRY.QCSTROREQ' for string which is equal to at least one token in the expression, * `TDBQRY.QCSTRRX' for string which matches regular expressions of the expression, * `TDBQRY.QCNUMEQ' for number which is equal to the expression, `TDBQRY.QCNUMGT' for number * which is greater than the expression, `TDBQRY.QCNUMGE' for number which is greater than or * equal to the expression, `TDBQRY.QCNUMLT' for number which is less than the expression, * `TDBQRY.QCNUMLE' for number which is less than or equal to the expression, `TDBQRY.QCNUMBT' * for number which is between two tokens of the expression, `TDBQRY.QCNUMOREQ' for number * which is equal to at least one token in the expression, `TDBQRY.QCFTSPH' for full-text * search with the phrase of the expression, `TDBQRY.QCFTSAND' for full-text search with all * tokens in the expression, `TDBQRY.QCFTSOR' for full-text search with at least one token in * the expression, `TDBQRY.QCFTSEX' for full-text search with the compound expression. All * operations can be flagged by bitwise-or: `TDBQRY.QCNEGATE' for negation, `TDBQRY.QCNOIDX' * for using no index. * @param expr an operand exression. */ public native void addcond(String name, int op, String expr); /** * Set the order of the result. * @param name the name of a column. An empty string means the primary key. * @param type the order type: `TDBQRY.QOSTRASC' for string ascending, `TDBQRY.QOSTRDESC' for * string descending, `TDBQRY.QONUMASC' for number ascending, `TDBQRY.QONUMDESC' for number * descending. */ public native void setorder(String name, int type); /** * Set the maximum number of records of the result. * @param max the maximum number of records of the result. If it is negative, no limit is * specified. * @param skip the maximum number of records of the result. If it is not more than 0, no * record is skipped. */ public native void setlimit(int max, int skip); /** * Execute the search. * @return a list object of the primary keys of the corresponding records. This method does * never fail. It returns an empty array even if no record corresponds. */ public native List search(); /** * Remove each corresponding record. * @return If successful, the return value is true, else, it is false. */ public native boolean searchout(); /** * Process each corresponding record. * @param qp specifies the query processor object. * @return If successful, the return value is true, else, it is false. */ public native boolean proc(TDBQRYPROC qp); /** * Get the hint string. * @return the hint string. */ public native String hint(); /** * Retrieve records with multiple query objects and get the set of the result. * @param others an array of the query objects except for the self object. * @param type a set operation type: `TDBQRY.MSUNION' for the union set, `TDBQRY.MSISECT' for * the intersection set, `TDBQRY.MSDIFF' for the difference set. If it is not defined, * `TDBQRY.MSUNION' is specified. * @return a list object of the primary keys of the corresponding records. This method does * never fail. It returns an empty array even if no record corresponds. * @note If the first query object has the order setting, the result array is sorted by the * order. */ public native List metasearch(TDBQRY[] others, int type); /** * Generate keyword-in-context strings. * @param cols a hash containing columns. * @param name the name of a column. If it is not defined, the first column of the query is * specified. * @param width the width of strings picked up around each keyword. If it is negative, the * whole text is picked up. * @param opts options by bitwise-or: `TDBQRY.KWMUTAB' specifies that each keyword is marked up * between two tab characters, `TDBQRY.KWMUCTRL' specifies that each keyword is marked up by * the STX (0x02) code and the ETX (0x03) code, `TDBQRY.KWMUBRCT' specifies that each keyword * is marked up by the two square brackets, `TDBQRY.KWNOOVER' specifies that each context does * not overlap, `TDBQRY.KWPULEAD' specifies that the lead string is picked up forcibly. * @return an array of strings around keywords. */ public String[] kwic(Map cols, String name, int width, int opts){ return kwicimpl(Util.maptostrary(cols), name, width, opts); } //---------------------------------------------------------------- // private methods //---------------------------------------------------------------- /** * Initialize the object. */ private native void initialize(TDB tdb); /** * Release resources. */ private native void destruct(); /** * Generate a keyword-in-context string. */ private native String[] kwicimpl(byte[][] cols, String name, int width, int opts); } /* END OF FILE */
white-gecko/TokyoCabinet-Android-API
TDBQRY.java
2,790
/************************************************************************************************* * Java binding of Tokyo Cabinet * Copyright (C) 2006-2010 FAL Labs * This file is part of Tokyo Cabinet. * Tokyo Cabinet is free software; you can redistribute it and/or modify it under the terms of * the GNU Lesser General Public License as published by the Free Software Foundation; either * version 2.1 of the License or any later version. Tokyo Cabinet is distributed in the hope * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * You should have received a copy of the GNU Lesser General Public License along with Tokyo * Cabinet; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA. *************************************************************************************************/
block_comment
en
true
69863_0
/* Bon Appétit Anna and Brian are sharing a meal at a restuarant and they agree to split the bill equally. Brian wants to order something that Anna is allergic to though, and they agree that Anna won't pay for that item. Brian gets the check and calculates Anna's portion. You must determine if his calculation is correct. For example, assume the bill has the following prices: . Anna declines to eat item which costs . If Brian calculates the bill correctly, Anna will pay . If he includes the cost of , he will calculate . In the second case, he should refund to Anna. You are given an array of prices, , the cost of each of the items, , the item Anna doesn't eat, and , the total amount of money that Brian charged Anna for her portion of the bill. If the bill is fairly split, print Bon Appetit. Otherwise, print the integer amount of money that Brian must refund to Anna. Input Format The first line contains two space-separated integers and , the number of items ordered and the -based index of the item that Anna did not eat. The second line contains space-separated integers where . The third line contains an integer, , the amount of money that Brian charged Anna for her share of the bill. Constraints Output Format If Brian did not overcharge Anna, print Bon Appetit on a new line; otherwise, print the difference (i.e., ) that Brian must refund to Anna. This will always be an integer. */ import java.util.Scanner; import java.util.Arrays; public class task020 { public static void main(String args[] ) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int K = sc.nextInt(); sc.nextLine(); int[] bill = Arrays.stream(sc.nextLine().split(" ")) .mapToInt(Integer::parseInt) .toArray(); int charged = sc.nextInt(); sc.close(); int actual = (Arrays.stream(bill).sum() - bill[K]) / 2; System.out.println((actual == charged) ? "Bon Appetit" : charged - actual); } }
vilasha/HackerRank-Algorithms-Java8
task020.java
526
/* Bon Appétit Anna and Brian are sharing a meal at a restuarant and they agree to split the bill equally. Brian wants to order something that Anna is allergic to though, and they agree that Anna won't pay for that item. Brian gets the check and calculates Anna's portion. You must determine if his calculation is correct. For example, assume the bill has the following prices: . Anna declines to eat item which costs . If Brian calculates the bill correctly, Anna will pay . If he includes the cost of , he will calculate . In the second case, he should refund to Anna. You are given an array of prices, , the cost of each of the items, , the item Anna doesn't eat, and , the total amount of money that Brian charged Anna for her portion of the bill. If the bill is fairly split, print Bon Appetit. Otherwise, print the integer amount of money that Brian must refund to Anna. Input Format The first line contains two space-separated integers and , the number of items ordered and the -based index of the item that Anna did not eat. The second line contains space-separated integers where . The third line contains an integer, , the amount of money that Brian charged Anna for her share of the bill. Constraints Output Format If Brian did not overcharge Anna, print Bon Appetit on a new line; otherwise, print the difference (i.e., ) that Brian must refund to Anna. This will always be an integer. */
block_comment
en
true
71301_0
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc import android.text.TextUtils; import com.ubercab.analytics.model.AnalyticsEvent; import com.ubercab.client.core.contacts.Contact; import com.ubercab.client.core.model.Ping; import com.ubercab.client.core.model.SafetyNetAddContactsRequest; import com.ubercab.client.core.model.SafetyNetAddContactsResponse; import com.ubercab.client.core.model.SafetyNetContact; import com.ubercab.client.core.model.SafetyNetDeleteContactsResponse; import com.ubercab.client.core.model.SafetyNetGetContactsResponse; import com.ubercab.client.core.model.SafetyNetGetSharedTripContactsResponse; import com.ubercab.client.core.model.SafetyNetShareTripResponse; import com.ubercab.rider.realtime.model.Client; import com.ubercab.rider.realtime.model.Trip; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public final class fei { boolean a; fes b; String c; private List d; private icl e; private icl f; private final chp g; private final drc h; private final cev i; private final hkr j; private final hku k; private final dpg l; private final dkn m; private final czf n; private final dkp o; private final hko p; public fei(chp chp1, drc drc1, cev cev1, hkr hkr1, hku hku1, dpg dpg1, dkn dkn1, hko hko1, czf czf1, dkp dkp1) { gjz.a(cev1); g = chp1; h = drc1; i = cev1; j = hkr1; k = hku1; l = dpg1; m = dkn1; p = hko1; n = czf1; o = dkp1; } static cev a(fei fei1) { return fei1.i; } private void c(List list) { o.a(p(), list); } private void d(List list) { if (list != null && d != null) { Iterator iterator = d.iterator(); while (iterator.hasNext()) { SafetyNetContact safetynetcontact = (SafetyNetContact)iterator.next(); Iterator iterator1 = list.iterator(); while (iterator1.hasNext()) { SafetyNetContact safetynetcontact1 = (SafetyNetContact)iterator1.next(); if (safetynetcontact.getId().equals(safetynetcontact1.getId())) { iterator.remove(); } } } } } private boolean n() { return n.E(); } private void o() { if (d != null && d.size() > 0) { n.m(true); return; } else { n.m(false); return; } } private String p() { Client client = j.c(); if (client != null) { return client.getUuid(); } else { return ""; } } private String q() { Trip trip = j.f(); if (trip != null) { return trip.getUuid(); } else { return ""; } } public final void a() { d = null; } public final void a(SafetyNetContact safetynetcontact) { ArrayList arraylist = new ArrayList(); arraylist.add(safetynetcontact); c(arraylist); } public final void a(List list) { SafetyNetAddContactsRequest safetynetaddcontactsrequest = new SafetyNetAddContactsRequest(); String s = m(); ArrayList arraylist = new ArrayList(); Contact contact; String s1; for (list = list.iterator(); list.hasNext(); arraylist.add(new com.ubercab.client.core.model.SafetyNetAddContactsRequest.Contact(contact.a(), s1))) { contact = (Contact)list.next(); s1 = duj.c(contact.b(), s); } safetynetaddcontactsrequest.mContacts = arraylist; o.a(p(), safetynetaddcontactsrequest); } public final void b() { i.a(this); e = k.e().c(new fek(this, (byte)0)); } public final void b(List list) { ArrayList arraylist = new ArrayList(); list = list.iterator(); do { if (!list.hasNext()) { break; } SafetyNetContact safetynetcontact = (SafetyNetContact)list.next(); if (!b.a(safetynetcontact)) { arraylist.add(safetynetcontact); } } while (true); list = j.c(); if (list != null) { list = list.getFormattedName(); } else { list = ""; } o.a(q(), list, i(), arraylist); } public final boolean c() { return d == null || d.size() < 5; } public final int d() { if (d == null) { return 5; } else { return 5 - d.size(); } } public final int e() { if (b == null) { return 0; } else { return b.c(); } } public final List f() { if (d == null) { g(); } return d; } public final void g() { o.a(p()); } public final fes h() { if (b == null) { o.b(q()); } return b; } public final String i() { Trip trip = j.f(); if (trip == null || !TextUtils.isEmpty(c)) { return c; } if (!l.s()) { c = trip.getShareUrl(); if (TextUtils.isEmpty(c)) { m.e(); } } else { f = p.b(trip.getUuid()).a(ico.a()).a(new fej(this, (byte)0)); } return c; } public final boolean j() { return a; } public final boolean k() { return n.D(); } public final void l() { n.F(); } public final String m() { Client client = j.c(); if (client != null) { return client.getMobileCountryIso2(); } else { return null; } } public final void onPingClientResponseEvent(dmr dmr1) { dmr1 = (Ping)dmr1.g(); if (dmr1 != null) { dmr1 = dmr1.getClient(); } else { dmr1 = null; } if (!h.g() || d != null || dmr1 == null || TextUtils.isEmpty(dmr1.getUuid())) { return; } else { g(); return; } } public final void onPingEvent(dar dar1) { if (!l.n()) { dar1 = dar1.a().getClient().getStatus(); if (a && !dar1.equals("OnTrip") && !dar1.equals("WaitingForPickup")) { a = false; c = null; b = null; return; } } } public final void onSafetyNetAddContactsResponseEvent(dmz dmz1) { if (dmz1.i()) { dmz1 = (SafetyNetAddContactsResponse)dmz1.g(); if (d == null) { d = dmz1.getContacts(); } else { d.addAll(dmz1.getContacts()); } i.c(new ffg(1, d)); o(); g.a(AnalyticsEvent.create("tap").setName(n.ev).setValue(String.valueOf(dmz1.getContacts().size()))); return; } else { i.c(new ffh(1)); return; } } public final void onSafetyNetDeleteContactsResponseEvent(dna dna1) { if (dna1.i()) { dna1 = (SafetyNetDeleteContactsResponse)dna1.g(); d(dna1.getContacts()); i.c(new ffg(2, d)); o(); g.a(AnalyticsEvent.create("tap").setName(n.ew).setValue(String.valueOf(dna1.getContacts().size()))); return; } else { i.c(new ffh(2)); return; } } public final void onSafetyNetGetContactsResponseEvent(dnb dnb1) { if (dnb1.i()) { d = ((SafetyNetGetContactsResponse)dnb1.g()).getContacts(); i.c(new ffg(0, d)); o(); return; } else { i.c(new ffh(0)); return; } } public final void onSafetyNetGetSharedTripContactsResponseEvent(dnc dnc1) { if (dnc1.i()) { b = new fes(((SafetyNetGetSharedTripContactsResponse)dnc1.g()).getContacts()); if (b.c() > 0) { a = true; } i.c(new ffk(b)); return; } else { i.c(new ffh(4)); return; } } public final void onSafetyNetShareTripResponseEvent(dnd dnd1) { if (dnd1.i()) { dnd1 = (SafetyNetShareTripResponse)dnd1.g(); if (b == null) { b = new fes(dnd1.getContacts()); } else { b.a(dnd1.getContacts()); } a = true; i.c(new ffm()); if (!n() && !k()) { i.c(new ffl(true)); } g.a(AnalyticsEvent.create("tap").setName(n.ey).setValue(String.valueOf(dnd1.getContacts().size()))); return; } else { i.c(new ffh(3)); return; } } public final void onShareYoRideResponseEvent(dnh dnh1) { if (dnh1.e()) { dnh1 = (Ping)dnh1.g(); if (dnh1 != null) { dnh1 = dnh1.getTrip(); } else { dnh1 = null; } if (dnh1 != null) { c = dnh1.getShareUrl(); i.c(new ffj(c)); } } } public final ffl produceSafetyNetSharedTripStatusUpdate() { boolean flag; if (a && !n() && !k()) { flag = true; } else { flag = false; } return new ffl(flag); } }
gdkjrygh/CompSecurity
uber/src/fei.java
2,780
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
line_comment
en
true
71557_0
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package assignment; import java.util.Scanner; /** * * @author Hp */ public class Faq extends Policy{ @Override public void displayMainMenu() { Menu.displayPolicyMenu(); Scanner scanner = new Scanner(System.in); System.out.print("\nEnter choice: "); int choice = scanner.nextInt(); switch (choice) { case 1: displayPointEarnMenu(); continueReadingPolicy(); break; case 2: displayRedemptionMenu(); continueReadingPolicy(); break; case 3: displayMembershipTierMenu(); continueReadingPolicy(); break; case 4: break; default: System.out.println("Invalid choice. Please select again."); this.displayMainMenu(); } } @Override public void continueReadingPolicy() { Scanner scanner = new Scanner(System.in); System.out.print("\nDo you want to continue reading other policies (Y/N)? "); String input = scanner.nextLine(); while (!input.equalsIgnoreCase("Y") && !input.equalsIgnoreCase("N")) { System.out.println("Invalid input. Please enter 'Y' or 'N'."); System.out.print("\nDo you want to continue reading other policies (Y/N)? "); input = scanner.nextLine(); } if (input.equalsIgnoreCase("Y")) { displayMainMenu(); } else { System.out.println("Stop Reading Policy"); } } public void displayPointEarnMenu() { System.out.println("\n***************************************************************"); System.out.println("* Point Earn Guidelines *"); System.out.println("***************************************************************"); System.out.println("* *"); System.out.println("* 1. Earn Points by Purchase *"); System.out.println("* 2. Earn Points by Referral Code *"); System.out.println("* 3. Earn Points by Playing Game *"); System.out.println("* 4. Back *"); System.out.println("* *"); System.out.println("***************************************************************\n"); Scanner scanner = new Scanner(System.in); System.out.print("Enter your choice: "); int choice = scanner.nextInt(); switch (choice) { case 1: displayPointEarnByPurchase(); break; case 2: displayPointEarnByReferral(); break; case 3: displayPointEarnByPlayingGames(); break; case 4: displayMainMenu(); break; default: System.out.println("Invalid choice. Please select again."); displayPointEarnMenu(); } } public void displayPointEarnByPurchase() { System.out.println("\n**************************************** Frequently Asked Questions (FAQ): ***************************************"); System.out.println("Guidelines for earning points by purchase: "); System.out.println("1. How do I earn points by purchasing?"); System.out.println(" - You can earn points by making purchases at our store."); System.out.println(" - The more you spend, the more points you'll accumulate."); System.out.println("2. How are points calculated for purchases?"); System.out.println(" - Points are typically calculated based on the total amount spent on purchases."); System.out.println(" - You can earn one point for every Ringgit spent."); System.out.println("3. Are points earned immediately after a purchase?"); System.out.println(" - Yes, points are typically credited to your account immediately after a qualifying purchase is made."); System.out.println(" - However, there may be rare instances where points are credited after a short processing period."); System.out.println("4. Do all purchases qualify for earning points?"); System.out.println(" - Yes, all purchases qualify for earning points."); System.out.println("5. How long is the duration for the point expiry??"); System.out.println(" - The duration of point expiry is 1 year."); System.out.println(" - It is based on the customer's first-time purchase date plus 1 year."); } public void displayPointEarnByReferral() { System.out.println("\n**************************************** Frequently Asked Questions (FAQ): ***************************************"); System.out.println("Guidelines for earning points by referral code..."); System.out.println("1. How do I obtain a referral code?"); System.out.println(" - The referral code can only be received by sharing with friends or family."); System.out.println("2. Is there a limit to the number of times I can use my referral code?"); System.out.println(" - No, there's typically no limit to how many times you can use your referral code."); System.out.println("3. How many points can I earn by using a referral code?"); System.out.println(" - There are 50 points for each referral code."); System.out.println("4. How long is the duration for the point expiry??"); System.out.println(" - The duration of point expiry is 1 year."); System.out.println(" - It is based on the customer's first-time purchase date plus 1 year"); } public void displayPointEarnByPlayingGames(){ System.out.println("\n**************************************** Frequently Asked Questions (FAQ): ***************************************"); System.out.println("Guidelines for earning points by playing games..."); System.out.println("1. How are points awarded for playing games"); System.out.println(" - Points are typically awarded based on your performance in the games."); System.out.println(" - The higher your performance, the more points you're likely to earn."); System.out.println("2. How many points can I earn by playing games?"); System.out.println(" - The number of points you can earn varies depending on your performance in the games."); System.out.println(" - Generally, you'll earn 50 points for each successful completion of a game level or challenge."); System.out.println("3. Are there any restrictions on playing games to earn points?"); System.out.println(" - Each user is limited to three attempts per game, with a total of five games available for play upon each login."); System.out.println("4. How do I access the games to earn points?"); System.out.println(" - You can access the games by logging into your account."); System.out.println(" - Once logged in, navigate to the 'Play Game' section."); System.out.println("5. How long is the duration for the point expiry??"); System.out.println(" - The duration of point expiry is 1 year."); System.out.println(" - It is based on the customer's first-time purchase date plus 1 year"); } public void displayRedemptionMenu() { System.out.println("\n*********************************** Frequently Asked Questions (FAQ): **********************************"); System.out.println("Guidelines for Redeemption..."); System.out.println("1. What types of rewards are included?"); System.out.println(" - There are three types of reward, including normal product, limited product and voucher."); System.out.println("2. How many rewards can be redeemed in total?"); System.out.println(" - There are no restrictions for users to redeem rewards."); System.out.println(" - Redemption is based on the user's points."); System.out.println("3. What rewards can I redeem with my points?"); System.out.println(" - All the rewards can be redeem with the points."); System.out.println("4. Can customers without a tier redeem rewards?"); System.out.println(" - Yes, customer with no tier is allow to redeem all the rewards, except limited product."); } public void displayMembershipTierMenu() { System.out.println("\n****************************** Frequently Asked Questions (FAQ): *****************************"); System.out.println("\nMembership Tier Guidelines:"); System.out.println("1. How is my spending calculated for membership tiers"); System.out.println(" - How is my spending calculated for membership tiers?"); System.out.println("2. Can I move up or down between membership tiers?"); System.out.println(" - Yes, your membership tier can change based on your spending."); System.out.println(" - If your spending increases, you may move up to a higher tier, and vice versa."); System.out.println("3. Are there any additional benefits for higher-tier members?"); System.out.println(" - Yes, higher-tier members often receive redemption rewards without any restrictions."); } }
KYUNSSSS/JavaAssignment
src/assignment/Faq.java
2,098
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */
block_comment
en
true
71656_0
/** * Created by junyuanlau on 28/4/16. */ public class Trade { int TradeID; String buyCpty; String sellCpty; int quantity; double executedPrice; int datetime; String ticker; String exchange; String region; public Trade(Order buy, Order sell, int quantity, double price){ }; }
yuanzai/DistributedSystems
src/Trade.java
93
/** * Created by junyuanlau on 28/4/16. */
block_comment
en
true
71718_9
import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import java.io.FileReader; import java.io.IOException; import java.time.Instant; import java.util.ArrayList; /** * The DataLoader class provides methods to load the data from the Cards,Users, and trades JSON files. */ public class DataLoader { private static final String CARDS_FILE_PATH = "json/cards.json"; private static final String USERS_FILE_PATH = "json/users.json"; private static final String TRADES_FILE_PATH = "json/trades.json"; /** * Loads cards from the Card.JSON file. * * @return an ArrayList of Card objects. */ public static ArrayList<Card> loadCards() { ArrayList<Card> cards = new ArrayList<>(); JSONParser parser = new JSONParser(); try (FileReader reader = new FileReader(CARDS_FILE_PATH)) { JSONArray cardsArray = (JSONArray) parser.parse(reader); for (Object obj : cardsArray) { JSONObject cardObject = (JSONObject) obj; cards.add(parseCard(cardObject)); } } catch (IOException | ParseException e) { e.printStackTrace(); } return cards; } /** * Loads users from the Users.JSON file. * * @return an ArrayList of User objects. */ public static ArrayList<User> loadUsers() { ArrayList<User> users = new ArrayList<>(); JSONParser parser = new JSONParser(); try (FileReader reader = new FileReader(USERS_FILE_PATH)) { JSONArray usersArray = (JSONArray) parser.parse(reader); for (Object obj : usersArray) { JSONObject userObject = (JSONObject) obj; users.add(parseUser(userObject)); } } catch (IOException | ParseException e) { e.printStackTrace(); } return users; } /** * Loads trades from the trades.JSON file. * * @return an ArrayList of Trade objects. */ public static ArrayList<Trade> loadTrades() { ArrayList<Trade> trades = new ArrayList<>(); JSONParser parser = new JSONParser(); try (FileReader reader = new FileReader(TRADES_FILE_PATH)) { JSONArray tradesArray = (JSONArray) parser.parse(reader); for (Object obj : tradesArray) { JSONObject tradeObject = (JSONObject) obj; trades.add(parseTrade(tradeObject)); } } catch (IOException | ParseException e) { e.printStackTrace(); } return trades; } /** * Parses a JSONObject into a Card object. * * @param cardObject the JSONObject to parse. * @return a Card object. */ private static Card parseCard(JSONObject cardObject) { int id = getIntValue(cardObject, "id"); String name = getStringValue(cardObject, "name"); String type = getStringValue(cardObject, "type"); String rarity = getStringValue(cardObject, "rarity"); int pack = getIntValue(cardObject, "pack"); int hp = getIntValue(cardObject, "hp"); double value = getDoubleValue(cardObject, "value"); int evoStage = getIntValue(cardObject, "evoStage"); ArrayList<Integer> familyCards = getIntegerList(cardObject, "family"); ArrayList<String> attacks = getStringList(cardObject, "attacks"); return new Card(id, name, type, rarity, pack, hp, value, evoStage, familyCards, attacks); } /** * Gets an integer value from a JSONObject. * * @param jsonObject the JSONObject. * @param key the key of the value. * @return the integer value. */ private static int getIntValue(JSONObject jsonObject, String key) { Object value = jsonObject.get(key); if (value instanceof Long) { return ((Long) value).intValue(); } return 0; } /** * Gets a double value from a JSONObject. * * @param jsonObject the JSONObject. * @param key value of the double. * @return the double value. */ private static double getDoubleValue(JSONObject jsonObject, String key) { Object value = jsonObject.get(key); if (value instanceof Long) { return ((Long) value).doubleValue(); } else if (value instanceof Double) { return (Double) value; } return 0.0; } /** * Gets a string value from a JSONObject. * * @param jsonObject the JSONObject. * @param key the key of the value. * @return the string value. */ private static String getStringValue(JSONObject jsonObject, String key) { Object value = jsonObject.get(key); return value != null ? value.toString() : ""; } /** * Gets an ArrayList of integers from a JSONObject. * * @param jsonObject the JSONObject. * @param key the key of the value. * @return an ArrayList of integers. */ private static ArrayList<Integer> getIntegerList(JSONObject jsonObject, String key) { ArrayList<Integer> list = new ArrayList<>(); Object value = jsonObject.get(key); if (value instanceof JSONArray) { JSONArray jsonArray = (JSONArray) value; for (Object obj : jsonArray) { if (obj instanceof Long) { list.add(((Long) obj).intValue()); } } } else if (value instanceof Long) { list.add(((Long) value).intValue()); } return list; } /** * Gets an ArrayList of strings from a JSONObject. * * @param jsonObject the JSONObject. * @param key the key of the value. * @return an ArrayList of strings. */ private static ArrayList<String> getStringList(JSONObject jsonObject, String key) { ArrayList<String> list = new ArrayList<>(); Object value = jsonObject.get(key); if (value instanceof JSONArray) { JSONArray jsonArray = (JSONArray) value; for (Object obj : jsonArray) { if (obj instanceof String) { list.add((String) obj); } } } else if (value instanceof String) { list.add((String) value); } return list; } /** * Parses a JSONObject into a User object. * * @param userObject the JSONObject to parse. * @return a User object. */ private static User parseUser(JSONObject userObject) { String userName = getStringValue(userObject, "userName"); String uniqueIdentifier = getStringValue(userObject, "uniqueIdentifier"); String password = getStringValue(userObject, "password"); String firstName = getStringValue(userObject, "firstName"); String lastName = getStringValue(userObject, "lastName"); String email = getStringValue(userObject, "email"); double currency = getDoubleValue(userObject, "currency"); ArrayList<Integer> favoriteCardsTemp = getIntegerList(userObject, "favoriteCards"); ArrayList<Card> favoriteCards = new ArrayList<>(); CardList masterList = CardList.getInstance(); for (Integer temp : favoriteCardsTemp) { favoriteCards.add(masterList.searchById(temp)); } ArrayList<Integer> ownedCardsTemp = getIntegerList(userObject, "ownedCards"); ArrayList<Card> ownedCards = new ArrayList<>(); for (Integer temp : ownedCardsTemp) { ownedCards.add(masterList.searchById(temp)); } Instant lastClaimedCurrencyTime = Instant.parse(getStringValue(userObject, "lastClaimedCurrencyTime")); User user = new User(userName, password, firstName, lastName, email, favoriteCards, currency, ownedCards); user.setLastClaimedCurrencyTime(lastClaimedCurrencyTime); return user; } /** * Parses a JSONObject into a Trade object. * * @param tradeObject the JSONObject to parse. * @return a Trade object. */ private static Trade parseTrade(JSONObject tradeObject) { UserList userList = UserList.getInstance(); CardList masterList = CardList.getInstance(); String receiverUserName = getStringValue(tradeObject, "receiverUserName"); User receiver = userList.searchByUserName(receiverUserName); String senderUserName = getStringValue(tradeObject, "senderUserName"); User sender = userList.searchByUserName(senderUserName); ArrayList<Integer> cardsIds = getIntegerList(tradeObject, "cardsOffered"); ArrayList<Card> cardsOffered = new ArrayList<Card>(); for (int num : cardsIds) { cardsOffered.add(masterList.searchById(num)); } int cardRequested = getIntValue(tradeObject, "cardsRequested"); Card realCard = masterList.searchById(cardRequested); boolean isFairTrade = (Boolean) tradeObject.get("isFairTrade"); boolean awaitingResponse = (Boolean) tradeObject.get("awaitingResponse"); boolean wasAccepted = (Boolean) tradeObject.get("wasAccepted"); String comment = getStringValue(tradeObject, "comment"); Trade trade = new Trade(sender, receiver, cardsOffered, realCard, isFairTrade, awaitingResponse, wasAccepted, comment); if (sender != null) sender.addReceivingTrade(trade); if (receiver != null) receiver.addReceivingTrade(trade); return trade; } }
CSVrajTPatel/PokeBros
DataLoader.java
2,147
/** * Gets an ArrayList of strings from a JSONObject. * * @param jsonObject the JSONObject. * @param key the key of the value. * @return an ArrayList of strings. */
block_comment
en
false
71786_9
/********************************************************************* * Indirect priority queue. * * The priority queue maintains its own copy of the priorities, * unlike the one in Algorithms in Java. * * This code is from "Algorithms in Java, Third Edition, * by Robert Sedgewick, Addison-Wesley, 2003. *********************************************************************/ public class IndexPQ { private int N; // number of elements on PQ private int[] pq; // binary heap private int[] qp; // private double[] priority; // priority values public IndexPQ(int NMAX) { pq = new int[NMAX + 1]; qp = new int[NMAX + 1]; priority = new double[NMAX + 1]; N = 0; } public boolean isEmpty() { return N == 0; } // insert element k with given priority public void insert(int k, double value) { N++; qp[k] = N; pq[N] = k; priority[k] = value; fixUp(pq, N); } // delete and return the minimum element public int delMin() { exch(pq[1], pq[N]); fixDown(pq, 1, --N); return pq[N+1]; } // change the priority of element k to specified value public void change(int k, double value) { priority[k] = value; fixUp(pq, qp[k]); fixDown(pq, qp[k], N); } /************************************************************** * General helper functions **************************************************************/ private boolean greater(int i, int j) { return priority[i] > priority[j]; } private void exch(int i, int j) { int t = qp[i]; qp[i] = qp[j]; qp[j] = t; pq[qp[i]] = i; pq[qp[j]] = j; } /************************************************************** * Heap helper functions **************************************************************/ private void fixUp(int[] a, int k) { while (k > 1 && greater(a[k/2], a[k])) { exch(a[k], a[k/2]); k = k/2; } } private void fixDown(int[] a, int k, int N) { int j; while (2*k <= N) { j = 2*k; if (j < N && greater(a[j], a[j+1])) j++; if (!greater(a[k], a[j])) break; exch(a[k], a[j]); k = j; } } }
SalmonRanjay/Bison-Maps
IndexPQ.java
636
/************************************************************** * Heap helper functions **************************************************************/
block_comment
en
false
71819_8
/****************************************************************************** * Compilation: javac Genome.java * Execution: java Genome - < input.txt (compress) * Execution: java Genome + < input.txt (expand) * Dependencies: BinaryIn.java BinaryOut.java * Data files: https://algs4.cs.princeton.edu/55compression/genomeTiny.txt * * Compress or expand a genomic sequence using a 2-bit code. * * % more genomeTiny.txt * ATAGATGCATAGCGCATAGCTAGATGTGCTAGC * * % java Genome - < genomeTiny.txt | java Genome + * ATAGATGCATAGCGCATAGCTAGATGTGCTAGC * ******************************************************************************/ /** * The {@code Genome} class provides static methods for compressing * and expanding a genomic sequence using a 2-bit code. * <p> * For additional documentation, * see <a href="https://algs4.cs.princeton.edu/55compression">Section 5.5</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class Genome { // Do not instantiate. private Genome() { } /** * Reads a sequence of 8-bit extended ASCII characters over the alphabet * { A, C, T, G } from standard input; compresses them using two bits per * character; and writes the results to standard output. */ public static void compress() { Alphabet DNA = Alphabet.DNA; String s = BinaryStdIn.readString(); int n = s.length(); BinaryStdOut.write(n); // Write two-bit code for char. for (int i = 0; i < n; i++) { int d = DNA.toIndex(s.charAt(i)); BinaryStdOut.write(d, 2); } BinaryStdOut.close(); } /** * Reads a binary sequence from standard input; converts each two bits * to an 8-bit extended ASCII character over the alphabet { A, C, T, G }; * and writes the results to standard output. */ public static void expand() { Alphabet DNA = Alphabet.DNA; int n = BinaryStdIn.readInt(); // Read two bits; write char. for (int i = 0; i < n; i++) { char c = BinaryStdIn.readChar(2); BinaryStdOut.write(DNA.toChar(c), 8); } BinaryStdOut.close(); } /** * Sample client that calls {@code compress()} if the command-line * argument is "-" an {@code expand()} if it is "+". * * @param args the command-line arguments */ public static void main(String[] args) { if (args[0].equals("-")) compress(); else if (args[0].equals("+")) expand(); else throw new IllegalArgumentException("Illegal command line argument"); } } /****************************************************************************** * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. * * This file is part of algs4.jar, which accompanies the textbook * * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. * http://algs4.cs.princeton.edu * * * algs4.jar is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * algs4.jar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with algs4.jar. If not, see http://www.gnu.org/licenses. ******************************************************************************/
HacoK/Algorithms
Genome.java
1,038
/****************************************************************************** * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. * * This file is part of algs4.jar, which accompanies the textbook * * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. * http://algs4.cs.princeton.edu * * * algs4.jar is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * algs4.jar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with algs4.jar. If not, see http://www.gnu.org/licenses. ******************************************************************************/
block_comment
en
true
72279_1
public class Alien extends Monster{ // The Alien, moves in leftwards, until it cannot go any further, // then it will turn 90 degrees to the left and continue. private int counter; public Alien(GameState game, int x, int y){ super(game, x, y); counter=0; } public void tick(){ // counter=0 left, counter=1 down, counter=2 right, counter=3 up switch(counter){ case 0: if(this.canMoveLeft()){ moveLeft(); break; } counter=(counter+1)%4; case 1: if(this.canMoveDown()){ moveDown(); break; } counter=(counter+1)%4; case 2: if(this.canMoveRight()){ moveRight(); break; } counter=(counter+1)%4; case 3: if(this.canMoveUp()){ moveUp(); break; } counter=(counter+1)%4; default: break; } } @Override public void drawSelf(){ String sprite = new String("\uD83D\uDC7D"); int x = this.getX(); int y = this.getY(); GameState game = this.getGame(); game.drawSpriteAt(x, y, sprite); } @Override public void onPlayerColision(Player p){ int x = this.getX(); int y = this.getY(); GameState game = this.getGame(); if(p.occupiesPosition(x, y)){ System.out.println("Captured by Aliens! Game Over..."); game.stop(); } } }
TriptSharma/JavaGame
Alien.java
391
// then it will turn 90 degrees to the left and continue.
line_comment
en
false
72382_13
import edu.princeton.cs.algs4.Queue; import edu.princeton.cs.algs4.Digraph; import edu.princeton.cs.algs4.In; import java.util.Iterator; /** * Todo: Nodes with the same ids in a circle should be treated differently for * minimum length calculation and ancestor */ public class SAP { private final Digraph digraphDFCopy; private int ancestor; private int minDistance; private int from; private int to; private final int n; private boolean[] marked; private int hops; private int[] edgeTo; private int[] DistTo; private final int[] id; private static final int INFINITY = Integer.MAX_VALUE; private final boolean print = false; private boolean hasCircle = false; // constructor takes a digraph ( not necessarily a DAG ) public SAP(Digraph digraph) { if (digraph == null) throw new IllegalArgumentException("Digraph value can not be null"); digraphDFCopy = new Digraph(digraph); n = digraphDFCopy.V(); id = new int[n]; edgeTo = new int[n]; DistTo = new int[n]; DistTo = new int[n]; for (int i = 0; i < n; i++) { id[i] = i; edgeTo[i] = i; } } // length of the shortest ancestral path between v and w; -1 if no such path public int length(int v, int w) { // System.out.println("length(): Calculating the distance between : " + v + " " // + w); if (v < 0 || v >= digraphDFCopy.V()) throw new IllegalArgumentException("The node ids should be within acceptable range.\n"); if (w < 0 || w >= digraphDFCopy.V()) throw new IllegalArgumentException("The node ids should be within acceptable range.\n"); if (((this.from == v && this.to == w) || (this.to == v && this.from == w)) && v != w) return minDistance; from = v; to = w; if (v == w) { ancestor = v; minDistance = 0; return 0; } if ((digraphDFCopy.indegree(from) == 0 && digraphDFCopy.outdegree(from) == 0) || (digraphDFCopy.indegree(to) == 0 && digraphDFCopy.outdegree(to) == 0)) { ancestor = -1; return minDistance = -1; } if (id[v] == id[w] && !hasCircle) { if (find(v, w) == w) { ancestor = v; minDistance = hops; } else if (find(w, v) == v && !hasCircle) { minDistance = hops; ancestor = w; } else { for (int i = 0; i < n; i++) { id[i] = i; // edgeTo[i] = i; } lockStepBFS(v, w); } } else { for (int i = 0; i < n; i++) { id[i] = i; // edgeTo[i] = i; } lockStepBFS(from, to); } return minDistance; } // length of the shortest ancestral path between any vertex in v and any vertex // in w; -1 if no such path public int length(Iterable<Integer> v, Iterable<Integer> w) { if (v == null || w == null) throw new IllegalArgumentException("Iterable value to SAP.length() can not be null.\n"); int currentDistance = 0; int prevDistance = INFINITY; // System.out.printf("sap triggers ancestor() with iterables "); Iterator<Integer> i = v.iterator(); Iterator<Integer> j = w.iterator(); if ((!i.hasNext()) || (!j.hasNext())) { return minDistance = -1; } int source; int destination; Object obj; while (i.hasNext()) { obj = i.next(); if (obj == null) throw new IllegalArgumentException("The values Iterables give to length() can not be null."); else source = (Integer) obj; while (j.hasNext()) { obj = j.next(); if (obj == null) throw new IllegalArgumentException("The values Iterables give to length() can not be null."); destination = (Integer) obj; currentDistance = length(source, destination); // System.out.printf("Current Distance: %d \n", currentDistance); if (currentDistance != -1 && currentDistance < prevDistance) { prevDistance = currentDistance; } } j = w.iterator(); } // System.out.printf("Here is the last value in previous distance: %d\n" , // prevDistance); if (prevDistance != INFINITY) minDistance = prevDistance; return minDistance; } // a common ancestor of v and w that participates in a shortest ancestral path; // -1 if no such path public int ancestor(int v, int w) { // System.out.println("Calculating the ancestor between : " + v + " " + w); if (v < 0 || v >= digraphDFCopy.V()) throw new IllegalArgumentException("The node ids should be within acceptable range.\n"); if (w < 0 || w >= digraphDFCopy.V()) throw new IllegalArgumentException("The node ids should be within acceptable range.\n"); if (v < 0 || w < 0) throw new IllegalArgumentException("The node ids should be within acceptable range.\n"); if (((this.from == v && this.to == w) || (this.to == v && this.from == w)) && v != w) return ancestor; from = v; to = w; if (v == w) { return ancestor = v; } if ((digraphDFCopy.indegree(from) == 0 && digraphDFCopy.outdegree(from) == 0) || (digraphDFCopy.indegree(to) == 0 && digraphDFCopy.outdegree(to) == 0)) { minDistance = -1; return ancestor = -1; } if (id[v] == id[w]) { if (find(v, w) == w && !hasCircle) { ancestor = v; minDistance = hops; } else if (find(w, v) == v && !hasCircle) { minDistance = hops; ancestor = w; } else { for (int i = 0; i < n; i++) { id[i] = i; // edgeTo[i] = i; } lockStepBFS(v, w); } } else { for (int i = 0; i < n; i++) { id[i] = i; // edgeTo[i] = i; } lockStepBFS(from, to); } return ancestor; } // a common ancestor that participates in the shortest ancestral path; -1 if no // such path public int ancestor(Iterable<Integer> v, Iterable<Integer> w) { if (v == null || w == null) throw new IllegalArgumentException("Iterable value to SAP.ancestor() can not be null.\n"); int len = 0; int prevLen = INFINITY; int currentAncestor = 0; Iterator<Integer> i = v.iterator(); Iterator<Integer> j = w.iterator(); if ((!i.hasNext()) || (!j.hasNext())) { return ancestor = -1; } int source; int destination; Object obj; while (i.hasNext()) { obj = i.next(); if (obj == null) throw new IllegalArgumentException("The values Iterables give to length() can not be null."); else source = (Integer) obj; while (j.hasNext()) { obj = j.next(); if (obj == null) throw new IllegalArgumentException("The values Iterables give to length() can not be null."); destination = (Integer) obj; len = length(source, destination); if (len != -1 && len < prevLen) { currentAncestor = ancestor; prevLen = len; } } j = w.iterator(); } ancestor = currentAncestor; minDistance = prevLen; return ancestor; } private int find(int x, int y) { hops = 0; while (x != edgeTo[x]) { x = edgeTo[x]; hops++; if (x == y) return x; } return -1; } private void updateDistance(int newNode, int previousNode) { while (DistTo[newNode] + 1 < DistTo[previousNode]) { DistTo[previousNode] = DistTo[newNode] + 1; newNode = previousNode; previousNode = edgeTo[previousNode]; } } private void lockStepBFS(int f, int t) { marked = new boolean[n]; Queue<Integer> fromQueue = new Queue<>(); Queue<Integer> toQueue = new Queue<>(); fromQueue.enqueue(f); toQueue.enqueue(t); marked[f] = true; marked[t] = true; DistTo[f] = 0; DistTo[t] = 0; int currentDistance = INFINITY; int currentAncestor = -1; int temp = 0; while (!(fromQueue.isEmpty() && toQueue.isEmpty())) { if (!fromQueue.isEmpty()) { int v = fromQueue.dequeue(); if (print) System.out.printf("took %d from fromQueue \n", v); for (int j : digraphDFCopy.adj(v)) { if (!marked[j]) { marked[j] = true; DistTo[j] = DistTo[v] + 1; id[j] = id[v]; edgeTo[j] = v; fromQueue.enqueue(j); } else { if (id[j] == id[v]) { updateDistance(j, v); hasCircle = true; if (find(j, f) == f) { ancestor = f; minDistance = hops; } else if (find(f, j) == f) { minDistance = hops; ancestor = f; } edgeTo[j] = v; } else { // if DistTo[j] is larger, change v's id, otherwise change temp = DistTo[j] + DistTo[v] + 1; if (currentDistance == INFINITY || temp < currentDistance) { currentAncestor = j; currentDistance = temp; } } } } } if (!toQueue.isEmpty()) { int w = toQueue.dequeue(); if (print) System.out.printf("took %d from toQueue \n", w); for (int k : digraphDFCopy.adj(w)) { if (!marked[k]) { marked[k] = true; DistTo[k] = DistTo[w] + 1; id[k] = id[w]; edgeTo[k] = w; toQueue.enqueue(k); } else { if (id[k] == id[w]) { updateDistance(k, w); hasCircle = true; if (find(k, t) == t) { ancestor = k; minDistance = hops; } else if (find(t, k) == t) { minDistance = hops; ancestor = t; } edgeTo[k] = w; } else { temp = DistTo[k] + DistTo[w] + 1; if (currentDistance == INFINITY || temp < currentDistance) { currentAncestor = k; currentDistance = temp; } } } } } } if (currentDistance == INFINITY) { // System.out.println("setting minDistance to -1 becuase currentDistance is // INFINITY "); minDistance = -1; ancestor = -1; // return minDistance; } else if (currentAncestor == -1) { return; } else { minDistance = currentDistance; ancestor = currentAncestor; // Once I have an ancestor I can update the id of its edgeTos to its id. I think } // return currentDistance; } private boolean testEdgeTo(int ancestor, int destination) { // System.out.printf("inside testEdge for " + from + " and " + to); if (ancestor == destination) return true; int i = ancestor; int counter = 0; for (; i != destination && counter < n; i = edgeTo[i]) { if (i == -1) break; counter++; // System.out.print(" " + i); } // if (i != -1) System.out.print(" " + i); return (i == destination); } public static void main(String[] args) { Digraph digraph = new Digraph(new In("digraph3.txt")); SAP sap = new SAP(digraph); System.out.printf("%b\n", sap.testEdgeTo(11, 12)); System.out.printf("%b\n", sap.testEdgeTo(11, 8)); } }
bitflame/WordNet-light-
SAP.java
3,171
// a common ancestor of v and w that participates in a shortest ancestral path;
line_comment
en
true
72454_1
/** * @author Grace Bero * Creates a spell class that can be used to create spells */ public class Spell { protected String spellName; protected int damage; protected int staminaCost; protected String keyAssociation; /** * Constructor for Attacks Class * @param s, string for spell name * @param d, int for damage * @param m, int for mana cost * @param k, string for key association */ public Spell(String s, int d, int st, String k) { spellName = s; damage = d; staminaCost = st; keyAssociation = k; } /** * Mutators for spell name, damage, and mana cost * @param spell, string for spell name * @param dmg, int for damage * @param stam, int for stamina cost * @param key, string for key association */ public void setSpellName(String s) { spellName = s; } public void setDamage(int d) { damage = d; } public void setStamina(int st) { staminaCost = st; } /** * Accessors for spell name, damage, and mana cost * @return spellName, damage, manaCost, keyAssociation */ public String getSpellName() { return spellName; } public int getDamage() { return damage; } public int getStaminaCost() { return staminaCost; } /** * toString method for Attacks class * @return String representation of Attack */ public String toString() { String spellString = spellName + ", " + damage + " dmg, " + staminaCost + " stamina"; return spellString; } /** * Testing printing out spells */ public static void main(String[] args) { Spell fireball = new Spell("Fireball", 20, 4, "f"); Spell lightning = new Spell("Lightning", 10, 2, "l"); Spell ice = new Spell("Ice", 15, 3, "i"); Spell heal = new Spell("Heal", -20, 4, "h"); System.out.println(fireball); System.out.println(lightning); System.out.println(ice); System.out.println(heal); } }
graceb620/Adventure_Game2.0
src/Spell.java
559
/** * Constructor for Attacks Class * @param s, string for spell name * @param d, int for damage * @param m, int for mana cost * @param k, string for key association */
block_comment
en
false
72473_9
import sun.reflect.generics.reflectiveObjects.NotImplementedException; /** * Created by sebastian on 28/03/15. * * Enum class containing enums that are used for consistency throughout the project. */ public class Enums { /** * Enumeration pertaining to statistics */ public enum Stats { /** * The number of matches */ matches, /** * The emotion */ emotion } /** * Enumeration pertaining to features */ public enum Features { /** * If the object of a pattern is an NP; else it is whole sub-clause, i.e. S. */ isNP, /** * If the regular order of subject := emotion holder and object := cause is reversed, e.g. for "scare". */ orderIsReversed } /** * Enumeration containing Plutchik's eight emotions that are used. */ public enum Emotions { anger, anticipation, disgust, fear, joy, sadness, surprise, trust } /** * Enumeration for the two association metrics that are used. */ public enum Metric { pmi, chi_square } /** * Enumeration containing the two ngrams that are used. */ public enum Ngram { unigram, bigram } /** * Enumeration containing the different sources the ngrams can come from. */ public enum NgramSource { np_cause, s_cause, s_cause_subj_pred, s_cause_pred_dobj, emotion_holder } /** * Enumeration containing the different possible sentiments. */ public enum Sentiment { positive, negative, neutral } /** * Enumeration containing the possible degrees of overlap with the NRC Emotion-Association Lexicon (EmoLex). */ public enum NRCOverlap { FALSE, TRUE, NA } /** * Converts an emotion enum to its corresponding sentiment. * @param emotion the emotion enum * @return the corresponding sentiment */ public static Sentiment emotionToSentiment(Emotions emotion) { switch (emotion) { case anger: case disgust: case fear: case sadness: return Sentiment.negative; case joy: case trust: return Sentiment.positive; case anticipation: case surprise: return Sentiment.neutral; default: throw new NotImplementedException(); } } }
sebastianruder/emotion_proposition_store
src/Enums.java
553
/** * Enumeration containing the two ngrams that are used. */
block_comment
en
false
72784_1
/* * Qno1:(Test-Drive: Body Mass Index Calculator) Obesity causes significant increases in illnesses such as diabetes and heart disease. To determine whether a person is overweight or obese, you can use a measure called the body mass index (BMI). The United States Department of Health and Human Services provides a BMI calculator at: http://www.nhlbi.nih.gov/guidelines/obesity/BMI/bmicalc.htm Use it to calculate your own BMI. A forthcoming exercise will ask you to program your own BMI calculator. To prepare for this, use the web to research the formulas for calculating BMI. */ import java.util.Scanner; public class BMI { public static void main(String args[]) { Scanner input = new Scanner(System.in); System.out.println("----------------------------------------------------------\n"); System.out.println("Enter The weight:"); double weight = input.nextDouble(); System.out.println("----------------------------------------------------------\n"); System.out.println("Enter The height:"); double height = input.nextDouble(); // The formula for BMI is weight in kilograms divided by height in meters squared double Body_Mass_index = weight / (height * height); System.out.println("----------------------------------------------------------\n"); System.out.println("The Body Mass Index is " + Body_Mass_index); // Categorizing the BMI if (Body_Mass_index < 18.5) { System.out.println("You are Underweight."); } else if (Body_Mass_index >= 18.5 && Body_Mass_index <= 24.9) { System.out.println("You have Normal weight."); } else if (Body_Mass_index >= 25 && Body_Mass_index <= 29.9) { System.out.println("You are Overweight."); } else { System.out.println("You are Obese."); } khan khan = new khan(); khan.printStart(); } }
Yousaf-Maaz/Java-Programmming
BMI.java
485
// The formula for BMI is weight in kilograms divided by height in meters squared
line_comment
en
false
72873_0
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Solutions; /** * * @author David */ import java.util.*; public class toilet { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String x=sc.next();int a=0,b=0,c=0; char y =x.charAt(0); if(y=='U'&&x.charAt(1)=='D'){a+=2;b++;c++;} if(y=='D'&&x.charAt(1)=='U'){b+=2;a++;c++;} if(y=='U'&&x.charAt(1)=='U'){b++;} if(y=='D'&&x.charAt(1)=='D'){a++;} for(int i=2;i<x.length();i++){ y=x.charAt(i-1); if(x.charAt(i)=='U'){ b+=2; if(y=='D')c++; }else{ a+=2; if(y=='U')c++; } } System.out.println(a); System.out.println(b); System.out.println(c); } }
dakoval/Kattis-Solutions
toilet.java
320
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */
block_comment
en
true
72939_0
class Prime{ public static void main(String args[]){ System.out.println(fun()); } public static int fun(){ long starttime = System.nanoTime(); int arr[] = {1,3,19,17,15}; int count = 0; int prime = 0; for(int i=0;i<5;i++){ for(int j=1;j<=arr[i];j++){ if(arr[i]%j == 0){ count++; } } if(count<2){ System.out.println(arr[i]); } else{ //System.out.println(arr[i]); prime++; } } long endtime = System.nanoTime(); long time = (endtime - starttime); System.out.println("Time in nanosecs:"+time); return prime; } }
shraddha131004/JRoj
pr.java
237
//System.out.println(arr[i]);
line_comment
en
true
73245_1
package controllers; import java.sql.SQLException; import java.util.List; import java.util.Map; import models.Building; import models.Experiment; import models.Room; import models.User; import play.Logger; import play.Routes; import play.data.Form; import play.data.validation.Constraints; import play.i18n.Messages; import play.mvc.Controller; import play.mvc.Result; import views.html.index; import views.html.admin.lab; import static play.data.Form.form; /** * Login and Logout. * User: yesnault */ public class Admin extends Controller { /** * Displays the admin mainview * * @return */ public static Result admin() { // try { return ok(views.html.admin.admin.render()); // } catch (SQLException e) { // return badRequest(e.toString()); // } } /** * Displays the user_edit view * @TODO wieso gibts hier den fehler von eclipse? * @return * * G */ public static Result user_edit(Long id) throws SQLException { Form<User> editForm = form(User.class); return ok(views.html.admin.user_edit.render(User.byId(id))); } /** * Displays the admin user view * * @return */ public static Result astudies() { return ok(views.html.admin.studies.render()); } /** * Displays the admin studies * * @return */ public static Result auser() { return ok(views.html.admin.user.render()); } /** * Displays the admin edit page * * @return */ public static Result edit() { return ok(views.html.admin.edit_admin.render()); } /** * Displays the admin lab * * @return */ public static Result lab() { try { return ok(views.html.admin.lab.render(Building.all(),Room.all(),Building.count())); } catch (SQLException e) { // TODO Auto-generated catch block return badRequest(e.toString()); } } /** *Gets the coordinates from client (admin) for a new room * *@return */ public static Result save(){ final Map<String, String[]> values = request().body().asFormUrlEncoded(); final String name = values.get("name")[0]; final String description = values.get("desc")[0]; // Float ist zu klein, schneidet die Hälfte ab!!! final double lat = Double.parseDouble(values.get("lat")[0]); final double lng = Double.parseDouble(values.get("lng")[0]); String created = "Lat: "+lat; // zeigt in der console an ob der server es bekommen hat Logger.info(created); try { long newId = Building.add(name, description, lat, lng); return ok(String.valueOf(newId)); // return ok("Neues Gebäude'"+name+"' wurde erfolgreich angelegt!"); } catch (SQLException e) { // TODO Auto-generated catch block return badRequest(e.toString()); } } public static Result saveuser(){ final Map<String, String[]> values = request().body().asFormUrlEncoded(); final String name = values.get("buildingName")[0]; final String description = values.get("pac-input")[0]; // Float ist zu klein, schneidet die Hälfte ab!!! final double lat = Double.parseDouble(values.get("latFld")[0]); final double lng = Double.parseDouble(values.get("lngFld")[0]); String created = "Lat: "+lat; // zeigt in der console an ob der server es bekommen hat Logger.info(created); try { Building.add(name, description, lat, lng); return ok(lab.render(Building.all(),Room.all(),Building.count())); } catch (SQLException e) { // TODO Auto-generated catch block return badRequest(e.toString()); } } public static Result saveEditBuilding(){ final Map<String, String[]> values = request().body().asFormUrlEncoded(); final Long id = Long.parseLong(values.get("id")[0]); final String name = values.get("name")[0]; final String description = values.get("desc")[0]; // Float ist zu klein, schneidet die Hälfte ab!!! final double lat = Double.parseDouble(values.get("lat")[0]); final double lng = Double.parseDouble(values.get("lng")[0]); // zeigt in der console an ob der server es bekommen hat Logger.info("Building with ID: "+id +" will be updated with 'Name:' "+ name+", 'Description:' "+description+", 'Lat:' "+lat+", 'Lng:' "+lng); try { Building.update(id, name, description, lat, lng); return ok("Änderungen gespeichert!"); } catch (Exception e) { // TODO Auto-generated catch block return badRequest(e.toString()); } } public static Result deleteBuilding(){ final Map<String, String[]> values = request().body().asFormUrlEncoded(); final Long idToDelete = Long.parseLong(values.get("id")[0]); final String nameToDelete = values.get("name")[0]; Boolean hasRoomsInUse = null; try { hasRoomsInUse = Building.checkRoomsUsedInSession(idToDelete); } catch (SQLException e1) { // TODO Auto-generated catch block return badRequest("ERROR CHECKING IF ROOMS IN USE:\n"+e1.toString()); } if(!hasRoomsInUse){ try{ Building.delete(idToDelete); return ok("Das Gebäude "+nameToDelete+" wurde ins Archiv verschoben!\n" + "Es können nun keine Studien mehr in ihm stattfinden."); } catch (SQLException e){ return badRequest("BUILDING TO ARCHIVE ERROR! "+e.toString()); } } else if(hasRoomsInUse) return badRequest("In diesem Gebäude finden noch Studien statt, deren Sessions noch nicht abgelaufen sind!"); else{ return badRequest("BOOLEAN CHECKING IF ROOMS IN USE == NULL: 'SOMETHING WENT VERY WRONG' "); } } public static Result saveNewRoom(){ final Map<String, String[]> values = request().body().asFormUrlEncoded(); final String name = values.get("roomName")[0]; final String description = values.get("roomDescription")[0]; final Long building_id = Long.parseLong(values.get("building_id")[0]); String created = name+" ; "+building_id+" ; "+description; // zeigt in der console an ob der server es bekommen hat Logger.info(created); try { long newId = Room.add(name, description, building_id); return ok(String.valueOf(newId)); } catch (SQLException e) { // TODO Auto-generated catch block return badRequest("Fehler beim Anlegen des Raumes:\n"+ e.toString()); } } public static Result saveEditRoom(){ final Map<String, String[]> values = request().body().asFormUrlEncoded(); final Long id = Long.parseLong(values.get("id")[0]); final String name = values.get("name")[0]; final String description = values.get("desc")[0]; try { Room.update(id, name, description); return ok("Die Änderungen wurden gespeichert!"); } catch (SQLException e) { // TODO Auto-generated catch block return badRequest(e.toString()); } } public static Result deleteRoom(){ final Map<String, String[]> values = request().body().asFormUrlEncoded(); final Long idToDelete = Long.parseLong(values.get("id")[0]); final String nameToDelete = values.get("name")[0]; Boolean roomInUse = null ; try { roomInUse = Room.checkRoomInUse(idToDelete); if(roomInUse) return badRequest("In diesem Raum finden noch Studien statt, deren Sessions noch nicht abgelaufen sind!"); else{ Room.delete(idToDelete); return ok("Der Raum "+nameToDelete+" wurde ins Archiv verschoben.\n" + "In ihm können keine weiteren Studien mehr stattfinden"); } } catch (SQLException e) { return badRequest(e.toString()); } } /** * Displays the admin lmap * * @return */ public static Result mapTest() { return ok(views.html.admin.mapTest.render()); } /** * Displays konto config * * @return */ public static Result konto() { return ok(views.html.admin.konto.render()); } }
dan91/PlayStartApp
app/controllers/Admin.java
2,244
/** * Displays the admin mainview * * @return */
block_comment
en
false
73768_6
/** A class that creates an Odometer object to track fuel and mileage for a car. * Class contains instance variables to track the miles driven and the fuel * efficiency in miles per gallon. Class includes mutator methods to reset the * odometer to 0 miles, to set the fuel efficiency and to accept miles driven * for a trip and add it to odometer total. Class includes an accessor method * that returns the number of gallons of gas the car has consumed since the * odometer was last reset. See test program "OdometerTest.java" that creates * several trips with different fuel efficiencies. */ package odometertest; import java.util.Scanner; /** * * @author k8port */ public class Odometer { // class variable private double miles; // the miles driven in a trip private double mpg; // the fuel efficiency of the vehicle in miles per gallon // constructors /** No argument constructor sets miles driven to 0 and fuel efficiency to * average combined fuel efficiency for 2014 vehicles. */ public Odometer() { miles = 0; mpg = 29.5; } // mutator and accessor methods /** No argument method to reset the odometer to 0. * */ public void resetZero() {miles = 0;}; /** Method that allows user to set the fuel efficiency of a vehicle. * Uses Scanner to get input from user instead of argument. */ public void setMPG() { Scanner scan = new Scanner(System.in); System.out.println("Set the fuel efficiency of your vehicle."); System.out.println("What is the combined (city/highway) fuel efficiency of the car?"); mpg = scan.nextDouble(); while (mpg < 10 || mpg > 150) { System.out.println("Error entering fuel efficiency. Please reenter."); mpg = scan.nextDouble(); } } /** Method that allows user to input miles driven for a trip and adds it to * the odometer total. Also tells user how much gas was used for these miles. */ public void acceptMiles() { double trip; Scanner scan = new Scanner(System.in); System.out.println("How many miles were driven on this trip?"); trip = scan.nextDouble(); while (trip < 0) { System.out.println("You must enter a positive number or 0 if no trip was taken."); trip = scan.nextDouble(); } miles += trip; } /** Method that allows user to request price of gas based on current odometer * reading. * @return the number of gallons of gas used since odometer was last set */ public double getGallons() {return miles/mpg;} // other methods /** Method to test equality of Odometer objects. * @param other the other Odometer * @return true if objects are the same */ public boolean equals(Odometer other) { return (mpg == other.mpg && miles == other.miles); } /** Method that returns String representation of Odometer object. * @return String representing Odometer object. */ @Override public String toString() { return miles + " miles driven at " + mpg + " miles per gallon."; } }
k8port/Java
Odometer.java
806
/** No argument constructor sets miles driven to 0 and fuel efficiency to * average combined fuel efficiency for 2014 vehicles. */
block_comment
en
false
73824_0
/** * All Gold has a value and can be picked up to acquire that value. */ public class Gold extends Pickup { public static final String TITLE = "Gold"; public static final String NAME = "gold"; public static final String DEFAULT_IMAGE_PATH = "coin.png"; @Override public String title() { return TITLE; } @Override public String name() { return NAME; } @Override public String defaultImagePath() { return DEFAULT_IMAGE_PATH; } private int value; public Gold(int x, int y) { super(x, y); value = 0; } public Gold(int x, int y, int val) { super(x, y); value = val; } public int getValue() { return value; } }
IceCreamYou/LodeRunner
Gold.java
217
/** * All Gold has a value and can be picked up to acquire that value. */
block_comment
en
false
74006_7
/* * Written by Ed Hong UWT Feb. 19, 2003. * Modified by Donald Chinn May 14, 2003. * Modified by Donald Chinn December 11, 2003. * Modified by Donald Chinn February 28, 2004. */ /** * Class that represents an edge in a graph. * An object (usually some sort of data) can be associated with the edge. * * A label (also represented by an object (e.g., a string) can also be * associated with an edge. This could be useful, for example, if you * need to mark an edge as being visited in some graph traversal. * * @author edhong * @version 0.0 */ public class Edge { /** the first endpoint of the edge */ private Vertex v1; /** the second endpoint of the edge */ private Vertex v2; private Object data; // an object associated with this edge private Object name; // a name associated with this edge /** * Constructor that allows data and a name to be associated * with the edge. * @param v the first endpoint of this edge * @param w the second endpoint of this edge * @param data data to be associated with this edge * @param name a name to be associated with this edge */ public Edge (Vertex v, Vertex w, Object data, Object name) { this.data = data; this.name = name; this.v1 = v; this.v2 = w; } /** * Return the first endpoint of this edge. * @return the first endpoint of this edge */ public Vertex getFirstEndpoint() { return this.v1; } /** * Return the second endpoint of this edge. * @return the second endpoint of this edge */ public Vertex getSecondEndpoint() { return this.v2; } /** * Return the data associated with this edge. * @return the data of this edge */ public Object getData() { return this.data; } /** * Set the data associated with this edge. * @param data the data of this edge */ public void setData(Object data) { this.data = data; } /** * Return the name associated with this edge. * @return the name of this edge */ public Object getName() { return this.name; } }
iceColdChris/KruskalsAlgorithm
Edge.java
581
/** * Return the first endpoint of this edge. * @return the first endpoint of this edge */
block_comment
en
false
74095_0
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Plant here. * * @author (your name) * @version (a version number or a date) */ public class Plant extends animatedObject { public int maxHp; public boolean isAlive = true; public int hp; public int damage; public boolean opaque = false; public MyWorld MyWorld; public Plant() { } /** * Act - do whatever the Plant wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { if (getWorld() != null) { if (isLiving()) { update(); if (!opaque) { getImage().setTransparency(255); } else { getImage().setTransparency(125); } } else { MyWorld = (MyWorld)getWorld(); AudioPlayer.play(80,"gulp.mp3"); MyWorld.board.removePlant(getXPos(), getYPos()); MyWorld.removeObject(this); return; } } } public void update() { } public int getXPos() { return ((getX()-Board.xOffset)/Board.xSpacing); } public int getYPos() { return ((getY()-Board.yOffset)/Board.ySpacing); } @Override public void addedToWorld(World world) { MyWorld = (MyWorld)getWorld(); MyWorld.addObject(new Dirt(), getX(), getY()+30); } public boolean isLiving() { if (hp <=0) { isAlive = false; } else { isAlive = true; } return isAlive; } public void hit(int dmg) { } }
TheExploration/Plants-Vs-Zombies
Plant.java
438
// (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
line_comment
en
true
74409_2
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class BOM here. * * @author (your name) * @version (a version number or a date) */ public class BOM extends Actor { /** * Act - do whatever the BOM wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { setLocation(getX(), getY()+8); jatuh(); } public void jatuh() { Actor KARAKTER = getOneIntersectingObject(KARAKTER.class); if(KARAKTER != null){ getWorld().removeObject(this); NYAWA.nyawa_berkurang(); }else if(isAtEdge()){ getWorld().removeObject(this); } } }
NCAF/GAFCOM_KELOMPOK-10
BOM.java
217
/** * Act - do whatever the BOM wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */
block_comment
en
true
74939_2
package chickenfactory; import java.util.*; public class Menu { //*NOTE: NO SETTER METHOD //INSTANCE VARIABLES OF ARRAYLISTS OF DIFFERENT MENU private ArrayList<Food> regularMenu = new ArrayList<Food>(); private ArrayList<Food> limitedMenu = new ArrayList<Food>(); private ArrayList<Food> specialMenu = new ArrayList<Food>(); //ADDS THE FOOD OBJECTS TO THE DIFFERENT MENU ACCORDING TO THE PRICE OF THE ITEM public void add(Food items) { if(items.getPrice()<100) { regularMenu.add(items); }else if (items.getPrice()>100 && items.getPrice()<1000) { limitedMenu.add(items); }else if (items.getPrice()>1000) { specialMenu.add(items); } } //Gives me the price of the item the user chose public double itemPriceRegular(int index1) { return regularMenu.get(index1).getPrice(); } public double itemPriceLimited(int index2) { return limitedMenu.get(index2).getPrice(); } public double itemPriceSpecial(int index3) { return specialMenu.get(index3).getPrice(); } //GETTER METHOD //--> prints out the menu so the customer is able to order from it public void getRegular() { System.out.println(regularMenu); } public void getLimited() { System.out.println(limitedMenu); } public void getSpecial() { System.out.println(specialMenu); } //--> Get's the size of the menu. Helps solve index out of bound issues public int getRegularMenuSize() { return regularMenu.size(); } public int getLimitedMenuSize() { return limitedMenu.size(); } public int getSpecialMenuSize() { return specialMenu.size(); } }
cattiskatt/chickenfactory2.0
Menu.java
494
//ADDS THE FOOD OBJECTS TO THE DIFFERENT MENU ACCORDING TO THE PRICE OF THE ITEM
line_comment
en
false
75075_0
/* powered by Rahmat Email: [email protected] Github: https://github.com/EnAnsari question link: https://quera.org/problemset/31021/ */ import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String n = sc.nextLine(); int nn = Integer.parseInt(n); String myInput = sc.nextLine(); String[] splited = myInput.split("\\s+"); if (nn < 0 || nn > 50) return; for (int i = 2; i <= nn; i++) { for (int j = i - 1; j >= 1; j--) { System.out.println(splited[i - 1] + ": salam " + splited[j - 1] + "!"); } } for (int i = 1; i <= nn; i++) { System.out.println(splited[i - 1] + ": khodafez bacheha!"); for (int j = i + 1; j <= nn; j++) { System.out.println(splited[j - 1] + ": khodafez " + splited[i - 1] + "!"); } } } }
EnAnsari/quera
bank/092/main.java
326
/* powered by Rahmat Email: [email protected] Github: https://github.com/EnAnsari question link: https://quera.org/problemset/31021/ */
block_comment
en
true
75134_4
// 1 * 4 <-- encodings of various directions around a cell // 2 // // +--+--+ +--+--+ // | | |11 12| 11 12 a maze and its representation // +--+ + +--+ + // | | |11 06| 11 06 // +--+--+ +--+--+ // // 16 16 16 16 initial maze contents returned by constructor // 16 15 15 16 // 16 15 15 16 // 16 16 16 16 // /*============================================================*/ import java.util.Random; import java.util.*; public class Maze { private int[][] m; // maze representation private boolean[][] marked; // have we visited this cell yet private int rows; // number of rows in the maze private int cols; // number of columns in the maze private final static byte[] TWO = { 1, 2, 4, 8, 16}; private final static byte[] DX = { 0,+1, 0,-1}; private final static byte[] DY = {-1, 0,+1, 0}; private boolean done; // used in finding a single solution. private long count; // used in finding the number of solutions. private Random r; // for generating random integers. public int getRows() { return( rows ); } public int getCols() { return( cols ); } public Maze ( int nr, int nc, int seed ) { r = new Random( seed ); rows = nr; cols = nc; m = new int[nr+2][nc+2]; for (int r=1; r<=nr; ++r ) { for (int c=1; c<=nc; ++c ) { m[r][c] = 15; } } for (int r=0; r<nr+2; ++r ) { m[r][0] = m[r][nc+1] = 16; } for (int c=0; c<nc+2; ++c ) { m[0][c] = m[nr+1][c] = 16; } Create( nr/2+1, nc/2+1, 0 ); } // Wall in direction p? public boolean ok ( int x, int y, int p ) { return( (m[x][y] & TWO[p]) == TWO[p] ); } private boolean downWall( int x, int y, int p ) { if (ok(x,y,p) && m[x+DX[p]][y+DY[p]] != 16) { m[x][y] ^= TWO[p]; m[x+DX[p]][y+DY[p]] ^= TWO[p^2]; return true; } return false; } private void knockDown( int count ) { // Caution: make sure there are at least count walls! for (int i=0; i<count; ++i) { int x = 1+r.nextInt(rows); int y = 1+r.nextInt(cols); if (!downWall( x, y, r.nextInt(4))) --i; } } private void Create ( int x, int y, int val ) { int[] perm = randPerm( 4 ); m[x][y] ^= val; for (int i=0; i<4; ++i) { int p = perm[i]; if (m[x+DX[p]][y+DY[p]] == 15) { m[x][y] ^= TWO[p]; Create( x+DX[p], y+DY[p], TWO[p^2] ); } } } private int[] randPerm( int n ) { // This algorithm should look familiar! int[] perm = new int[n]; for (int k=0; k<n; ++k) perm[k] = k; for (int k=n; k>0; --k) { int rand = r.nextInt(k); int t = perm[rand]; perm[rand] = perm[k-1]; perm[k-1] = t; } return( perm ); } public String toString() { StringBuilder sb = new StringBuilder(); for (int i = 1; i <= rows; i++) { for (int j = 1; j <= cols; j++) { String out = m[i][j] > 9 ? (m[i][j] + " ") : (m[i][j] + " "); sb.append(out); } sb.append(System.getProperty("line.separator")); } return sb.toString(); } private void back(int x, int y) { if (x > rows || y > cols || x < 1 || y < 1) return; m[x][y] += 16; if (x == rows && y == cols) { count++; m[x][y] -= 16; return; } for (int i = 0; i < 4; i++) { if (((m[x][y] & TWO[i]) == 0) && m[x + DX[i]][y + DY[i]] < 16) { back(x + DX[i], y + DY[i]); } } m[x][y] -= 16; } public void solveMaze() { int x = 1; int y = 1; solve(x, y); } public boolean solve(int x, int y) { m[x][y] += 16; if (x == rows && y == cols) { toString(); m[x][y] -= 16; return true; } for (int i = 0; i < 4; i++) { if (((m[x][y] & TWO[i]) == 0) && m[x + DX[i]][y + DY[i]] < 16) { boolean done = solve(x + DX[i], y + DY[i]); if (done) { m[x][y] -= 16; return true; } } } m[x][y] -= 16; return false; } public long numSolutions() { int x = 1; int y = 1; back(x, y); return count; } public static void main ( String[] args ) { int row = Integer.parseInt( args[0] ); int col = Integer.parseInt( args[1] ); Maze maz = new Maze( row, col, 9998 ); System.out.print( maz ); maz.solveMaze(); System.out.println( "Solutions = "+maz.numSolutions() ); maz.knockDown( (row+col)/4 ); maz.solveMaze(); System.out.print( maz ); System.out.println( "Solutions = "+maz.numSolutions() ); maz = new Maze( row, col, 9999 ); // creates the same maze anew. maz.solveMaze(); System.out.print( maz ); } }
john-curry/226a5
Maze.java
1,782
// | | |11 12| 11 12 a maze and its representation
line_comment
en
false
75469_0
package com.bridgelabz.employeewage; /*Calculate Daily Employee Wage Assume Wage per Hour is 20 Assume Full Day Hour is 8*/ public class DailyWage { public static void main(String[] args) { int IS_PRESENT = 1, EMP_RATE_PER_HOUR = 20; int emphrs = 0, empwage = 0; double employeeCheck = Math.floor(Math.random() * 10) % 2; if ( employeeCheck == 1) emphrs = 8; else emphrs = 0; empwage = emphrs * EMP_RATE_PER_HOUR ; System.out.println("Employee wage is " + empwage); } }
ullas28/EmployeeWage
DailyWage.java
179
/*Calculate Daily Employee Wage Assume Wage per Hour is 20 Assume Full Day Hour is 8*/
block_comment
en
true
75731_5
import java.util.Scanner; import java.util.StringTokenizer; public class Demo { public static void main(String[] args) { // int result; // Numbers rc = new Numbers(); // Scanner sc =new Scanner(System.in); // System.out.println("Enter number1 : "); // result = rc.Natural(); // System.out.println(result); // // } //} //class Numbers { // public int Natural() { // int sum=0; // for (int i = 0; i <= 10; i++) { // sum=sum+i; // } // return sum; // } //} Scanner sc = new Scanner(System.in); Numbers nc = new Numbers(); int result; System.out.println("Enter number1 : "); result = nc.Natural(); System.out.println(result); } } class Numbers { public int Natural() { int sum = 0; for (int i = 0; i <= 10; i++) { sum = sum + i; } return sum; } }
azlaan23/java_kanguage1
Demo.java
275
// System.out.println(result);
line_comment
en
true
76125_1
package electronics; class Electronics { private double price; public Electronics(double price) { this.price = price; } // Getter and setter for price public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } } class Television extends Electronics { private int screenSize; private String brand; public Television(double price, int screenSize, String brand) { super(price); this.screenSize = screenSize; this.brand = brand; } public void watch() { System.out.println("Watching TV on a " + screenSize + " inch " + brand + " television."); } // Getters and setters for screenSize and brand } class Smartphone extends Electronics { private String operatingSystem; private boolean isWaterproof; public Smartphone(double price, String operatingSystem, boolean isWaterproof) { super(price); this.operatingSystem = operatingSystem; this.isWaterproof = isWaterproof; } public void call() { System.out.println("Making a call on a smartphone with " + operatingSystem + " OS."); } // Getters and setters for operatingSystem and isWaterproof } public class Main { public static void main(String[] args) { Electronics[] devices = new Electronics[3]; devices[0] = new Television(1000.0, 55, "Samsung"); devices[1] = new Smartphone(800.0, "Android", true); devices[2] = new Television(1200.0, 65, "LG"); for (Electronics device : devices) { if (device instanceof Television) { Television tv = (Television) device; tv.watch(); } else if (device instanceof Smartphone) { Smartphone smartphone = (Smartphone) device; smartphone.call(); } } } }
ManuShamil/java-lab-assignment-06-03-2023
electronics/Main.java
488
// Getters and setters for screenSize and brand
line_comment
en
true
76404_0
/** * The driver of the SIT project. Is responsible for acting as the user interface and handling output. * * @version 0.1 * * @author Joseph Antaki * @author Abby Beizer * @author Jamie Tyler Walder */ import java.io.File; import java.util.*; public class SIT { /** * @param args Takes a series of tags, followed by a list of file or directory names. * Possible tags include -j,-a,-c designating the languages Java, Ada and C++ respectively, * -r to search all subfolders in the current directory, and -help or ? to display help information. * If no arguments are entered, all files will be selected by default. */ public static void main(String[] args) { Input input = new Input(); input.processInput(args); } /** * A static method called by other classes to present output to the user * * @param message A String to print to the user interface */ public static void notifyUser(String message) { System.out.println(message); } /** * Collects a response from the user to a given prompt. * The calling class must specify what valid responses are * @param message The prompting message * @param validResponses A list of acceptable responses that should be handled by the calling class upon return * @return The appropriate response provided by the user */ public static String getResponse(String message,List<String> validResponses) { //start scanner Scanner scanner = new Scanner(System.in); //set a response String response = ""; boolean invalid = true; //while the user doesn't provide this method with a valid response it will prompt them for a correct response while(invalid) { System.out.println(message); //collect next line response = scanner.nextLine(); //check for valid response invalid =! validResponses.contains(response); //yell at them if they don't get it right if(invalid) { System.out.println("invalid response."); } } scanner.close(); return response; } /** * Displays valid commands for using this application to the user */ public static void displayHelp() { notifyUser(""); notifyUser("This Software Integrity Tester (SIT) analyzes Java, Ada, and C++ source code"); notifyUser("for security weaknesses and vulnerabilities.\n"); notifyUser("Usage: SIT <language tags> <directories and filenames>\n"); notifyUser("Language Tags:"); notifyUser("\tLanguage tags specify the file types accepted by the current run of the SIT."); notifyUser("\tDesignating files which do not conform to the specified tags will generate an error."); notifyUser("\tAt least one language tag from the following is required and must precede any file paths:"); notifyUser("\t-j\tJava"); notifyUser("\t-a\tAda"); notifyUser("\t-c\tC++"); notifyUser("\tMultiple language tags may be specified, separated by spaces."); notifyUser("\t(ex. \"SIT -j -a <files>\" will allow both Java and Ada files to be analyzed)"); notifyUser(""); notifyUser("Directories and Files:"); notifyUser("\tIf no directory or file paths are specified, the files in the current directory will be analyzed."); notifyUser("\tDesignating a directory analyzes all files in that directory which conform to the specified language tags."); notifyUser("\tAny number of directory and file paths may be specified."); notifyUser(""); notifyUser("Additional Commands:"); notifyUser("\t-r\tWhen this command follows the path of a directory, the SIT will analyze all files in that directory"); notifyUser("\t\tand all of its subdirectories which conform to the specified language tags."); notifyUser(""); } }
TeamEmuRU/SWIntegrity
src/SIT.java
936
/** * The driver of the SIT project. Is responsible for acting as the user interface and handling output. * * @version 0.1 * * @author Joseph Antaki * @author Abby Beizer * @author Jamie Tyler Walder */
block_comment
en
true
76607_15
/** * */ package planning; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import common.GridMap; import common.Point; import common.Utils; /** * A* algorithm * @author ziyan * */ public class AStar { private final GridMap cspace; /** * A* algorithm * @param cspace cspace grid map */ public AStar(final GridMap cspace) { this.cspace = cspace; } /** * Compute optimal path * @param start start point * @param end end point * @return */ public Point[] compute(final Point start, final Point end) { final Node init = new Node(start); final Node goal = new Node(end); if(!init.isValid() || !goal.isValid()) return null; init.h = Utils.elength(init.x - goal.x, init.y - goal.y); final PriorityQueue<Node> queue = new PriorityQueue<Node>(); final Map<Node, Double> seen = new HashMap<Node, Double>(); seen.put(init, init.c + init.h); queue.add(init); Node head; while(true) { head = queue.poll(); if(head == null) return null; // no path if(head.equals(goal)) break; // found goal for(final Node child : head.getSuccessors(goal)) { final Double previous = seen.get(child); if(previous == null || previous > child.c + child.h) { queue.add(child); seen.put(child, child.c + child.h); } } } final Point[] points = new Point[head.level + 1]; while(head != null) { points[head.level] = head.getPoint(); head = head.parent; } return points; } /** * Search node * @author ziyan * */ private class Node implements Comparable<Node> { public int x, y; public double h, c; public Node parent; public int level; /** * Node constructor for start and end point * @param p */ public Node(final Point p) { this.x = (int)(p.x / cspace.getMPP()) + cspace.getWidth() / 2; this.y = cspace.getHeight() - ((int)(p.y / cspace.getMPP()) + cspace.getHeight() / 2); this.h = 0; this.c = 0; this.parent = null; this.level = 0; } /** * Node constructor for successor function * @param parent * @param x * @param y * @param c * @param goal */ private Node(final Node parent, final int x, final int y, final double c, final Node goal) { this.x = parent.x + x; this.y = parent.y + y; this.parent = parent; this.level = parent.level + 1; if(isValid()) { // potential field to avoid sticking to the wall double p = (double)(GridMap.INTRAVERSABLE - (int)cspace.getData(this.y, this.x)) / (double)(GridMap.INTRAVERSABLE - GridMap.TRAVERSABLE); p = 1.0 / p; this.c = parent.c + p * c; this.h = Utils.elength(this.x - goal.x, this.y - goal.y); } } /** * Check if point is outside of grid or part of an obstacle * @return */ public boolean isValid() { if(x < 0 || x >= cspace.getWidth()) return false; if(y < 0 || y >= cspace.getHeight()) return false; return cspace.getData(y, x) != GridMap.INTRAVERSABLE; } /** * Get successor of the current point * @param goal goal point used to calculate heurist * @return */ public Node[] getSuccessors(final Node goal) { final List<Node> nodes = new ArrayList<Node>(); final Node top = new Node(this, 0, -1, 1, goal); final Node bottom = new Node(this, 0, 1, 1, goal); final Node left = new Node(this, -1, 0, 1, goal); final Node right = new Node(this, 1, 0, 1, goal); final Node topLeft = new Node(this, -1, -1, 1.5, goal); final Node topRight = new Node(this, -1, 1, 1.5, goal); final Node bottomLeft = new Node(this, 1, -1, 1.5, goal); final Node bottomRight = new Node(this, 1, 1, 1.5, goal); if(top.isValid()) nodes.add(top); if(bottom.isValid()) nodes.add(bottom); if(left.isValid()) nodes.add(left); if(right.isValid()) nodes.add(right); if(topLeft.isValid()) nodes.add(topLeft); if(topRight.isValid()) nodes.add(topRight); if(bottomLeft.isValid()) nodes.add(bottomLeft); if(bottomRight.isValid()) nodes.add(bottomRight); return nodes.toArray(new Node[]{}); } /** * Convert to player coordinates * @return */ public Point getPoint() { return new Point(cspace.getMPP() * (x - cspace.getWidth() / 2), cspace.getMPP() * ((cspace.getHeight() - y) - cspace.getHeight() / 2)); } /* * (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(final Object obj) { return obj instanceof Node && ((Node)obj).x == this.x && ((Node)obj).y == this.y; } /* * (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return this.y * cspace.getWidth() + this.x; } /* * (non-Javadoc) * @see java.lang.Comparable#compareTo(java.lang.Object) */ public int compareTo(final Node o) { if(h + c < o.h + o.c) return -1; return 1; } } }
ziyan/mobile-robot-programming
src/planning/AStar.java
1,710
/* * (non-Javadoc) * @see java.lang.Comparable#compareTo(java.lang.Object) */
block_comment
en
true
76664_11
import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.ItemListener; import java.awt.event.ActionEvent; import java.awt.event.WindowEvent; import java.awt.event.ItemEvent; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; /// abstract windows toolkit import javax.swing.UnsupportedLookAndFeelException; import javax.swing.ScrollPaneLayout; import javax.swing.JColorChooser; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.UIManager; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel;/// the modern pack 'swing' import java.sql.PreparedStatement; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement;/// mysql database import java.io.FileNotFoundException; import java.io.BufferedReader; import java.io.PrintWriter; import java.io.FileReader; import java.io.File;/// input-output public class ENvy extends JFrame /*implements ActionListener*/{ /** * */ private static final long serialVersionUID = 1L; //==================================================================upper==================================================================================================== private JPanel upperPanel; private JCheckBox boldButton, italicButton; private Font font = new Font("Serif", Font.PLAIN, 14); private static final String[] color_names = {"Black", "Blue", "Cyan", "Dark Gray", "Gray", "Green", "Light Gray", "Magenta", "Orange", "Pink", "Red", "White", "Yellow"}; private static final Color[] colors = {Color.BLACK, Color.BLUE, Color.CYAN, Color.DARK_GRAY, Color.GRAY, Color.GREEN, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.RED, Color.WHITE, Color.YELLOW}; private JComboBox<String> lista_culori; private JButton new_window; //==================================================================center================================================================================================== private JScrollPane scrollablePane; private JTextArea textarea; private ScrollPaneLayout centrez; //===================================================================lower================================================================================================== private JButton changeColorJButton, saveJButton, filePickerJButton; private JPanel lowerPanel; private JFileChooser fileChooser; //===================================================================generic================================================================================================ private Color color = Color.LIGHT_GRAY; //==================================================================database================================================================================================ private static String db_name="root", db_password="nick7777777", db_connection="jdbc:mysql://127.0.0.1:3306/envy_database", db_table="envy_table"; public ENvy(){ //precalculated operations super("ENvy: The Text Editor"); //=================================================================generic operations================================================================================= CheckBoxHandler handler = new CheckBoxHandler(); lista_culori = new JComboBox<String>(color_names); lista_culori.setMaximumRowCount(5); try { UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); } catch(UnsupportedLookAndFeelException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } //==================================================================upper operations================================================================================= upperPanel = new JPanel(); //bold button stuff boldButton = new JCheckBox("bold", false); boldButton.addItemListener(handler); upperPanel.add(boldButton); //italic button stuff italicButton = new JCheckBox("italic", false); italicButton.addItemListener(handler); upperPanel.add(italicButton); //new window stuff new_window = new JButton("new window"); upperPanel.add(new_window); //other stuff upperPanel.add(lista_culori); upperPanel.setBackground(Color.BLACK); add(upperPanel, BorderLayout.NORTH);//we add the upper panel itself effectively to the JFrame //===================================================================center operations============================================================================ textarea = new JTextArea(); scrollablePane = new JScrollPane(textarea); centrez = new ScrollPaneLayout(); centrez.setHorizontalScrollBarPolicy(ScrollPaneLayout.HORIZONTAL_SCROLLBAR_AS_NEEDED); centrez.setVerticalScrollBarPolicy(ScrollPaneLayout.VERTICAL_SCROLLBAR_AS_NEEDED); scrollablePane.setLayout(centrez); add(scrollablePane, BorderLayout.CENTER); setSize(300, 120); setVisible(true); //====================================================================lower operations=============================================================================== lowerPanel = new JPanel(); changeColorJButton = new JButton("bkg color"); lowerPanel.add(changeColorJButton); saveJButton = new JButton("save"); lowerPanel.add(saveJButton); filePickerJButton = new JButton("select file"); lowerPanel.add(filePickerJButton); fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY ); //lowerPanel.setLayout( new FlowLayout() ); add(lowerPanel, BorderLayout.SOUTH); //anonymous listeners--------------------------------------------------------------------------------------------------------------------------------------------------------------- new_window.addActionListener(/// ~~~ new ActionListener() { public void actionPerformed(ActionEvent e) { try{ fir_exec fir = new fir_exec(multithreading.thG, "fir" + Integer.toString(multithreading.contor)); Thread new_th = new Thread(fir); new_th.start(); }catch(Exception exc){ JDialog show = new JDialog(); JLabel lab = new JLabel("Error!"); show.add(lab); show.setSize(200, 100); show.setVisible(true); } } });/// ~~~ changeColorJButton.addActionListener(// $$$ new ActionListener() { public void actionPerformed(ActionEvent e) { try{ color = JColorChooser.showDialog(ENvy.this, "Pick a color", color); if( color == null ) color = Color.LIGHT_GRAY; textarea.setBackground( color ); //String opt = "backgroundColour"; //databaseQuery(opt, color); }catch(Exception exc){ System.err.println(exc.getMessage()); } } });// $$$ lista_culori.addItemListener(// +++ new ItemListener() { public void itemStateChanged(ItemEvent e) { try{ textarea.setForeground( colors[ lista_culori.getSelectedIndex() ] ); }catch(Exception exc){ System.err.println(exc.getMessage()); } } });//+++ saveJButton.addActionListener(// ||| new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser fileChooser = new JFileChooser(); int option = fileChooser.showSaveDialog(getParent()); try { File f = null; if(option == JFileChooser.APPROVE_OPTION) f = fileChooser.getSelectedFile(); PrintWriter scriitor = new PrintWriter(f); scriitor.write(textarea.getText()); scriitor.close(); }catch(FileNotFoundException exc){ System.err.println( exc.getMessage() ); ENvy.errorMessage("The file could not be found!"); }catch(Exception exc) { System.err.println( exc.getMessage() ); ENvy.errorMessage("The type of file could not be opened!"); } } //JFrame.EXIT_ON_CLOSE; });// ||| filePickerJButton.addActionListener(/// @@@ new ActionListener() { public synchronized void actionPerformed(ActionEvent e) { File f = getFile(); try{ BufferedReader cititor = new BufferedReader( new FileReader(f) ); textarea.setText(""); String line = cititor.readLine(); while( line != null){ textarea.append(line); line = cititor.readLine(); } cititor.close(); }catch(Exception exc){ System.err.println( exc.getMessage() ); ENvy.errorMessage("Eroare de citire!"); } } });/// @@@ JFrame.setDefaultLookAndFeelDecorated(true); } //explicit listeners----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- private class CheckBoxHandler implements ItemListener{//listener for the checkable font option buttons(italic and bold) public void itemStateChanged(ItemEvent e) { try{ if(boldButton.isSelected() && italicButton.isSelected()) font = new Font(font.getFamily(), Font.BOLD + Font.ITALIC, font.getSize()); else if(boldButton.isSelected()) font = new Font(font.getFamily(), Font.BOLD, font.getSize()); else if(italicButton.isSelected()) font = new Font(font.getFamily(), Font.ITALIC, font.getSize()); else font = new Font(font.getFamily(), Font.PLAIN, font.getSize()); if(boldButton.isSelected()) { databaseQuery("bold", true); System.out.println("db"); } if(italicButton.isSelected()) { databaseQuery("italic", true); System.out.println("db"); } textarea.setFont(font); }catch(Exception exc){ System.err.println(exc.getMessage()); } } } //methods-------------------------------------------------------------------------------------------------------------------------------------------- //the method for the file chooser of "save" which returns the file within the textarea's content is saved private synchronized File getFile(){ // ~~~ JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY ); int result = fileChooser.showOpenDialog(this); if(result == JFileChooser.CANCEL_OPTION) System.exit(1); File fileName = fileChooser.getSelectedFile(); if( fileName == null || fileName.getName().equals("") ) { JOptionPane.showMessageDialog(this, "Invalid Name", "Invalid Name", JOptionPane.ERROR_MESSAGE); System.exit(1); } return fileName; }// ~~~ private static void errorMessage(String error_message){ JDialog dial = new JDialog(); JLabel lab = new JLabel(error_message); dial.add(lab); dial.setSize(300, 150); dial.setVisible(true); } private void databaseQuery(String optiune, boolean val) { try { Connection con = DriverManager.getConnection(db_connection, db_name, db_password);//Establishing connection String query = "INSERT INTO " + db_table+"(optiune) VALUES(\""+optiune+"\")"; PreparedStatement st = con.prepareStatement(query); st.executeUpdate(); con.close(); }catch(SQLException e) { System.out.println(e.getMessage()); } } }
Nico7777777/ENvy---the-text-editor
ENvy.java
2,612
//127.0.0.1:3306/envy_database", db_table="envy_table";
line_comment
en
true
78488_3
import java.util.Scanner; public class Demo { //first letters of a class should be capital //the main (Demo in this case) class should always be public i.e. a public class can be accessed by other files, classes, packages etc public static void main(String[] args){ /*we have the main method prefixed with public because it should be accessed by the JVM, and that cannot be done if the method is private We use static because the main method is called by the JVM before any objects are created. Usually we call a method using an object. But here, there is no object created yet. So, JVM calls the main method by itself. String[] is an array of strings. args is the name of the array. It can be anything. It is used to store command line arguments i.e. after typing java Demo arg1 arg2 arg3, arg1, arg2, arg3 are stored in the args array. main method is the entry point of the program */ System.out.println("Hello World!"); /*System is a class, out is an object of the PrintStream class, println is a method of the PrintStream class. When we say System.out, we are referring to the default output device of the system i.e. the console. println is used to print a line to the console. */ Scanner input = new Scanner(System.in); /*Scanner is a class, input is an object of the Scanner class, new is a keyword used to create an object, Scanner(System.in) is a constructor of the Scanner class System.in reads your inputs from the default input device i.e. the keyboard The left side 'Scanner input' is the declaration of the object. The right side 'new Scanner(System.in)' is the instantiation of the object. */ System.out.println(input.nextLine()); //input is the object of the Scanner class, nextLine is a method of the Scanner class. It is used to read a line of text. } } //When we type javac in the cmd, it checks the environment variables to find the path of the java compiler. If it finds it, it compiles the file. If it doesn't, it throws an error. //We add f at the end of a float number because by default, Java treats all floating point numbers as double. So, we add f to tell Java that it is a float number.
Defalt2-O/DSA_Code_Alongs
Demo.java
520
/*System is a class, out is an object of the PrintStream class, println is a method of the PrintStream class. When we say System.out, we are referring to the default output device of the system i.e. the console. println is used to print a line to the console. */
block_comment
en
true
79873_0
package a; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Vector; public final class c { public static Vector a(String paramString) { File localFile = new File(paramString); try { localFileInputStream = new FileInputStream(localFile); locala = new a(); arrayOfByte = new byte[20496]; do { locala.a(); i = 0; j = 0; if (j < 1048576) break; locala.b(); } while (i > 0); } catch (FileNotFoundException localFileNotFoundException) { try { while (true) { a locala; byte[] arrayOfByte; int i; int j; localFileInputStream.close(); return locala.c(); localFileNotFoundException = localFileNotFoundException; localFileNotFoundException.printStackTrace(); FileInputStream localFileInputStream = null; continue; try { int k = localFileInputStream.read(arrayOfByte, 0, 4096); i = k; if (i <= 0) continue; j += i; locala.a(new com.c.b(arrayOfByte, i)); } catch (IOException localIOException1) { while (true) localIOException1.printStackTrace(); } } } catch (IOException localIOException2) { while (true) localIOException2.printStackTrace(); } } } public static com.c.b b(String paramString) { File localFile = new File(paramString); FileInputStream localFileInputStream; b localb; try { localFileInputStream = new FileInputStream(localFile); arrayOfByte = new byte[20496]; localb = new b(); localb.a(); } catch (FileNotFoundException localFileNotFoundException) { try { while (true) { byte[] arrayOfByte; int j = localFileInputStream.read(arrayOfByte, 0, 16384); i = j; if (i <= 0) break; localb.a(new com.c.b(arrayOfByte, i)); } localFileNotFoundException = localFileNotFoundException; localFileNotFoundException.printStackTrace(); localFileInputStream = null; } catch (IOException localIOException1) { while (true) { localIOException1.printStackTrace(); int i = 0; } localb.b(); } } try { localFileInputStream.close(); return localb.c(); } catch (IOException localIOException2) { while (true) localIOException2.printStackTrace(); } } } /* Location: /Users/mdp/Downloads/iMessage/classes-dex2jar.jar * Qualified Name: a.c * JD-Core Version: 0.6.2 */
mdp/iMessageChatDecompile
src/a/c.java
691
/* Location: /Users/mdp/Downloads/iMessage/classes-dex2jar.jar * Qualified Name: a.c * JD-Core Version: 0.6.2 */
block_comment
en
true
79945_21
/* Main GUI display This should update and display the users info */ import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTextArea; import javax.swing.JTextField; public class MainGUI extends JFrame { private static ArrayList<Float> expenseValue; private static ArrayList<String> expenseName; // Strings are used to access database private String username; private String password; // Declaring buttons private JButton updateButton; private JButton logoutButton; private JButton displayButton; private JButton expensesButton; // Declaring textfields for user input private JTextField yearlySalaryText; private JTextField savingGoalText; private JTextField monthlyExpensesText; private JTextArea viewGoalsArea; final int FRAME_WIDTH; final int FRAME_LENGTH; public MainGUI(String username, String password) { expenseName = new ArrayList<String>(); expenseValue = new ArrayList<Float>(); this.username = username; this.password = password; FRAME_WIDTH = 700; FRAME_LENGTH = 500; // Creating textFields // bound them to the JFrame with .setBounds yearlySalaryText = new JTextField("Enter Yearly Salary"); yearlySalaryText.setBounds(10, 50, 200, 30); savingGoalText = new JTextField("Enter Monthly Saving Goal"); savingGoalText.setBounds(10, 100, 200, 30); // .setEditable prevents the user from messing with the output viewGoalsArea = new JTextArea(20, 20); viewGoalsArea.setBounds(350, 50, 320, 400); viewGoalsArea.setEditable(false); // Creating buttons updateButton = new JButton("Update"); updateButton.setBounds(10, 350, 100, 25); expensesButton = new JButton("Expenses"); expensesButton.setBounds(110, 350, 100, 25); logoutButton = new JButton("Logout"); logoutButton.setBounds(110, 400, 100, 25); displayButton = new JButton("Display"); displayButton.setBounds(10, 400, 100, 25); // Creating new instance of actionlisteners // Placing actionListeners to buttons logoutButton logoutListener = new logoutButton(); logoutButton.addActionListener(logoutListener); updateButton updateListener = new updateButton(); updateButton.addActionListener(updateListener); displayButton displayListener = new displayButton(); displayButton.addActionListener(displayListener); expensesButton expensesListener = new expensesButton(); expensesButton.addActionListener(expensesListener); // Add everything to frame add(yearlySalaryText); add(savingGoalText); add(viewGoalsArea); add(updateButton); add(logoutButton); add(displayButton); add(expensesButton); // Finalize Frame setLayout(null); setTitle("MAIN"); setSize(FRAME_WIDTH, FRAME_LENGTH); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setResizable(false); getContentPane().setBackground(Color.WHITE); setVisible(true); } // Action listeners // logoutButton disposes of the JFrame // Quick and easy way to 'log out' private class logoutButton implements ActionListener { public void actionPerformed(ActionEvent e) { dispose(); } } // updateButton should take the user input and place it in the database // int variables getting the user input are created // Throw number format exception if there is something but int in there // Try catch maybe? private class updateButton implements ActionListener { public void actionPerformed(ActionEvent e) { try { String url = "jdbc:sqlserver://localhost:1433;databaseName=App_DB;integratedSecurity=true;"; Connection conn = DriverManager.getConnection(url); Statement sta = conn.createStatement(); int salary = Integer.parseInt(yearlySalaryText.getText()); String updateSalaryQuery = "update " + username + " set Monthly_Salary = " + "'" + salary + "'" + " where ID = 1"; boolean in1 = sta.execute(updateSalaryQuery); int savings = Integer.parseInt(savingGoalText.getText()); String goalQuery = "update " + username + " set Monthly_Goal = " + "'" + savings + "'" + " where ID = 1"; boolean in2 = sta.execute(goalQuery); } catch (Exception exc) { exc.printStackTrace(); } } } public String getName(String username) { try { String url = "jdbc:sqlserver://localhost:1433;databaseName=App_DB;integratedSecurity=true;"; Connection conn = DriverManager.getConnection(url); Statement sta = conn.createStatement(); String getNameFL = "select userNameFL from User_table where userName = '" + username + "'"; ResultSet in = sta.executeQuery(getNameFL); while (in.next()) { username = in.getString("userNameFL"); return username; } } catch (Exception exc) { exc.printStackTrace(); } return null; } public String getSalary(String username) { try { String url = "jdbc:sqlserver://localhost:1433;databaseName=App_DB;integratedSecurity=true;"; Connection conn = DriverManager.getConnection(url); Statement sta = conn.createStatement(); String getSalary = "select Monthly_Salary from " + username + " where ID = 1"; ResultSet in = sta.executeQuery(getSalary); while (in.next()) { username = in.getString("Monthly_Salary"); return username; } } catch (Exception exc) { exc.printStackTrace(); } return null; } public String getSavings(String username) { try { String url = "jdbc:sqlserver://localhost:1433;databaseName=App_DB;integratedSecurity=true;"; Connection conn = DriverManager.getConnection(url); Statement sta = conn.createStatement(); String getSavings = "select Monthly_Goal from " + username + " where ID = 1"; ResultSet in = sta.executeQuery(getSavings); while (in.next()) { username = in.getString("Monthly_Goal"); return username; } } catch (Exception exc) { exc.printStackTrace(); } return null; } private class expensesButton implements ActionListener { public void actionPerformed(ActionEvent e) { Expenses myExpenses = new Expenses(username); } } public static void getExpenseName(String user, String expense) { try { String url = "jdbc:sqlserver://localhost:1433;databaseName=App_DB;integratedSecurity=true;"; Connection conn = DriverManager.getConnection(url); Statement sta = conn.createStatement(); String query = "select " + expense + " from " + user; ResultSet in = sta.executeQuery(query); while (in.next()) { user = in.getString("Expense_Name"); expenseName.add(user); } } catch (Exception exc) { exc.printStackTrace(); } } public static void getExpenseValue(String user) { try { // Get a connection to a database and create a statement String url = "jdbc:sqlserver://localhost:1433;databaseName=App_DB;integratedSecurity=true;"; Connection conn = DriverManager.getConnection(url); Statement sta = conn.createStatement(); for(int j = 0; j < expenseName.size(); j++) { String getExp = "select " + expenseName.get(j) + " from " + user; ResultSet in = sta.executeQuery(getExp); while (in.next()) { float i = in.getFloat(expenseName.get(j)); expenseValue.add(i); } } } catch (Exception exc) { exc.printStackTrace(); } } public static String getAllExpense() { String out = ""; for(int i = 0; i < expenseName.size(); i++) { out = expenseName.get(i) + " = " + expenseValue.get(i) + "\n"; } return out; } private class displayButton implements ActionListener { public void actionPerformed(ActionEvent e) { String savings = getSavings(username); String salary = getSalary(username); String name = getName(username); float monthlySalary = Float.parseFloat(salary) / 12; float monthlySavings = 12 * Float.parseFloat(savings); // This is a test that prints the username and password viewGoalsArea.setText("\tHello " + name + "\n" + "This is your current yearly salary: " + salary + "\n" + "This is your current savings goal: " + savings + "\n" + "This is how much you can save a year : " + monthlySavings); // Use viewGoalsArea.setText("Some string"); to display in text area } } }
JonathanPinder/DataStructuresProject
MainGUI.java
2,380
//localhost:1433;databaseName=App_DB;integratedSecurity=true;";
line_comment
en
true
81527_3
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.HashMap; import java.util.List; import java.util.Map; public class Leitura { //Constantes relevantes para o trab static final int FEDERAL = 6, ESTADUAL = 7, ISOLADO = -1; static final int[] DEFERIDO = {2, 16}, ELEITO = {2, 3}; static final String MASCULINO = "2", FEMININO = "4", FORMATO_DATA = "d/MM/yyyy", SEPARADOR_CSV_CD = ";", SEPARADOR_CSV_VOT = ";", VALIDO_LEGENDA = "Válido (legenda)"; static final char FED = 'F', EST = 'E', MAS = 'M', FEM = 'F'; //Colunas do arquivo de "candidato.csv" // Valor da coluna do arquivo csv - 1 static final private int CD_CARGO_CAND = 13, CD_SITUACAO_CANDIDADO_TOT = 68, NR_CANDIDATO = 16, NM_URNA_CANDIDATO = 18, NR_PARTIDO = 27, SG_PARTIDO = 28, NR_FEDERACAO = 30, DT_NASCIMENTO = 42, CD_SIT_TOT_TURNO = 56, CD_GENERO = 45, NM_TIPO_DESTINACAO_VOTOS = 67; //Colunas do arquivo de "votos.csv" // Valor da coluna do arquivo csv - 1 static final private int CD_CARGO_VOT = 17; static final int[] IGNORAR_NR_VOTAVEL = {95,96,97,98}; //Colunas irrelevantes static final int NR_VOTAVEL = 19, QT_VOTOS = 21, NM_VOTAVEL = 20; private Map<Integer,Candidato> extra = new HashMap<>();//candidatos (do cargo de opcao) não deferidos e que os votos sao direcionados para legenda do partido static boolean NOMINAL = true, LEGENDA = false; private boolean ignorarNrVotavel(Integer x){ for(int i = 0; i < 3; i++){ if(x == IGNORAR_NR_VOTAVEL[i]) return true; } return false; } private boolean deferido(Integer x ) { if(x != DEFERIDO[0] && x != DEFERIDO[1]){ return false; } return true; } public void readCand(boolean federal, Map<Integer,Partido> part, List<Partido> partRanking, Map<Integer,Candidato> cand, List<Candidato> candEleitos,String fcand, String enconding){ FileInputStream c; BufferedReader inputc; String line = ""; //ler candidatos try{ c = new FileInputStream(fcand); inputc = new BufferedReader(new InputStreamReader(c, enconding)); line = inputc.readLine(); String rep = "\""; String rrep = ""; DateTimeFormatter formatter = DateTimeFormatter.ofPattern(FORMATO_DATA); while((line = inputc.readLine()) != null){ line = line.replace(rep,rrep); String[] row = line.split(SEPARADOR_CSV_CD); Integer situacao = Integer.parseInt(row[CD_SITUACAO_CANDIDADO_TOT]); Partido partido; //verifica se o partido existe if(part.containsKey(Integer.parseInt( row[NR_PARTIDO] ) ) == true ){ partido = part.get( Integer.parseInt( row[NR_PARTIDO] ) ); } else { partido = cPartido(row); part.put( Integer.parseInt(row[NR_PARTIDO]) , partido); partRanking.add(partido); } int cd = Integer.parseInt(row[CD_CARGO_CAND]); if( cd != FEDERAL && cd != ESTADUAL ){ //nao necessario para o processamento atual continue; } else if( cd == FEDERAL && federal == false){ continue; } else if( cd == ESTADUAL && federal == true){ continue; } Character cargo = (cd == FEDERAL?FED:EST); if(deferido(situacao)==false ){ if(row[NM_TIPO_DESTINACAO_VOTOS].compareTo(VALIDO_LEGENDA) == 0 ){ Candidato curr = cCandidato(row, cargo, partido, formatter); extra.put(curr.getNumero(), curr); } continue; } else { Candidato curr = cCandidato(row, cargo, partido, formatter); curr.getPartido().addCandidato(curr); if(curr.eleito()) candEleitos.add(curr); cand.put(curr.getNumero(), curr); } } } catch(FileNotFoundException e){ System.out.println("Arquivo " + fcand + " nao encontrado"); System.exit(1); } catch(IOException e){ System.out.println("Erro ao ler arquivo " + fcand + "!\n"); System.exit(1); } } private Partido cPartido(String[] row){ return new Partido(row[SG_PARTIDO].trim(), Integer.parseInt(row[NR_PARTIDO]) ); } private Candidato cCandidato(String[] row, Character cargo, Partido partido, DateTimeFormatter formatter){ String nome = row[NM_URNA_CANDIDATO].trim(); Character genero = (row[CD_GENERO].compareTo(MASCULINO) == 0 ? MAS:FEM); LocalDate nascimento = LocalDate.parse(row[DT_NASCIMENTO], formatter); Integer numero = Integer.parseInt(row[NR_CANDIDATO]);; Integer numero_federacao = Integer.parseInt(row[NR_FEDERACAO]); Integer votos = 0; //verifica o direcionamento de votos //String vl = ; boolean nominal; if(row[NM_TIPO_DESTINACAO_VOTOS].compareTo(VALIDO_LEGENDA) == 0) nominal = LEGENDA; else nominal = NOMINAL; Boolean eleito = ( (Integer.parseInt(row[CD_SIT_TOT_TURNO]) == ELEITO[0] || Integer.parseInt(row[CD_SIT_TOT_TURNO]) == ELEITO[1]) ? true: false); return new Candidato(cargo, nome, genero, nascimento, partido, numero, numero_federacao, votos, nominal, eleito); } public void readVotos(boolean federal, Map<Integer, Partido> part, List<Partido> partRanking,Map<Integer,Candidato> cand, String fvotos, String enconding){ FileInputStream v; BufferedReader inputv; //ler votos try{ v = new FileInputStream(fvotos); inputv = new BufferedReader(new InputStreamReader(v, enconding)); String rep = "\""; String rrep = ""; String line = ""; line = inputv.readLine(); while( (line = inputv.readLine()) != null){ line = line.replace(rep,rrep); String[] row = line.split(SEPARADOR_CSV_VOT); Integer num = Integer.parseInt(row[NR_VOTAVEL]); if(ignorarNrVotavel(num) == true){ continue; } int cd = Integer.parseInt(row[CD_CARGO_VOT]); if( cd != FEDERAL && cd != ESTADUAL ){ //nao necessario para o processamento atual continue; } else if( ( cd == FEDERAL && federal==false) || (cd == ESTADUAL && federal) ){ //nao necessario para o processamento atual continue; } Integer votos = Integer.parseInt(row[QT_VOTOS]); pAll(part, cand, num, votos); } } catch(FileNotFoundException e){ System.out.println("Arquivo " + fvotos + " nao encontrado\n"); System.exit(1); } catch (IOException e) { System.out.println("Erro ao ler arquivo " + fvotos + "!\n"); System.exit(1); } } private void pAll(Map<Integer, Partido> part, Map<Integer,Candidato> cand, Integer num, Integer votos){ //candidatos não deferidos com direcionamento de votos para legenda if(extra.containsKey(num) == true){ pCandidatoIndeferido(part,num,votos); } //candidatos deferidos else if( cand.containsKey(num) == true ){ pCandidatoDeferido(part,cand, num, votos); } //votos em legenda else if (part.containsKey(num) == true){ pPartido(part, num, votos); } } private void pCandidatoIndeferido(Map<Integer, Partido> part, Integer num, Integer votos){ extra.get(num).getPartido().incVotosLegenda(votos); } private void pCandidatoDeferido(Map<Integer, Partido> part, Map<Integer,Candidato> cand, Integer num, Integer votos){ //trocar para boolean if( cand.get(num).getFlagNominal() == LEGENDA) { cand.get(num).getPartido().incVotosLegenda(votos); } else { cand.get(num).incVotos(votos); cand.get(num).getPartido().incVotosNominais(votos); } } private void pPartido(Map<Integer, Partido> part, Integer num, Integer votos){ part.get(num).incVotosLegenda(votos); } }
Pedro2um/Trab1OOP
src/Leitura.java
2,598
//Colunas do arquivo de "votos.csv"
line_comment
en
true
81556_27
/* * Conditions Of Use * * This software was developed by employees of the National Institute of * Standards and Technology (NIST), an agency of the Federal Government. * Pursuant to title 15 Untied States Code Section 105, works of NIST * employees are not subject to copyright protection in the United States * and are considered to be in the public domain. As a result, a formal * license is not needed to use the software. * * This software is provided by NIST as a service and is expressly * provided "AS IS." NIST MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED * OR STATUTORY, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT * AND DATA ACCURACY. NIST does not warrant or make any representations * regarding the use of the software or the results thereof, including but * not limited to the correctness, accuracy, reliability or usefulness of * the software. * * Permission to use this software is contingent upon your acceptance * of the terms of this agreement * * . * */ /*************************************************************************** * Product of NIST/ITL Advanced Networking Technologies Division(ANTD). * **************************************************************************/ package gov.nist.core; import java.net.*; /* * IPv6 Support added by Emil Ivov ([email protected])<br/> * Network Research Team (http://www-r2.u-strasbg.fr))<br/> * Louis Pasteur University - Strasbourg - France<br/> * * Frank Feif reported a bug. * * */ /** * Stores hostname. * @version 1.2 * * @author M. Ranganathan * @author Emil Ivov <[email protected]> IPV6 Support. <br/> * * * * Marc Bednarek <[email protected]> (Bugfixes).<br/> * */ public class Host extends GenericObject { /** * Determines whether or not we should tolerate and strip address scope * zones from IPv6 addresses. Address scope zones are sometimes returned * at the end of IPv6 addresses generated by InetAddress.getHostAddress(). * They are however not part of the SIP semantics so basically this method * determines whether or not the parser should be stripping them (as * opposed simply being blunt and throwing an exception). */ private static boolean stripAddressScopeZones = false; private static final long serialVersionUID = -7233564517978323344L; protected static final int HOSTNAME = 1; protected static final int IPV4ADDRESS = 2; protected static final int IPV6ADDRESS = 3; static { stripAddressScopeZones = Boolean.getBoolean("gov.nist.core.STRIP_ADDR_SCOPES"); } /** hostName field */ protected String hostname; /** address field */ protected int addressType; private InetAddress inetAddress; /** default constructor */ public Host() { addressType = HOSTNAME; } /** Constructor given host name or IP address. */ public Host(String hostName) throws IllegalArgumentException { if (hostName == null) throw new IllegalArgumentException("null host name"); setHost(hostName, IPV4ADDRESS); } /** constructor * @param name String to set * @param addrType int to set */ public Host(String name, int addrType) { setHost(name, addrType); } /** * Return the host name in encoded form. * @return String */ public String encode() { return encode(new StringBuilder()).toString(); } public StringBuilder encode(StringBuilder buffer) { if (addressType == IPV6ADDRESS && !isIPv6Reference(hostname)) { buffer.append('[').append(hostname).append(']'); } else { buffer.append(hostname); } return buffer; } /** * Compare for equality of hosts. * Host names are compared by textual equality. No dns lookup * is performed. * @param obj Object to set * @return boolean */ public boolean equals(Object obj) { if ( obj == null ) return false; if (!this.getClass().equals(obj.getClass())) { return false; } Host otherHost = (Host) obj; return otherHost.hostname.equals(hostname); } /** get the HostName field * @return String */ public String getHostname() { return hostname; } /** get the Address field * @return String */ public String getAddress() { return hostname; } /** * Convenience function to get the raw IP destination address * of a SIP message as a String. * @return String */ public String getIpAddress() { String rawIpAddress = null; if (hostname == null) return null; if (addressType == HOSTNAME) { try { if (inetAddress == null) inetAddress = InetAddress.getByName(hostname); rawIpAddress = inetAddress.getHostAddress(); } catch (UnknownHostException ex) { dbgPrint("Could not resolve hostname " + ex); } } else { if (addressType == IPV6ADDRESS){ try { String ipv6FullForm = getInetAddress().toString(); int slashIndex = ipv6FullForm.indexOf("/"); if (slashIndex != -1) { ipv6FullForm = ipv6FullForm.substring(++slashIndex, ipv6FullForm.length()); } if (hostname.startsWith("[")) { rawIpAddress = '[' + ipv6FullForm + ']'; } else { rawIpAddress = ipv6FullForm; } } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { rawIpAddress = hostname; } } return rawIpAddress; } /** * Set the hostname member. * @param h String to set */ public void setHostname(String h) { setHost(h, HOSTNAME); } /** Set the IP Address. *@param address is the address string to set. */ public void setHostAddress(String address) { setHost(address, IPV4ADDRESS); } /** * Sets the host address or name of this object. * * @param host that host address/name value * @param type determines whether host is an address or a host name */ private void setHost(String host, int type){ //set inetAddress to null so that it would be reinited //upon next call to getInetAddress() inetAddress = null; if (isIPv6Address(host)) addressType = IPV6ADDRESS; else addressType = type; // Null check bug fix sent in by [email protected] if (host != null){ hostname = host.trim(); //if this is an FQDN, make it lowercase to simplify processing if(addressType == HOSTNAME) hostname = hostname.toLowerCase(); //remove address scope zones if this is an IPv6 address as they //are not allowed by the RFC int zoneStart = -1; if(addressType == IPV6ADDRESS && stripAddressScopeZones && (zoneStart = hostname.indexOf('%'))!= -1){ hostname = hostname.substring(0, zoneStart); //if the above was an IPv6 literal, then we would need to //restore the closing bracket if( hostname.startsWith("[") && !hostname.endsWith("]")) hostname += ']'; } } } /** * Set the address member * @param address address String to set */ public void setAddress(String address) { this.setHostAddress(address); } /** Return true if the address is a DNS host name * (and not an IPV4 address) *@return true if the hostname is a DNS name */ public boolean isHostname() { return addressType == HOSTNAME; } /** Return true if the address is a DNS host name * (and not an IPV4 address) *@return true if the hostname is host address. */ public boolean isIPAddress() { return addressType != HOSTNAME; } /** Get the inet address from this host. * Caches the inet address returned from dns lookup to avoid * lookup delays. * *@throws UnkownHostexception when the host name cannot be resolved. */ public InetAddress getInetAddress() throws java.net.UnknownHostException { if (hostname == null) return null; if (inetAddress != null) return inetAddress; inetAddress = InetAddress.getByName(hostname); return inetAddress; } //----- IPv6 /** * Verifies whether the <code>address</code> could * be an IPv6 address */ private boolean isIPv6Address(String address) { return (address != null && address.indexOf(':') != -1); } /** * Verifies whether the ipv6reference, i.e. whether it enclosed in * square brackets */ public static boolean isIPv6Reference(String address) { return address.charAt(0) == '[' && address.charAt(address.length() - 1) == ']'; } @Override public int hashCode() { return this.getHostname().hashCode(); } }
RestComm/jain-sip
src/gov/nist/core/Host.java
2,173
/** * Set the address member * @param address address String to set */
block_comment
en
false
82336_9
package edu.mills.cs64.final_project; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Arrays; import java.util.Hashtable; import java.util.List; import java.util.Scanner; /** * A representation of an academic course. Course information * can be loaded from a file through the method {@link #loadCourses(String)}. * After this method has been called, courses can be retrieved * through the method {@link #getCourse(String)}. * * @author B0048993 * @version 28 April 2016 */ public class Course { private String department; private int number; private String name; private int credits; private CoreRequirement[] requirementsMet; private static Hashtable<String, Course> courses; private static final String COURSES_FILE = "courses.txt"; private static Hashtable<CoreRequirement, List<Course>> coursesMeetingRequirements; /** * Constructs a new Course with the given information. * * * @param department the department * @param number the course number * @param name the course name * @param credits the number of credits * @param requirementsMet the list of requirements met */ private Course(String department, int number, String name, int credits, CoreRequirement[] requirementsMet) { this.department = department; this.number = number; this.name = name; this.credits = credits; this.requirementsMet = requirementsMet; } /** * Loads course information from the specified file, after * which the information can be retrieved by calling * {@link #getCourse(String)}. * <p> * The file should consist of records in the following * format: * <pre> * DEPARTMENT NUMBER * NAME * CREDITS * REQUIREMENTS MET (comma-separated list) * </pre> * Here is a sample file: * <pre> * CS 64 * Computer Concepts and Intermediate Programming * 4 * QL * ARTH 18 * Introduction to Western Art * 3 * CA, CIE, IP * </pre> * All courses in the file must meet at least one requirement. * <p> * Results are undefined if the file is not in the proper format. * (In other words, there is no error checking and recovery.) * * @param filename the name of the file with course information * @throws FileNotFoundException if the file cannot be found */ public static void loadCourses(String filename) throws FileNotFoundException { courses = new Hashtable<String, Course>(); coursesMeetingRequirements = new Hashtable<CoreRequirement, List<Course>>(); List<Course> courseList; File inputFile = new File(COURSES_FILE); Scanner scanner = new Scanner(inputFile); while (scanner.hasNextLine()) { String[] splitLine1 = scanner.nextLine().split(" "); String department = splitLine1[0]; int number = Integer.parseInt(splitLine1[1]); String name = scanner.nextLine(); int credits = Integer.parseInt(scanner.nextLine()); String[] splitLine4 = scanner.nextLine().split(", "); CoreRequirement[] requirementsMet = new CoreRequirement[splitLine4.length]; for (int i = 0; i < requirementsMet.length; i++) { requirementsMet[i] = CoreRequirement.valueOf(splitLine4[i]); } Course course = new Course(department, number, name, credits, requirementsMet); courses.put(course.getShortName(), course); for (CoreRequirement cr : requirementsMet) { if (coursesMeetingRequirements.containsKey(cr)) { courseList = coursesMeetingRequirements.get(cr); courseList.add(course); } else { courseList = new ArrayList<Course>(); courseList.add(course); } coursesMeetingRequirements.put(cr, courseList); } } scanner.close(); } /** * Gets a course that was previously loaded through a call * to {@link #loadCourses(String)}. * * @param shortName the short name of the course, as would be * returned by {@link #getShortName()} * @return the course, or null if it cannot be found * @throws IllegalStateException if courses have not yet been * loaded */ public static Course getCourse(String shortName) throws IllegalStateException { try { Course course = courses.get(shortName); if (course != null) { return course; } else { return null; } } catch (IllegalStateException e) { System.err.println(e.toString()); return null; } } /** * Gets a list of courses that meets the provided * Core Requirement. * * @param the core requirement * @return list of courses that meet CoreRequirement */ public static List<Course> getCoursesMeetingRequirements(CoreRequirement cr) { if (cr != null) { return coursesMeetingRequirements.get(cr); } return null; } /** * Gets a short version of the name of this course. * This consists of the department and the number, e.g., * "CS 64". * * @return a short version of the name of this course */ public String getShortName() { return department + " " + number; } /** * Gets the department of this course. * * @return the department */ public String getDepartment() { return department; } /** * Gets the number of this course. * * @return the number */ public int getNumber() { return number; } /** * Gets the name of this course. * * @return the name */ public String getName() { return name; } /** * Gets the number of credits for this course. * * @return the number of credits */ public int getCredits() { return credits; } /** * Gets the core requirements met by this course. * * @return the requirements met by this course */ public CoreRequirement[] getRequirementsMet() { return requirementsMet; } /** * Gets the hashtable with a core requirement as the key * and a list of courses as values. * * @return the courses that meet each core requirement */ public Hashtable<CoreRequirement, List<Course>> getcoursesMeetingRequirements() { return coursesMeetingRequirements; } /** * Overrides the toString method. * * @return a string representation of the course * department, number, name and credits. */ @Override public String toString() { return department + " " + number + ": " + name + "(" + credits + ")"; } }
kcutler/Student-Record-System
Course.java
1,692
/** * Gets the number of credits for this course. * * @return the number of credits */
block_comment
en
false
82402_0
/* fileName: Theif.java * * author: Andrew Matteson * date: 10/20/12 * compiler: jGRASP 1.8.8_20 * * Heroes vs. Monsters * CSCD 211 * Java II * * -> worked alone <- * * Extra Credit Attempted: * ->>>Extra Hero: yes * ->>>Monster Skill: yes * ->>>JavaDoc: No */ import java.util.Random; public class Thief extends Hero{ Thief(){ //super requirements //(int hp, int atkSpd, int minDmg, int maxDmg, double hitChance, double blockChance) super(75, 6, 20, 40, .8, .4, "Surprise Attack"); // hp = 75; // atkSpd = 6; // hitChance = .8; // minDamage = 20; // maxDamage = 40; // blockChance = .4; } //SURPRISE ATTACK ABILITY public void specialAbility(DungeonCharacter monster){ double surpriseChance = .4; double normalAttackChance = .8; Random rand = new Random(); double result = rand.nextDouble(); if(result < surpriseChance){ System.out.println("You gained an extra attack!"); super.attackDamage(monster); super.attackDamage(monster); } else if( result < normalAttackChance){ super.attackDamage(monster); } else{ System.out.println("Surprise Attack missed!!"); } } }
amatteson89/HeroesVsMonsters
Thief.java
445
/* fileName: Theif.java * * author: Andrew Matteson * date: 10/20/12 * compiler: jGRASP 1.8.8_20 * * Heroes vs. Monsters * CSCD 211 * Java II * * -> worked alone <- * * Extra Credit Attempted: * ->>>Extra Hero: yes * ->>>Monster Skill: yes * ->>>JavaDoc: No */
block_comment
en
true
82683_1
import javax.swing.JOptionPane; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author Muhammad Talha Tahir */ public class menuHnd implements MenuListener{ @Override public void menuSelected(MenuEvent e) { String message = "This Web Browser is developed by Bitf19a003\nas an OOAD assignment."; JOptionPane.showMessageDialog(null,message, "About Us" , JOptionPane.INFORMATION_MESSAGE); } @Override public void menuDeselected(MenuEvent e) { return; } @Override public void menuCanceled(MenuEvent e) { return; } }
MuhammadTalhaTahir/Web-Browser
src/menuHnd.java
212
/** * * @author Muhammad Talha Tahir */
block_comment
en
true
82751_2
package ast; import java.util.*; import visitor.*; /** * The AST Abstract class is the Abstract Syntax Tree representation; * each node contains<ol><li> references to its kids, <li>its unique node number * used for printing/debugging, <li>its decoration used for constraining * and code generation, and <li>a label for code generation</ol> * The AST is built by the Parser */ public abstract class AST { protected ArrayList<AST> kids; protected int nodeNum; protected AST decoration; protected String label = ""; // label for generated code of tree static int NodeCount = 0; public AST() { kids = new ArrayList<AST>(); NodeCount++; nodeNum = NodeCount; } public void setDecoration(AST t) { decoration = t; } public AST getDecoration() { return decoration; } public int getNodeNum() { return nodeNum; } /** * get the AST corresponding to the kid * @param i is the number of the needed kid; it starts with kid number one * @return the AST for the indicated kid */ public AST getKid(int i) { if ( (i <= 0) || (i > kidCount())) { return null; } return kids.get(i - 1); } /** * @return the number of kids at this node */ public int kidCount() { return kids.size(); } public ArrayList<AST> getKids() { return kids; } /** * accept the visitor for this node - this method must be defined in each of * the subclasses of AST * @param v is the ASTVisitor visiting this node (currently, a printer, * constrainer and code generator) * @return the desired Object, as determined by the visitor */ public abstract Object accept(ASTVisitor v); public AST addKid(AST kid) { kids.add(kid); return this; } public void setLabel(String label) { this.label = label; } public String getLabel() { return label; } }
bestkao/Compiler
src/ast/AST.java
514
/** * get the AST corresponding to the kid * @param i is the number of the needed kid; it starts with kid number one * @return the AST for the indicated kid */
block_comment
en
false
82798_1
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package CTC; public class CTCModel { private int throughput; private int capacity; private int occupancy; private String[] trackControllers = {"A1", "A2", "A3"}; private String[] trains = {"1111", "2222", "3333"}; /*public Track getTrack(String TrackID) * { * * } */ public String [] getTrackIDs() { String s[] = new String [trackControllers.length]; for(int i = 0; i < trackControllers.length; i++) { s[i] = trackControllers[i]; } return s; } public String [] getTrainIDs() { String s[] = new String [trains.length]; for(int i = 0; i < trains.length; i++) { s[i] = trains[i]; } return s; } public int getThroughput() { return throughput; } public int getCapacity() { return capacity; } public int getOccupancy() { return occupancy; } }
zsweigart/NSE-Train-Control
CTCModel.java
294
/*public Track getTrack(String TrackID) * { * * } */
block_comment
en
true
83106_4
import java.util.Scanner; class time{ public static void main(String[] args) { Scanner checkTime = new Scanner(System.in); System.out.println("Enter Time IN Seconds : "); int secoundGet = checkTime.nextInt(); //for close the checkTime checkTime.close(); //get time in minutes int timeinMin = secoundGet / 60; //get the remaining minutes mod secoundGet by 60 int haltingSec = secoundGet % 60; //get the time in hours devide minutes by 60 int timeinHours = timeinMin / 60; //now get the remaining minutes mod minutes by 60 int haltingMin = timeinMin % 60; //now get the output System.out.println("The Entered Time : " + timeinHours + " Hours " + haltingMin +" Minutes and " + haltingSec +" Seconds."); } }
JehanKandy/Time-Convert-in-Java-
time.java
230
//now get the remaining minutes mod minutes by 60
line_comment
en
true
83427_3
import java.awt.image.*; import java.util.Random; // places rocks on the vertical beaches and along the top public class Rocks { Random rand = new Random(); int random; // main function public void rock(TileMap mappy, BufferedImage tile) { random = rand.nextInt(10); borderRock(15, mappy, tile); borderRock(95, mappy, tile); topRock(mappy, tile); } // generates rocks along the top of the island public void topRock(TileMap mappy, BufferedImage tile) { int rockSize, chance; for (int x = 9; x < mappy.getWidth() - 15; x++) { chance = rand.nextInt(5); if (chance != 0) { rockSize = rand.nextInt(10) + 6; for (int width = x; width < x + rockSize; width++) { for (int height = 11; height > rockSize; height--) { mappy.setTile(width, height, tile); } } } } } // generates rock on the vertical beaches starting at the start parameter public void borderRock(int start, TileMap mappy, BufferedImage tile) { int rockSize, placement, chance; for (int y = 15; y < mappy.getHeight() - 20; y++) { chance = rand.nextInt(18); if (chance == 0) { rockSize = rand.nextInt(4) + 3; placement = rand.nextInt(7) - 5; for (int height = y; height < y + rockSize; height++) { for (int width = start + placement; width < start + placement + rockSize; width++) { mappy.setTile(width, height, tile); } } } } } }
WolffRuoff/Animal_Crossing_Island_Generator
Rocks.java
479
// generates rock on the vertical beaches starting at the start parameter
line_comment
en
true
83481_0
import java.awt.Color; import java.awt.Graphics; import java.awt.Point; public class Enemy { static final int ST_DANCE = 0; static final int ST_WAIT = 1; static final int ST_ATTACK = 2; static final int ST_HURT = 3; static final int ST_DIVE = 4; static final int ST_DYING = 5; static final int ST_DEAD = 6; static final int ST_FROZEN = 7; static final int NUMSTATES = 8; static final int NUMENEMIES = 10; static final int WEP_ROCK = 0; static final int WEP_BEAM = 1; static final int WEP_RING = 2; static final int WEP_FIRE = 3; static final int MAXWAYPOINTS = 10; static final int MAXVELOCITY = 3; static final int WAYDIST = 2; static final int PATTERN_CIRCLE = 0; static final int PATTERN_DIVE = 1; int MaxHealth; int Health; int Damage; int Value; StatedSprite StateSpriteInfo; int DefState; int State1; int State2; int State3; int Percent1; int Percent2; int Percent3; int TableX; int TableY; int defx; int defy; int TimeFrozen; int Burning; int WeaponType; boolean Smart; int MultiFire; int CurrentPattern; Point Target; int HalfWidth; Enemy Leader; static MissileManager MMObj; static int EnemiesLeft; static Player CurrentPlayer; int update_tempx; int update_tempy; int update_temppx; int update_temppy; int update_waydx; int update_waydy; static int AllOffX; static int AllOffY; static int p_x; static int p_y; static long UpdateTempLong; public Enemy(int paramInt1, int paramInt2, int paramInt3, int paramInt4, int paramInt5, int paramInt6, int paramInt7, int paramInt8, int paramInt9, int paramInt10, int paramInt11, boolean paramBoolean, int paramInt12) { this.Health = paramInt1; this.MaxHealth = paramInt1; this.Damage = paramInt2; this.Value = paramInt3; this.DefState = paramInt4; this.State1 = paramInt5; this.State2 = paramInt6; this.State3 = paramInt7; this.Percent1 = paramInt8; this.Percent2 = paramInt9; this.Percent3 = paramInt10; this.WeaponType = paramInt11; this.Smart = paramBoolean; this.MultiFire = paramInt12; } public void Burn(int paramInt) { this.Burning = paramInt; } public void Freeze(int paramInt) { this.StateSpriteInfo.SetNewState(7); this.StateSpriteInfo.NextState = 7; this.TimeFrozen = paramInt * 10; } public int GetNumEnemies() { return 10; } public void Hit(int paramInt) { this.Health -= paramInt; if (this.Health < 1) { this.StateSpriteInfo.SetNewState(5); int i = (int)Utils.GetRandom(0L, 19L); switch (i) { case 0: SoundMan.PlayClip(0); break; case 1: SoundMan.PlayClip(1); break; } } else { this.StateSpriteInfo.SetNewState(3); } } public final void Paint(Graphics paramGraphics) { this.StateSpriteInfo.Paint(paramGraphics); if (this.StateSpriteInfo.visible) { p_x = this.StateSpriteInfo.xpos + this.HalfWidth - 10; p_y = this.StateSpriteInfo.ypos + this.StateSpriteInfo.height + 4; paramGraphics.setColor(Color.yellow); paramGraphics.drawRect(p_x, p_y, 21, 4); paramGraphics.setColor(Color.red); paramGraphics.fillRect(p_x + 1, p_y + 1, this.Health * 20 / this.MaxHealth, 3); } } static void SetPlayer(Player paramPlayer) { CurrentPlayer = paramPlayer; } public final void Update() { if (this.StateSpriteInfo.active) { this.StateSpriteInfo.Update(); if (this.TimeFrozen != 0) { this.TimeFrozen--; if (this.TimeFrozen == 0) { this.StateSpriteInfo.CurrentState = 0; this.StateSpriteInfo.NextState = 0; } else { this.StateSpriteInfo.NextState = 7; } } if (this.Burning != 0 && Utils.GetRandom(1L, 50L) <= this.Burning) { Explosion.AddExplosion(this.StateSpriteInfo.xpos + 10, this.StateSpriteInfo.ypos + 16); Explosion.AddExplosion(this.StateSpriteInfo.xpos + 16, this.StateSpriteInfo.ypos + 16); Explosion.AddExplosion(this.StateSpriteInfo.xpos + 22, this.StateSpriteInfo.ypos + 16); this.Health--; if (this.Health < 1) { this.StateSpriteInfo.SetNewState(5); this.Burning = 0; } } if (this.StateSpriteInfo.Action == 5) { this.StateSpriteInfo.CurrentState = 6; this.StateSpriteInfo.visible = false; this.StateSpriteInfo.active = false; this.StateSpriteInfo.Action = 0; EnemyManager.CreateFloater(this.StateSpriteInfo.xpos + 16, this.StateSpriteInfo.ypos + 26, this.Value); EnemiesLeft--; } else if (this.StateSpriteInfo.CurrentState == 2 && this.StateSpriteInfo.FrameCount == 0 && (this.StateSpriteInfo.CurrentFrame == 5 || (this.StateSpriteInfo.CurrentFrame == 7 && this.MultiFire >= 1) || (this.StateSpriteInfo.CurrentFrame == 6 && this.MultiFire >= 2))) { if (this.Smart) { MMObj.LaunchEnemyMissile(this.StateSpriteInfo.xpos + 16, this.StateSpriteInfo.ypos + 36, this.Damage, this.WeaponType, CurrentPlayer.StateSpriteInfo.xpos + 16, CurrentPlayer.StateSpriteInfo.ypos + 16); } else { MMObj.LaunchEnemyMissile(this.StateSpriteInfo.xpos + 16, this.StateSpriteInfo.ypos + 36, this.Damage, this.WeaponType, this.StateSpriteInfo.xpos + 16, 500); } } if (this.StateSpriteInfo.CurrentState != 5 && this.CurrentPattern == 0) { this.StateSpriteInfo.xpos = this.defx + AllOffX; this.StateSpriteInfo.ypos = this.defy + AllOffY; } } if (this.StateSpriteInfo.CurrentState == 0) { UpdateTempLong = Utils.GetRandom(0L, 10000L); if (UpdateTempLong <= this.Percent1) { this.StateSpriteInfo.NextState = this.State1; } else if (UpdateTempLong <= this.Percent2) { this.StateSpriteInfo.NextState = this.State2; } else if (UpdateTempLong <= this.Percent3) { this.StateSpriteInfo.NextState = this.State3; } } } } /* Location: C:\Users\brody\Downloads\invader.jar!\Enemy.class * Java compiler version: 1 (45.3) * JD-Core Version: 1.1.3 */
Nerdmaster/skwerl-invaders
Enemy.java
1,968
/* Location: C:\Users\brody\Downloads\invader.jar!\Enemy.class * Java compiler version: 1 (45.3) * JD-Core Version: 1.1.3 */
block_comment
en
true
83484_3
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.util.*; /** * Write a description of class Slime here. * * @author Gabriel Silva de Azevedo * @version 25/07/2017 */ public class Slime extends Actor { int frame = 1,speed = 2,animationCounter = 0,direction = 0,vida = 3; /** * Act - do whatever the Slime wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { chegarRock(); animationCounter++; } public int getVida(){ return this.vida; } public void setVida(int j){ this.vida = j; } public int getDirec(){ return this.direction; } public void setDirec(int i){ this.direction = i; } public void chegarRock(){ World w = getWorld(); List top = w.getObjectsAt(getX(),getY()-15, Rock.class); List bot = w.getObjectsAt(getX(),getY()+15, Rock.class); List left = w.getObjectsAt(getX()-15,getY(), Rock.class); List right = w.getObjectsAt(getX()+15,getY(), Rock.class); if(right.isEmpty()){ setLocation(getX()+3, getY()); direction = 1; } if(left.isEmpty()){ setLocation(getX()-3, getY()); direction = 0; } if(top.isEmpty()){ setLocation(getX(), getY()-3); direction = 2; } if(bot.isEmpty()){ setLocation(getX(), getY()+3); direction = 3; } } public void AnimateLeft(){ if(frame == 1){ setImage("SlimeL1.png"); } else if(frame ==2){ setLocation(getX(),getY()+2); setImage("SlimeL2.png"); } else if(frame ==3){ setLocation(getX(),getY()-2); setImage("SlimeL3.png"); } else if(frame ==4){ setLocation(getX(),getY()-2); setImage("SlimeL4.png"); } else if(frame ==5){ setLocation(getX(),getY()+2); setImage("SlimeL5.png"); } else if(frame ==6){ setImage("SlimeL1.png"); frame = 1; return; } frame ++; } public void moveLeft(){ setLocation(getX()-speed, getY()); /*if(animationCounter % 6==0){ AnimateLeft(); } */ } public void AnimateRight(){ if(frame == 1){ setImage("SlimeR1.png"); } else if(frame ==2){ setLocation(getX(),getY()+2); setImage("SlimeR2.png"); } else if(frame ==3){ setLocation(getX(),getY()-2); setImage("SlimeR3.png"); } else if(frame ==4){ setLocation(getX(),getY()-2); setImage("SlimeR4.png"); } else if(frame ==5){ setLocation(getX(),getY()+2); setImage("SlimeR5.png"); } else if(frame ==6){ setImage("SlimeR1.png"); frame = 1; return; } frame ++; } public void moveRight(){ setLocation(getX()+speed, getY()); /*if(animationCounter % 6==0){ AnimateRight(); } */ } public void AnimateUp(){ if(frame == 1){ setImage("SlimeU1.png"); } else if(frame ==2){ setLocation(getX(),getY()+2); setImage("SlimeU2.png"); } else if(frame ==3){ setLocation(getX(),getY()-2); setImage("SlimeU3.png"); } else if(frame ==4){ setLocation(getX(),getY()-2); setImage("SlimeU4.png"); } else if(frame ==5){ setLocation(getX(),getY()+2); setImage("SlimeU5.png"); } else if(frame ==6){ setImage("SlimeU1.png"); frame = 1; return; } frame ++; } public void moveUp(){ setLocation(getX(), getY()-speed); if(animationCounter % 6==0){ AnimateUp(); } } public void AnimateDown(){ if(frame == 1){ setImage("Slime 1.png"); } else if(frame ==2){ setLocation(getX(),getY()+2); setImage("SlimeD2.png"); } else if(frame ==3){ setLocation(getX(),getY()-2); setImage("SlimeD3.png"); } else if(frame ==4){ setLocation(getX(),getY()-2); setImage("SlimeD4.png"); } else if(frame ==5){ setLocation(getX(),getY()+2); setImage("SlimeD5.png"); } else if(frame ==6){ setImage("Slime 1.png"); frame = 1; return; } frame ++; } public void moveDown(){ setLocation(getX(), getY()+speed); if(animationCounter % 6==0){ AnimateDown(); } } }
Matoro17/GreenFootGame-GirlinTheDugeon
Slime.java
1,370
/*if(animationCounter % 6==0){ AnimateLeft(); } */
block_comment
en
true
83490_1
import greenfoot.*; /** * A dangerous rocket that gets thrown by the rabbits * * @author Daniel Bark * @version 1.0 */ public class Rocket extends Projectile { /** * Constructs a rocket * @param direction The parameter decides if the rocket is thrown to the left or the right * @param isSuperRocket decides if the Rocket is a superrocket or not * @param thrownBy the Actor who threw the rocket */ Rocket(boolean direction, boolean isSuperRocket, Actor thrownBy){ mImage = getImage(); mDirection = direction; isSuperProjectile = isSuperRocket; mThrownBy = thrownBy; if(isSuperProjectile){ mImage.scale(60, 60); mDamage = 2; } if(direction){ setRotation(180); } } @Override public void act(){ move(8); randomTurn(); removeAtCollision(); hittingTarget(); } /** * Removes a rocket if it reaches the edge of the world */ private void removeAtCollision(){ if(isAtEdge()){ getWorld().removeObject(this); } } /** * Randomizes the flight path of the rocket */ private void randomTurn(){ if(Greenfoot.getRandomNumber(5) == 0){ if(Greenfoot.getRandomNumber(2) == 0){ turn(5); } else{ turn(-5); } } } }
danba340/RabbitWars
Rocket.java
343
/** * Constructs a rocket * @param direction The parameter decides if the rocket is thrown to the left or the right * @param isSuperRocket decides if the Rocket is a superrocket or not * @param thrownBy the Actor who threw the rocket */
block_comment
en
true
84567_5
// License: GPL. Copyright 2007 by Immanuel Scholz and others //Licence: GPL // Note: The name of the main class will be the name of the application menu on OS X. // so instead of exposing "org.openstreetmap.josm.gui.MainApplication" to the // user, we subclass it with a nicer name "JOSM". // An alternative would be to set the name in the plist file---but JOSM usually // is not delivered as an OS X Application Bundle, so we have no plist file. import org.openstreetmap.josm.gui.MainApplication; public class JOSM extends MainApplication {}
Firefishy/josm
src/JOSM.java
157
// An alternative would be to set the name in the plist file---but JOSM usually
line_comment
en
false
85842_1
/** * Klasse Ball zum Erkunden von Attributen und Methoden * * @author [email protected] * * @version 4.0 (2018-08-07) * */ public class Ball extends KREIS { private float reibung; private float elastizitaet; private float masse; private String farbe; /** * Konstruktor der Klasse Ball * * @param x x-Koordinate des Mittelpunkts * @param y y-Koordinate des Mittelpunkts */ public Ball( float x , float y ) { super( 25 ); super.setzeFarbe( "blau"); super.macheAktiv(); this.masse = 1f; setzeMasse( this.masse ); this.farbe = super.nenneFarbe(); this.reibung = 0.1f; super.setzeReibung( this.reibung ); this.elastizitaet = 0.5f; super.setzeElastizitaet( this.elastizitaet ); super.setzeMittelpunkt( x , y ); } /** * Konstruktor der Klasse Ball * * @param kg Masse des Balls in kg * @param radius Radius des Balls in Pixel am Bildschirm */ public Ball ( int radius ) { this( 0 , 100 ); super.setzeRadius( radius ); super.macheAktiv(); this.elastizitaet = 0.5f; super.setzeElastizitaet( this.elastizitaet ); this.reibung = 0.1f; super.setzeReibung( this.reibung ); } /** * Legt den Ball an den entsprechenden Koordinaten ab. * * @param x x-Koordinate * @param y y-Koordinate */ public void setzeMittelpunkt( float x , float y ) { super.setzeGeschwindigkeit( 0 , 0 ); super.setzeMittelpunkt( x , y ); } /** * Setzt die Geschwindigkeit des Balls auf einen bestimmten Wert. * Liegt der Ball still, so entspricht das einem "Tritt" in diese Richtung. * * @param inXrichtung Geschwindigkeit in x-Richtung * @param inYrichtung Geschwindigkeit in y-Richtung */ public void setzeGeschwindigkeit( float inXrichtung , float inYrichtung ) { //this.geschwindigkeitX = inXrichtung; //this.geschwindigkeitY = inYrichtung; super.setzeGeschwindigkeit( inXrichtung , inYrichtung ); } /** * Nennt die aktuelle Geschwindigkeit in x-Richtung. * * @return aktuelle Geschwindigktei in x-Richtung */ public float nenneGeschwindigkteiX() { //this.geschwindigkeitX = super.nenneVx(); //this.geschwindigkeitY = super.nenneVy(); return super.nenneVx(); } /** * Nennt die aktuelle Geschwindigkeit in y-Richtung. * * @return aktuelle Geschwindigktei in y-Richtung */ public float nenneGeschwindigkteiY() { //this.geschwindigkeitX = super.nenneVx(); //this.geschwindigkeitY = super.nenneVy(); return super.nenneVy(); } /** * Setzt den Reibungs-Koeffizienten des Balls beim Rollen auf dem Boden. * * @param reibungsKoeffizient 0=keine Reibung ; 0.5=standard */ public void setzeReibung( float reibungsKoeffizient ) { this.reibung = reibungsKoeffizient; super.setzeReibung( reibungsKoeffizient ); } /** * Gibt den aktuellen Reibungs-Koeffizienten des Balls zurueck. * * @return aktueller Reibungs-Koeffizienten des Balls */ public float nenneReibung() { return this.reibung; } /** * Setzt die Elastizitaet des Balls auf eienen bestimmten Wert. * * * @param elastizitaetsKonstante 0 = steinhart ; 0.5 = standard ; 1 = reibungsfreier Gummihuepfer */ public void setzeElastizitaet( float elastizitaetsKonstante ) { this.elastizitaet = elastizitaetsKonstante; super.setzeElastizitaet( elastizitaetsKonstante ); } /** * Gibt die aktuelle Elastizitaets-Konstante des Balls zurueck. * * @return aktuelle Elastizitaets-Konstante des Balls */ public float nenneElastizitaet() { return this.elastizitaet; } /** * Setzt die Masse des Balls in kg * * @param kg neue Masse des Balls */ public void setzeMasse( float kg ) { this.masse = kg; super.setzeMasse( kg ); } /** * Nennt die aktuelle Masse des Balls * * @return aktuelle Masse des Balls */ public float nenneMasse() { return this.masse; } public void setzeFarbe( String farbe ) { this.farbe = farbe; super.setzeFarbe( farbe ); } }
engine-alpha/bluej-bouncer
Ball.java
1,470
/** * Konstruktor der Klasse Ball * * @param x x-Koordinate des Mittelpunkts * @param y y-Koordinate des Mittelpunkts */
block_comment
en
true
85961_1
/* * Copyright Dept. of Mathematics & Computer Science Univ. Paris-Descartes * * This software is governed by the CeCILL license under French law and * abiding by the rules of distribution of free software. You can use, * modify and/ or redistribute the software under the terms of the CeCILL * license as circulated by CEA, CNRS and INRIA at the following URL * "http://www.cecill.info". * * As a counterpart to the access to the source code and rights to copy, * modify and redistribute granted by the license, users are provided only * with a limited warranty and the software's author, the holder of the * economic rights, and the successive licensors have only limited * liability. * * In this respect, the user's attention is drawn to the risks associated * with loading, using, modifying and/or developing or reproducing the * software by the user in light of its specific status of free software, * that may mean that it is complicated to manipulate, and that also * therefore means that it is reserved for developers and experienced * professionals having in-depth computer knowledge. Users are therefore * encouraged to load and test the software's suitability as regards their * requirements in conditions enabling the security of their systems and/or * data to be ensured and, more generally, to use and operate it in the * same conditions as regards security. * * The fact that you are presently reading this means that you have had * knowledge of the CeCILL license and that you accept its terms. */ package pddl4j.exp; /** * This interface is implements by all expression that can be used in the PDDL * language in the initial state description. * * @author Damien Pellier * @version 1.0 */ public interface InitEl extends Exp { }
gerryai/PDDL4J
src/pddl4j/exp/InitEl.java
454
/** * This interface is implements by all expression that can be used in the PDDL * language in the initial state description. * * @author Damien Pellier * @version 1.0 */
block_comment
en
false
86471_2
package Vdb; /* * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. */ /* * Author: Henk Vandenbergh. */ import java.util.*; /** * This class stores all Work() instances and with that can keep track of which * SD is used where. * * We could maintain individual lists, but it seems easier to just always * recreate whatever we need from one central Work list when needed. * The information is not asked for often enough to warrant worrying about * performance. * * During report creation AllWork has information about ALL runs, during a real * run however it knows only about what is CURRENTLY running by calling * clearWork() at appropriate times. */ public class AllWork { private final static String c = "Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved."; private static Vector <Work> work_list = new Vector(8, 0); public static void addWork(Work work) { common.where(); work_list.add(work); } public static void clearWork() { common.where(); work_list.removeAllElements(); } /** * Return SDs used anywhere */ public static String[] obsolete_getRealUsedSdNames() { HashMap map = new HashMap(16); for (int i = 0; i < work_list.size(); i++) { Work work = (Work) work_list.elementAt(i); for (int j = 0; j < work.wgs_for_slave.size(); j++) { WG_entry wg = (WG_entry) work.wgs_for_slave.get(j); String[] names = wg.getRealSdNames(); for (int k = 0; k < names.length; k++) map.put(names[k], null); } } return (String[]) map.keySet().toArray(new String[0]); } /** * Return SDs used in a host */ public static String[] obsolete_getRealHostSdList(Host host) { HashMap <String, Object> map = new HashMap(16); for (int i = 0; i < work_list.size(); i++) { Work work = (Work) work_list.elementAt(i); if (Host.findHost(work.host_label) != host) continue; for (int j = 0; j < work.wgs_for_slave.size(); j++) { WG_entry wg = (WG_entry) work.wgs_for_slave.get(j); String[] names = wg.getRealSdNames(); for (int k = 0; k < names.length; k++) map.put(names[k], null); } } return (String[]) map.keySet().toArray(new String[0]); } /** * Return SDs used in a slave */ public static String[] obsolete_getSlaveSdList(Slave slave) { HashMap map = new HashMap(16); for (int i = 0; i < work_list.size(); i++) { Work work = (Work) work_list.elementAt(i); if (work.slave_label.equals(slave.getLabel())) continue; for (int j = 0; j < work.wgs_for_slave.size(); j++) { WG_entry wg = (WG_entry) work.wgs_for_slave.get(j); map.put(wg.sd_used.sd_name, null); } } return (String[]) map.keySet().toArray(new String[0]); } /** * Return SDs used for this RD_entry */ public static String[] obsolete_getRdSdList(RD_entry rd) { HashMap map = new HashMap(16); for (Work work : work_list) { if (work.rd != rd) continue; for (WG_entry wg : work.wgs_for_slave) { for (String name : wg.getRealSdNames()) map.put(name, null); } } return (String[]) map.keySet().toArray(new String[0]); } /** * Return SDs used in a host for this RD_entry */ public static String[] obsolete_getHostRdSdList(Host host, RD_entry rd) { HashMap map = new HashMap(16); for (int i = 0; i < work_list.size(); i++) { Work work = (Work) work_list.elementAt(i); if (work.rd != rd) continue; if (Host.findHost(work.slave_label) != host) continue; for (int j = 0; j < work.wgs_for_slave.size(); j++) { WG_entry wg = (WG_entry) work.wgs_for_slave.get(j); map.put(wg.sd_used.sd_name, null); } } return (String[]) map.keySet().toArray(new String[0]); } /** * Return SDs used in a slave for this RD_entry */ public static String[] obsolete_getSlaveRdSdList(Slave slave, RD_entry rd) { HashMap map = new HashMap(16); for (int i = 0; i < work_list.size(); i++) { Work work = (Work) work_list.elementAt(i); if (work.rd != rd) continue; if (work.slave_label.equals(slave.getLabel())) continue; for (int j = 0; j < work.wgs_for_slave.size(); j++) { WG_entry wg = (WG_entry) work.wgs_for_slave.get(j); map.put(wg.sd_used.sd_name, null); } } return (String[]) map.keySet().toArray(new String[0]); } }
itfanr/vdbench
Vdb/AllWork.java
1,431
/** * This class stores all Work() instances and with that can keep track of which * SD is used where. * * We could maintain individual lists, but it seems easier to just always * recreate whatever we need from one central Work list when needed. * The information is not asked for often enough to warrant worrying about * performance. * * During report creation AllWork has information about ALL runs, during a real * run however it knows only about what is CURRENTLY running by calling * clearWork() at appropriate times. */
block_comment
en
false
86790_26
// WikiHelp.java // ----------------------- // part of the AnomicHTTPD caching proxy // (C) by Michael Peter Christen; [email protected] // first published on http://www.anomic.de // Frankfurt, Germany, 2004 // // $LastChangedDate$ // $LastChangedRevision$ // $LastChangedBy$ // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // You must compile this file with // javac -classpath .:../classes WikiHelp.java // if the shell's current path is HTROOT import net.yacy.cora.protocol.RequestHeader; import net.yacy.server.serverObjects; import net.yacy.server.serverSwitch; public class WikiHelp { public static serverObjects respond(@SuppressWarnings("unused") final RequestHeader header, @SuppressWarnings("unused") final serverObjects post, @SuppressWarnings("unused") final serverSwitch env) { //final plasmaSwitchboard sb = (plasmaSwitchboard) env; final serverObjects prop = new serverObjects(); return prop; } }
jadonk/yacy_search_server
htroot/WikiHelp.java
449
// javac -classpath .:../classes WikiHelp.java
line_comment
en
true
86932_0
/** * Interface that presents the two methods that each class animal has to do */ public interface Animal { void eat(); void watch(); }
ilan15/OOP-Observer-Design-Patern
Animal.java
34
/** * Interface that presents the two methods that each class animal has to do */
block_comment
en
false
87020_17
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.time.Duration; import java.time.Instant; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; /* Matt Parker Can you find: five five-letter words with twenty-five unique letters? FJORD GUCKS NYMPH VIBEX WALTZ Q Matt: 32 days Benjamin: 15 minutes Fred: 3 seconds Constraints: - No duplicate letters (valid words have 5 unique characters) - Order of letters irrelevant (ignore anagrams during search) - i.e. Word is Set of Characters Representation: - 32-bit number - 26 bits for the letters A-Z - 6 bits unused 25 0 ABCDEFGHIJKLMNOPQRSTUVWXYZ 1 1 1 1 1 fjord ---D-F---J----O--R-------- fjord --C---G---K-------S-U----- gucks -------------------------- fjord AND gucks (INTERSECTION) --CD-FG--JK---O--RS-U----- fjord OR gucks (UNION) */ class Wordle { private static List<String> rawWords; public static void main(String[] args) throws IOException { Stopwatch stopwatch = new Stopwatch(); rawWords = new ArrayList<>(); // Uncomment the following 1 line to find 538 solutions: // rawWords.addAll(Files.readAllLines(Path.of("words_alpha.txt"))); // Uncomment the following 2 lines to find 10 solutions: rawWords.addAll(Files.readAllLines(Path.of("wordle-nyt-answers-alphabetical.txt"))); rawWords.addAll(Files.readAllLines(Path.of("wordle-nyt-allowed-guesses.txt"))); rawWords.removeIf(word -> word.length() != 5); System.out.println(rawWords.size() + " raw words"); int[] cookedWords = rawWords.stream() // A---E------L---P---------- apple // --C-----I--L-----------XY- cylix // --C-----I--L-----------XY- xylic .mapToInt(Wordle::encodeWord) // remove words with duplicate characters .filter(word -> Integer.bitCount(word) == 5) .sorted() // remove anagrams .distinct() .toArray(); System.out.println(cookedWords.length + " cooked words\n"); int[] firstStep = new int[cookedWords.length]; // for (int i = 0; i < cookedWords.length; ++i) { IntStream.range(0, cookedWords.length).parallel().forEach((int i) -> { int A = cookedWords[i]; int j; for (j = i + 1; j < cookedWords.length; ++j) { int B = cookedWords[j]; if ((A & B) == 0) break; } firstStep[i] = j - i; }); // for (int i = 0; i < cookedWords.length; ++i) { IntStream.range(0, cookedWords.length).parallel().forEach((int i) -> { int A = cookedWords[i]; for (int j = i + firstStep[i]; j < cookedWords.length; ++j) { int B = cookedWords[j]; if ((A & B) != 0) continue; int AB = A | B; for (int k = j + firstStep[j]; k < cookedWords.length; ++k) { int C = cookedWords[k]; if ((AB & C) != 0) continue; int ABC = AB | C; for (int l = k + firstStep[k]; l < cookedWords.length; ++l) { int D = cookedWords[l]; if ((ABC & D) != 0) continue; int ABCD = ABC | D; for (int m = l + firstStep[l]; m < cookedWords.length; ++m) { int E = cookedWords[m]; if ((ABCD & E) != 0) continue; System.out.printf("%s\n%s\n\n", stopwatch.elapsedTime(), decodeWords(A, B, C, D, E)); } } } } }); System.out.println(stopwatch.elapsedTime()); } private static String decodeWord(int word) { // --C-----I--L-----------XY- cylix/xylic return rawWords.stream() .filter(raw -> encodeWord(raw) == word) .collect(Collectors.joining("/", visualizeWord(word) + " ", "")); } private static String decodeWords(int... words) { // ----E-----K-M--P---T------ kempt // ---D---H------O------V---Z vozhd // --C-----I--L-----------XY- cylix/xylic // -B----G------N---R--U----- brung // A----F----------Q-S---W--- waqfs return Arrays.stream(words) .mapToObj(Wordle::decodeWord) .collect(Collectors.joining("\n")); } private static int encodeWord(String raw) { // 1 1 1 1 1 fjord int bitset = 0; for (int i = 0; i < raw.length(); ++i) { bitset |= 1 << 26 >> raw.charAt(i); } return bitset; } private static String visualizeWord(int word) { // 1 1 1 1 1 // ---D-F---J----O--R-------- char[] a = new char[26]; word <<= 6; for (int i = 0; i < a.length; ++i, word <<= 1) { a[i] = (word < 0) ? (char) ('A' + i) : '-'; } return new String(a); } } class Stopwatch { private final Instant start = Instant.now(); public String elapsedTime() { Instant now = Instant.now(); Duration duration = Duration.between(start, now).truncatedTo(ChronoUnit.MILLIS); String formatted = DateTimeFormatter.ISO_LOCAL_TIME.format(duration.addTo(LocalTime.of(0, 0))); return "[" + formatted + "] "; } }
fredoverflow/wordle
Wordle2.java
1,629
// 1 1 1 1 1 fjord
line_comment
en
true
87159_3
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import javax.swing.JOptionPane; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author SAMYAK & ATISHAY */ public class PNR extends javax.swing.JFrame { /** * Creates new form PNR */ public PNR(String un) { initComponents(); jLabel2.setText(""+un); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { PNR = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); TA1 = new javax.swing.JTextArea(); jButton1 = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); getContentPane().add(PNR, new org.netbeans.lib.awtextra.AbsoluteConstraints(280, 40, 870, 67)); jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 204, 204)); jLabel1.setText("ENTER PNR NO."); getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 40, 220, 60)); TA1.setColumns(20); TA1.setFont(new java.awt.Font("Bell MT", 1, 30)); // NOI18N TA1.setRows(5); jScrollPane1.setViewportView(TA1); getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 250, 1200, 420)); jButton1.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N jButton1.setText("SHOW STATUS"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 120, 580, 50)); jLabel2.setVisible(false); getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 120, 190, 30)); jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N jLabel3.setForeground(new java.awt.Color(255, 204, 204)); jLabel3.setText("<<back to home"); jLabel3.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel3MouseClicked(evt); } }); getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 130, 260, 50)); jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/train_railway_snow_forest_119261_1440x900.jpg"))); // NOI18N jLabel4.setText("jLabel4"); getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1280, 690)); pack(); }// </editor-fold>//GEN-END:initComponents int b; private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed b=Integer.parseInt(PNR.getText()); try { Class.forName("java.sql.Driver"); Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/irctc?zeroDateTimeBehavior=convertToNull","root","123456"); Statement stmt=con.createStatement(); String sql="select * from BOOK_TICKET where PNR="+b+" && username='"+ jLabel2.getText()+"'"; System.out.println(sql); ResultSet rs= stmt.executeQuery(sql); while(rs.next()) { int pnr = rs.getInt("PNR"); String src=rs.getString("SRC"); String dst=rs.getString("DST"); String doj=rs.getString("DOJ"); int np = rs.getInt("NOP"); String train =rs.getString("TRAIN"); String ts =rs.getString("ticket_status"); TA1.append(" YOUR TICKET INFO " + "\n" +"USER ID: "+jLabel2.getText()+ "\n" +"PNR NO: "+ pnr + "\n" +"NUMBER OF PASSENGERS: " +np+"\n"+ "SOURCE STATION: "+src+"\n"+ "DESTINATION STATION: "+dst+"\n"+ "TRAIN NAME: " +train+"\n"+"TICKET STATUS: " + ts+ "\n"+"DATE OF JOURNEY: "+doj); } } catch(Exception ex) { JOptionPane.showMessageDialog(null,ex.getMessage()); } }//GEN-LAST:event_jButton1ActionPerformed private void jLabel3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel3MouseClicked HOME L=new HOME(jLabel2.getText()); L.setVisible(true);this.dispose(); }//GEN-LAST:event_jLabel3MouseClicked /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(PNR.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(PNR.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(PNR.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(PNR.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new PNR(null).setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField PNR; private javax.swing.JTextArea TA1; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JScrollPane jScrollPane1; // End of variables declaration//GEN-END:variables }
Sam9685/IRCTC-
src/PNR.java
2,028
/** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */
block_comment
en
false
87198_0
/** * * @author João Pedro */ public class Menu extends javax.swing.JFrame { private Gerenciador gerenciador; public Menu() { this.setResizable(false); this.gerenciador = new Gerenciador(); initComponents(); this.pack(); this.setLocationRelativeTo(null); } private void initComponents() { BtmTreinador = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); btmAddPoke = new javax.swing.JButton(); btmPokedex = new javax.swing.JButton(); btmCriaBatalha = new javax.swing.JButton(); btmStats = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); BtmTreinador.setText("ADICIONAR TREINADOR"); BtmTreinador.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtmTreinadorActionPerformed(evt); } }); jLabel1.setFont(new java.awt.Font("Segoe UI", 0, 20)); // NOI18N jLabel1.setText("POOKEMON"); btmAddPoke.setText("CRIAR POKEMON"); btmAddPoke.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btmAddPokeActionPerformed(evt); } }); btmPokedex.setText("POKEDEX"); btmPokedex.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btmPokedexActionPerformed(evt); } }); btmCriaBatalha.setText("BATALHAR!"); btmCriaBatalha.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btmCriaBatalhaActionPerformed(evt); } }); btmStats.setText("ESTATÍSTICAS"); btmStats.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btmStatsActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(110, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(150, 150, 150)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout .createSequentialGroup() .addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(btmAddPoke, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(BtmTreinador, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btmPokedex, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btmCriaBatalha, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btmStats, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(108, 108, 108))))); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(14, 14, 14) .addComponent(jLabel1) .addGap(19, 19, 19) .addComponent(BtmTreinador, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btmAddPoke, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btmPokedex, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btmCriaBatalha, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btmStats, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(103, Short.MAX_VALUE))); pack(); } private void BtmTreinadorActionPerformed(java.awt.event.ActionEvent evt) { gerenciador.abrirTela(this, new TelaTreinador(this)); } private void btmCriaBatalhaActionPerformed(java.awt.event.ActionEvent evt) { gerenciador.abrirTela(this, new TelaBatalha(this)); } private void btmAddPokeActionPerformed(java.awt.event.ActionEvent evt) { gerenciador.abrirTela(this, new TelaPokemon(this)); } private void btmPokedexActionPerformed(java.awt.event.ActionEvent evt) { gerenciador.abrirTela(this, new TelaPokedex(this)); } private void btmStatsActionPerformed(java.awt.event.ActionEvent evt) { gerenciador.abrirTela(this, new TelaEstatisticas(this)); } public Gerenciador getGerenciador() { return gerenciador; } public static void main(String args[]) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Menu().setVisible(true); } }); } private javax.swing.JButton BtmTreinador; private javax.swing.JButton btmAddPoke; private javax.swing.JButton btmCriaBatalha; private javax.swing.JButton btmPokedex; private javax.swing.JButton btmStats; private javax.swing.JLabel jLabel1; }
jplima0707/Jogo-Pokemon-Trabalho-final-poo
Menu.java
1,911
/** * * @author João Pedro */
block_comment
en
true
87421_0
import javax.swing.JFrame; /** * This class contains the main() method that creates a model, a view, and a controller, passing the * model and the view to the controller. * @author Ted Mader * @version Alpha * @date 5/02/14 **/ public class Risk { public static void main(String[] args) { RiskModel model = new RiskModel(); RiskView view = new RiskView(); RiskController controller = new RiskController(model, view); } }
tlmader/risk
Risk.java
131
/** * This class contains the main() method that creates a model, a view, and a controller, passing the * model and the view to the controller. * @author Ted Mader * @version Alpha * @date 5/02/14 **/
block_comment
en
true
87460_13
import java.util.*; class Risk { public static void main(String[] args) { ArrayList<Integer> troopNumbersMaster = new ArrayList<Integer>(); System.out.println("Simulating a Risk turn with the following setup:"); System.out.println(); System.out.println("The first value is the attacking country, the rest of the"); System.out.println("values are the chain of defending countries"); /** * Edit the numbers below here for attacking a defending troop setups and the * number of trials to run */ // The attacking Troop troopNumbersMaster.add(45); // The defending Troops troopNumbersMaster.add(1); troopNumbersMaster.add(1); troopNumbersMaster.add(7); troopNumbersMaster.add(1); troopNumbersMaster.add(7); troopNumbersMaster.add(7); troopNumbersMaster.add(7); troopNumbersMaster.add(1); troopNumbersMaster.add(1); troopNumbersMaster.add(1); troopNumbersMaster.add(1); // The number of trials int totalReps = 100000; /** * Do not edit below here */ System.out.println(troopNumbersMaster); System.out.println(); Integer[] copyDeep = new Integer[troopNumbersMaster.size()]; copyDeep = troopNumbersMaster.toArray(copyDeep); int winCount = 0; for (int i = 0; i < totalReps; i++) { ArrayList<Integer> troopNumbers = new ArrayList<Integer>(Arrays.asList(copyDeep)); // the starting index for the attackers int attackingIndex = 0; // Have the attacking index attack the next square until depleted while (attackingIndex < troopNumbers.size() - 1 && troopNumbers.get(attackingIndex) > 1) { // System.out.println("Attacking Index " + attackingIndex); // System.out.println(troopNumbers); int attacking = troopNumbers.get(attackingIndex); int defending = troopNumbers.get(attackingIndex + 1); int[] res = simulateBattle(new int[] { attacking, defending }); if (res[0] > 1) { // the attacker won, needs to leave one behind // System.out.println("attacker Won"); troopNumbers.set(attackingIndex, 1); troopNumbers.set(attackingIndex + 1, res[0] - 1); attackingIndex++; } else { // the defender won // System.out.println("defender Won"); troopNumbers.set(attackingIndex, 1); troopNumbers.set(attackingIndex + 1, res[1]); } } // simulation is finisished, attacker won if they made it to the last index if (attackingIndex == troopNumbers.size() - 1) { winCount++; } } double percentWon = (double) winCount / (double) totalReps; System.out.println("Result: "); System.out.printf("Win percent: %.2f %n", percentWon * 100); } public static int[] simulateBattle(int[] input) { int attacking = input[0]; int defending = input[1]; // System.out.println("Battling " + attacking + " vs " + defending); while (attacking > 1 && defending > 0) { // System.out.println("Attacking: " + attacking); // System.out.println("Defending: " + defending); int[] attackingRolls = new int[Math.min(attacking - 1, 3)]; int[] defendingRolls = new int[Math.min(defending, 2)]; for (int i = 0; i < attackingRolls.length; i++) { attackingRolls[i] = (int) (Math.random() * 6) + 1; } for (int i = 0; i < defendingRolls.length; i++) { defendingRolls[i] = (int) (Math.random() * 6) + 1; } Arrays.sort(attackingRolls); Arrays.sort(defendingRolls); attackingRolls = reverseArray(attackingRolls); defendingRolls = reverseArray(defendingRolls); // System.out.println("attacking Rolls:"); // System.out.println(Arrays.toString(attackingRolls)); // System.out.println("defending Rolls:"); // System.out.println(Arrays.toString(defendingRolls)); for (int i = 0; i < Math.min(attackingRolls.length, defendingRolls.length); i++) { if (attackingRolls[i] > defendingRolls[i]) { defending--; // System.out.println("minus one defending"); } else { attacking--; // System.out.println("minus one attacking"); } } } int[] result = new int[] { attacking, defending }; return result; } public static int[] reverseArray(int[] validData) { for (int i = 0; i < validData.length / 2; i++) { int temp = validData[i]; validData[i] = validData[validData.length - i - 1]; validData[validData.length - i - 1] = temp; } return validData; } }
tshibley/Risk-Model
Risk.java
1,330
// simulation is finisished, attacker won if they made it to the last index
line_comment
en
false
87722_0
/* Joseph Calise ID#: 2380565 [email protected] CPSC-231 Section 03 MP3A_Cards */ import java.util.LinkedList; public class Dealer { Deck dealers_deck; public Dealer() { this.dealers_deck = new Deck(); } public int size() { return this.dealers_deck.size(); } public LinkedList<Card> deals(int n) { LinkedList<Card> deltCards = new LinkedList<Card>(); int i; for (i = 0; i < n; i++) { if (this.dealers_deck.size() != 0) { deltCards.add(this.dealers_deck.deal()); } else { return deltCards; } } return deltCards; } public void resetDeck() { this.dealers_deck = new Deck(); } public String toString() { int i; String cardsInDeck = ""; for (i = 0; i < this.dealers_deck.size(); i++) { cardsInDeck += this.dealers_deck.get(i) + "\n"; } return cardsInDeck; } }
josephcalise/blackjack
Dealer.java
294
/* Joseph Calise ID#: 2380565 [email protected] CPSC-231 Section 03 MP3A_Cards */
block_comment
en
true
87775_4
import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.security.Key; import java.util.Base64; import java.util.Scanner; /** * This is the backdoor client * Use ip = 127.0.0.1 and port = 9999 by default * @author salah3x */ public class Client { public static void main(String[] args) throws Exception { //Server ip String host = "127.0.0.1"; //Port to listen to int port = 9999; if (args.length == 2) { host = args[0]; port = Integer.valueOf(args[1]); } //The signal to let the client know that the request is finished //there will be no data to wait for(needed by the client to stop reading from output stream) String endSignal = "%**%"; //The encryption key used to encrypt an decrypt communication //Symmetric encryption is used String encryptionKey = "sixteen byte key"; //Encryption algorithm String algorithm = "AES"; //A helper class used to encrypt and decrypt Strings CryptoHelper cryptoHelper = new CryptoHelper(encryptionKey, algorithm); //Starting the server Socket socket = new Socket(host, port); //Used to red user input Scanner scanner = new Scanner(System.in); //Used to write data to socket's output stream PrintWriter printWriter = new PrintWriter(socket.getOutputStream()); //Used to read data from socket's input stream BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); //Check if we are/still connected to server while (!socket.isClosed()) { try { //Getting user input System.err.print("[remote shell] $ "); String cmd = scanner.nextLine(); //Encrypting and sending command printWriter.println(cryptoHelper.encrypt(cmd)); printWriter.flush(); if (cmd.equals("exit")) break; //Reading, decrypting and printing output to console String line; while ((line = cryptoHelper.decrypt(br.readLine())) != null) { //Until there is no data to read if (line.endsWith(endSignal)) break; System.out.println(line); } } catch (Exception e) { e.printStackTrace(); br.close(); printWriter.close(); socket.close(); } } } /** * This helper class deals with Cipher class and byte arrays in order * to provide an abstraction to use encryption on strings */ static class CryptoHelper { private Cipher cipher; private Key key; CryptoHelper(String key, String algo) throws Exception { this.key = new SecretKeySpec(key.getBytes(), algo); this.cipher = Cipher.getInstance(algo); } String encrypt(String plaintext) throws Exception { if (plaintext == null) return null; cipher.init(Cipher.ENCRYPT_MODE, key); byte[] encrypted = cipher.doFinal(plaintext.getBytes()); return Base64.getEncoder().encodeToString(encrypted); } String decrypt(String encrypted) throws Exception { if (encrypted == null) return null; cipher.init(Cipher.DECRYPT_MODE, key); byte[] decorded = Base64.getDecoder().decode(encrypted); byte[] decrypted = cipher.doFinal(decorded); return new String(decrypted); } } }
salah3x/backdoor
src/Client.java
895
//there will be no data to wait for(needed by the client to stop reading from output stream)
line_comment
en
false
87874_0
import java.util.ArrayList; import java.util.List; /** * This class contains utility methods for performing various tasks. * @author Matteo Loporchio */ public final class Utility { /** * This function chops a list into sublists of a given length. * @param l the list to be divided * @param k the number of elements in each sublist * @return a list containing all the sublists */ public static <T> List<List<T>> split(List<T> l, int k) { List<List<T>> parts = new ArrayList<List<T>>(); for (int i = 0; i < l.size(); i += k) { parts.add(l.subList(i, Math.min(l.size(), i + k))); } return parts; } }
mloporchio/BTXA
Utility.java
200
/** * This class contains utility methods for performing various tasks. * @author Matteo Loporchio */
block_comment
en
false
87902_0
package uk.ac.bristol.star.cdf.test; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import uk.ac.bristol.star.cdf.record.BankBuf; import uk.ac.bristol.star.cdf.record.Buf; import uk.ac.bristol.star.cdf.record.Pointer; import uk.ac.bristol.star.cdf.record.SimpleNioBuf; public class BufTest { private static boolean assertionsOn_; private final int blk_ = 54; private final int nn_ = 64; // Puts the various Buf implementations through their paces. public void testBufs() throws IOException { byte[] data = new byte[ 8 * 100 ]; ByteArrayOutputStream bout = new ByteArrayOutputStream(); DataOutputStream dout = new DataOutputStream( bout ); for ( int i = 0; i < nn_; i++ ) { dout.writeByte( -i ); dout.writeByte( i ); dout.writeShort( -i ); dout.writeShort( i ); dout.writeInt( -i ); dout.writeInt( i ); dout.writeLong( -i ); dout.writeLong( i ); dout.writeFloat( -i ); dout.writeFloat( i ); dout.writeDouble( -i ); dout.writeDouble( i ); } dout.flush(); dout.close(); byte[] bytes = bout.toByteArray(); int nbyte = bytes.length; assert nbyte == blk_ * nn_; boolean isBit64 = false; boolean isBigEndian = true; ByteBuffer buf1 = ByteBuffer.wrap( bytes ); checkBuf( new SimpleNioBuf( buf1, isBit64, isBigEndian ) ); checkBuf( BankBuf.createSingleBankBuf( buf1, isBit64, isBigEndian ) ); checkBuf( BankBuf.createMultiBankBuf( new ByteBuffer[] { buf1 }, isBit64, isBigEndian ) ); int[] banksizes = { 23, blk_ - 1, blk_ + 1, 49, blk_ * 4, blk_ * 2 + 2 }; List<ByteBuffer> bblist = new ArrayList<ByteBuffer>(); int ioff = 0; int ibuf = 0; int nleft = nbyte; while ( nleft > 0 ) { int leng = Math.min( banksizes[ ibuf % banksizes.length ], nleft ); byte[] bb = new byte[ leng ]; System.arraycopy( bytes, ioff, bb, 0, leng ); bblist.add( ByteBuffer.wrap( bb ) ); ibuf++; ioff += leng; nleft -= leng; } ByteBuffer[] bbufs = bblist.toArray( new ByteBuffer[ 0 ] ); assert bbufs.length > 6; checkBuf( BankBuf .createMultiBankBuf( bbufs, isBit64, isBigEndian ) ); File tmpFile = File.createTempFile( "data", ".bin" ); tmpFile.deleteOnExit(); FileOutputStream fout = new FileOutputStream( tmpFile ); fout.write( bytes ); fout.close(); FileChannel inchan = new FileInputStream( tmpFile ).getChannel(); int[] banksizes2 = new int[ banksizes.length + 2 ]; System.arraycopy( banksizes, 0, banksizes2, 0, banksizes.length ); banksizes2[ banksizes.length + 0 ] = nbyte; banksizes2[ banksizes.length + 1 ] = nbyte * 2; for ( int banksize : banksizes2 ) { checkBuf( BankBuf.createMultiBankBuf( inchan, nbyte, banksize, isBit64, isBigEndian ) ); } inchan.close(); FileChannel copychan = new FileInputStream( tmpFile ).getChannel(); assert copychan.size() == nbyte; ByteBuffer copybuf = ByteBuffer.allocate( nbyte ); copychan.read( copybuf ); copychan.close(); assert copybuf.position() == nbyte; checkBuf( new SimpleNioBuf( copybuf, isBit64, isBigEndian ) ); tmpFile.delete(); } private void checkBuf( Buf buf ) throws IOException { assert buf.getLength() == nn_ * blk_; byte[] abytes = new byte[ 2 ]; short[] ashorts = new short[ 2 ]; int[] aints = new int[ 4 ]; long[] alongs = new long[ 2 ]; float[] afloats = new float[ 21 ]; double[] adoubles = new double[ 2 ]; for ( int i = 0; i < nn_; i++ ) { int ioff = i * blk_; buf.readDataBytes( ioff + 0, 2, abytes ); buf.readDataShorts( ioff + 2, 2, ashorts ); buf.readDataInts( ioff + 6, 2, aints ); buf.readDataLongs( ioff + 14, 2, alongs ); buf.readDataFloats( ioff + 30, 2, afloats ); buf.readDataDoubles( ioff + 38, 2, adoubles ); assert abytes[ 0 ] == -i; assert abytes[ 1 ] == i; assert ashorts[ 0 ] == -i; assert ashorts[ 1 ] == i; assert aints[ 0 ] == -i; assert aints[ 1 ] == i; assert alongs[ 0 ] == -i; assert alongs[ 1 ] == i; assert afloats[ 0 ] == -i; assert afloats[ 1 ] == i; assert adoubles[ 0 ] == -i; assert adoubles[ 1 ] == i; } Pointer p = new Pointer( 0 ); assert buf.readUnsignedByte( p ) == 0; assert buf.readUnsignedByte( p ) == 0; p.set( blk_ ); assert buf.readUnsignedByte( p ) == 255; assert buf.readUnsignedByte( p ) == 1; } private static boolean checkAssertions() { assertionsOn_ = true; return true; } private static void runTests() throws IOException { assert checkAssertions(); if ( ! assertionsOn_ ) { throw new RuntimeException( "Assertions disabled - bit pointless" ); } BufTest test = new BufTest(); test.testBufs(); } public static void main( String[] args ) throws IOException { runTests(); } }
mbtaylor/jcdf
BufTest.java
1,648
// Puts the various Buf implementations through their paces.
line_comment
en
true
87975_0
class Solution { public String[] findWords(String[] words) { String[] rows = {"qwertyuiop", "asdfghjkl", "zxcvbnm"}; List<String> result = new ArrayList<>(); for (String word : words) { String lowercaseWord = word.toLowerCase(); if (isWordInRow(lowercaseWord, rows)) { result.add(word); } } return result.toArray(new String[0]); } private boolean isWordInRow(String word, String[] rows) { for (String row : rows) { Set<Character> rowSet = new HashSet<>(); for (char c : row.toCharArray()) { rowSet.add(c); } boolean isInRow = true; for (char c : word.toCharArray()) { if (!rowSet.contains(c)) { isInRow = false; break; } } if (isInRow) { return true; } } return false; } } /* 题目描述:给你一个字符串数组 words ,只返回可以使用在 美式键盘 同一行的字母打印出来的单词。键盘如下图所示。美式键盘 中: 第一行由字符“qwertyuiop”组成。 第二行由字符“asdfghjkl”组成。 第三行由字符“zxcvbnm”组成。 思路:遍历字符串,先将三行的单词添加进hashset里面,在遍历字符串,判断是否包含 */
aaaaaaliang/LeetCode1
L23.java
354
/* 题目描述:给你一个字符串数组 words ,只返回可以使用在 美式键盘 同一行的字母打印出来的单词。键盘如下图所示。美式键盘 中: 第一行由字符“qwertyuiop”组成。 第二行由字符“asdfghjkl”组成。 第三行由字符“zxcvbnm”组成。 思路:遍历字符串,先将三行的单词添加进hashset里面,在遍历字符串,判断是否包含 */
block_comment
en
true
88159_2
/** * Nick F * Sat Jul 26 19:49:17 UTC 2014 * CTCI 1.1 */ import java.util.*; class One { public static void main(String[] args) { for( String w : args ) { if (isUniqueCharsNoMap(w) ) { System.out.println(w + " | All Unique"); } else { System.out.println(w + " | Not All Unique"); } } System.out.println("done"); } /** Determine if a string has only unique characters */ public static boolean isUniqueChars(String str) { char[] letters = str.toCharArray(); HashSet<Character> set = new HashSet<>(); for (char c : letters) { if (set.contains(c)) { return false; } set.add(c); } return true; } /** Determine if a string has only unique chars, do not use extra data structure */ public static boolean isUniqueCharsNoMap(String str) { char[] letters = str.toCharArray(); char test; for (int i=0; i<letters.length; i++) { test = letters[i]; for (int j=i+1; j<letters.length; j++) { if (test == letters[j]) { return false; } } } return true; } }
nickfun/stuff
i/One.java
329
/** Determine if a string has only unique chars, do not use extra data structure */
block_comment
en
true
88190_7
/**Jul 18, 2019 * @author Joseph Kirkish */ package chapter9; import java.math.BigDecimal; /** * Class Airline extends class Object. The Airline class sets out to describe * the parameters that identify an airline. The parameters in this application * are conmpanyName, Number of Employees, number of planes, FAA registry ID and * revenue. * * @author jkirkish * */ public class Airline extends Object { private String companyName; private int NumberOfPlanes; private String FaaRegistryID; private int NumberOfEmployees; private BigDecimal revenue = new BigDecimal(0.00); // five argument constructor public Airline(String name, int plane, String Id, int staff, BigDecimal money) { companyName = name; NumberOfPlanes = plane; FaaRegistryID = Id; setNumberOfEmployees(staff); setRevenue(money); } /** * @return the companyName */ public String getCompanyName() { return companyName; } /** * @param companyName * the companyName to set */ public void setCompanyName(String companyName) { this.companyName = companyName; } /** * @return the numberOfPlanes */ public int getNumberOfPlanes() { return NumberOfPlanes; } /** * @param numberOfPlanes * the numberOfPlanes to set */ public void setNumberOfPlanes(int numberOfPlanes) { if (numberOfPlanes >= 0) NumberOfPlanes = numberOfPlanes; else throw new IllegalArgumentException("Planes must be more than 0"); } /** * @return the faaRegistryID */ public String getFaaRegistryID() { return FaaRegistryID; } /** * @param faaRegistryID * the faaRegistryID to set */ public void setFaaRegistryID(String faaRegistryID) { FaaRegistryID = faaRegistryID; } /** * @return the numberOfEmployees */ public int getNumberOfEmployees() { return NumberOfEmployees; } /** * @param numberOfEmployees * the numberOfEmployees to set */ public void setNumberOfEmployees(int numberOfEmployees) { if (numberOfEmployees >= 0) NumberOfEmployees = numberOfEmployees; else throw new IllegalArgumentException("Staffing level must be " + "greater than 0"); } /** * @return the revenue */ public BigDecimal getRevenue() { return revenue; } /** * @param revenue * the revenue to set */ public void setRevenue(BigDecimal money) { revenue = money; } // return a String format that defines the Airline object for the user @Override // indicates that this method overrides a superclass method public String toString() { return String.format(" %s: %s\n %s: %s planes\n %s: %s\n %s: %s Employees\n %s: $%f", "Airline", companyName, "Fleet", NumberOfPlanes, "FAA Registration", FaaRegistryID, "Company size", NumberOfEmployees, "Annual Revenue", revenue); }//end of method toString }//end of class
jkirkish/MorePractice
Airline.java
826
/** * @return the faaRegistryID */
block_comment
en
true
88453_3
/* SWEN20003 Object Oriented Software Development * RPG Game Engine * Author: James Stone 761353 stone1 */ import org.newdawn.slick.Image; import org.newdawn.slick.geom.Vector2f; abstract public class Item { private Image image; private Vector2f position; /** * Generates an item, called by subclasses as abstract class * @param image an image representing the item * @param position the start position of the item in the world */ Item(Image image, Vector2f position) { this.image = image; this.position = position; } /** * What happens when an item is picked up * @param playerStats the stats to modify */ public abstract void onPickup(Stats playerStats); /** * Renders an item to the screen * @param camera the camera */ public void render(Camera camera) { if (onScreen(camera)) { image.drawCentered((int) position.getX(), (int) position.getY()); } } /** * Renders an item to the statusPanel * @param camera the camera * @param position where in the status panel to place it */ public void render(Camera camera, Vector2f position) { image.draw((int) position.getX(), (int) position.getY()); } private boolean onScreen(Camera cam) { return cam.getMinX() <= position.getX() && position.getX() <= cam.getMaxX() && cam.getMinY() <= position.getY() && position.getY() <= cam.getMaxY(); } /** * Returns true if a point is within a certain distance of the item * @param point the point * @param distance the distance (px) * @return true if a point is within a certain distance of the item */ public boolean near(Vector2f point, float distance) { return position.distance(point) < distance; } }
jamesmstone/Object-Oriented-Software-Development-Project
src/Item.java
462
/** * Renders an item to the screen * @param camera the camera */
block_comment
en
false
88732_10
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.util.List; /** * @author Anderson Silva Brito * @version 1 */ public class Player extends Actor { /** * Player - construtor * @param String moveDown - botão para mover para baixo * @param String moveUp - botão para mover para cima * @param String moveLeft - botão para mover para esquerda * @param String moveRight - botão para mover para direita * @param String shootButton - botão para atirar * @param int playerAppearance - numero da skin do jogador * @param Weapon weapon - arma do jogador */ private int time; private int velocidade=3; private String direction ="right"; // Direção do personagem private String moveDown; private String moveUp; private String moveLeft; private String moveRight; private String shootButton; private int playerAppearance; //dependencias private HeartBar heart = new HeartBar(999999999,"heart/"); private Weapon weapon; //new ShotgunOne();//new M4(); //private Weapon secondaryWeapon = new Hand() public void act() { /** * atc - metodo de atuar do greenfoot. */ if (time == 0){ createDependencies(); } time++; movePlayer(); shoot(); takeDamage(); weapon.updateWeapon(getX() ,getY(),direction ); heart.updateStatusBar(getX()-9,getY()-30); } // Construtor Pirncipal public Player(String moveDown, String moveUp, String moveLeft, String moveRight, String shootButton, int playerAppearance , Weapon weapon) { this.moveDown = moveDown; this.moveUp = moveUp; this.moveLeft = moveLeft; this.moveRight = moveRight; this.shootButton = shootButton; this.playerAppearance = playerAppearance; this.weapon = weapon; } public String getShootButton(){ /** * getShootButton - retorna o valor do botão de atirar * @return String shootButton */ return shootButton; } public void resetTime(){ /** * resetTime - reseta o timer do jogador e das armas * @return void */ time=0; weapon.resetTime(); } public Weapon getWeapon(){ /** * getWeapon - retorna a arma do jogador * @return Weapon weapon */ return this.weapon; } public void setWeapon(Weapon weapon){ /** * setWeapon - muda a arma do jogador * @param Weapon weapon - arma * @return void */ this.weapon= weapon; } public String getDirection(){ /** * getDirection - retorna a direção do jogador * @return String direction */ return this.direction; } public int getHeart(){ /** * getHeart - retorna a vida atual do jogador * @return int heart */ return heart.getQuantidadeAtual(); } public int getPlayerAppearance(){ /** * getPlayerAppearance - retorna o valor da skin do jogador * @return int playerAppearance */ return playerAppearance; } public void setPlayerAppearance(int playerAppearance){ /** * setPlayerAppearance - muda o valor da skin do jogador (playerAppearance) * @param int playerAppearance - valor da skin * @return void */ this.playerAppearance = playerAppearance; } public void createDependencies(){ /** * createDependencies - adiciona as dependencias ao jogo * @return void */ World world = getWorld(); // Cria um objeto de classe World e o define como o World atual world.addObject(heart, getX() + 25, getY() + 10); world.addObject(weapon,getX(),getY()); } public void movePlayer() { /** * movePlayer - verifica o botão pressionado e move o jogador * @return void */ if (Greenfoot.isKeyDown(moveLeft)) { setLocation(getX() - (velocidade -weapon.getPeso()), getY() ); setImage("ator/leftPlayer" + playerAppearance + ".png"); direction = "left"; } if (Greenfoot.isKeyDown(moveRight)) { setLocation(getX() + (velocidade -weapon.getPeso()), getY() ); setImage("ator/rightPlayer" + playerAppearance + ".png"); direction = "right"; } if (Greenfoot.isKeyDown(moveDown)) { setLocation(getX(), getY() + (velocidade -weapon.getPeso()) ); setImage("ator/downPlayer" + playerAppearance + ".png"); direction = "down"; } if (Greenfoot.isKeyDown(moveUp)) { setLocation(getX(), getY() - (velocidade -weapon.getPeso()) ); setImage("ator/upPlayer" + playerAppearance + ".png"); direction = "up"; } } private void shoot() { /** * shoot - verifica o botão pressiona e efetua um disparo caso der verdadeiro * @return void */ if (Greenfoot.isKeyDown(shootButton)) { weapon.shoot(direction,time); } } public void takeDamage() { /** * takeDamage - verifica o contato com NonPlayerCharacter.class e EnemyAtaque.class , após isso , efetua um bloco de código. * @return void */ Levels world = (Levels)getWorld(); if (isTouching(NonPlayerCharacter.class)){ NonPlayerCharacter enemy = getIntersectingObjects(NonPlayerCharacter.class).get(0); heart.lose(enemy.getDamage()); if(heart.getQuantidadeAtual()<=0){ world.lose(); } } if (isTouching(EnemyAtaque.class)){ EnemyAtaque ataque = getIntersectingObjects(EnemyAtaque.class).get(0); heart.lose(ataque.getDamage()); world.removeObject(ataque); if(heart.getQuantidadeAtual()<=0){ world.lose(); } } } /**public void gameOver() { if (isTouching(FastZombie.class)) { getWorld().showText("GAME OVER!!!", getWorld().getWidth() / 2, getWorld().getHeight() / 2); Greenfoot.stop(); } }*/ }
PAndersonSB/TTS-TryToSurvive
Player.java
1,536
/** * resetTime - reseta o timer do jogador e das armas * @return void */
block_comment
en
true
89133_1
import java.util.*; public class Malady extends OntClass { Set<Symptom> symptoms; private Set<Symptom> inheritedSymptoms; private double priorProbability; public String treatment; public Malady() {} public Malady(String line) { super(line); symptoms = new HashSet<Symptom>(); String[] csvComponents = line.split(","); this.className = csvComponents[0]; inheritedSymptoms = null; if (csvComponents.length >= 3) priorProbability = Double.parseDouble(csvComponents[2]); else priorProbability = 0.0; if (csvComponents.length >= 4) { String[] treatments = Arrays.copyOfRange(csvComponents, 3, csvComponents.length); treatment = ""; for (String t : treatments) { treatment += t + ","; } treatment = treatment.substring(0, treatment.length() - 1); } else treatment = null; } public static Malady fromSymptomLine(String[] symptomLine) { Malady m = new Malady(symptomLine[1]); m.priorProbability = 1.0; // placeholder for now return m; } void addSymptom(Symptom s) { symptoms.add(s); } double getPriorProb() { return priorProbability; } public Set<Symptom> getSymptons() { return symptoms; } public void addSympton(Symptom s) { symptoms.add(s); } public String getTreatments() { String treatments = ""; String emergency = null; Set<OntClass> current = new HashSet<OntClass>(); current.add(this); while (true) { Set<OntClass> next = new HashSet<OntClass>(); for (OntClass classObj : current) { Malady malady = (Malady)classObj; if (malady.treatment != null && !"".equals(malady.treatment)) { if (malady.treatment.contains("Call 911 immediately.")) { emergency = malady.treatment; } else treatments += " " + malady.treatment + ","; } next.addAll(malady.getParents()); } // root's only parent is itself, so if next==current we have // reached the root node if (next.equals(current)) { break; } current = next; } if (treatments.length() > 0 && treatments.charAt(treatments.length() - 1) == ',') treatments = treatments.substring(0, treatments.length() - 1); return emergency == null ? treatments : emergency + " In the meantime: " + treatments; } Set<Symptom> inheritedSymptoms() { if (inheritedSymptoms == null) { inheritedSymptoms = new HashSet<Symptom>(); Set<OntClass> current = new HashSet<OntClass>(); current.addAll(this.getParents()); while (true) { Set<OntClass> next = new HashSet<OntClass>(); for (OntClass classObj : current) { Malady malady = (Malady)classObj; inheritedSymptoms.addAll(malady.getSymptons()); next.addAll(malady.getParents()); } // root's only parent is itself, so if next==current we have // reached the root node if (next.equals(current)) { break; } current = next; } } return inheritedSymptoms; } }
rush8192/bmi210-project
src/Malady.java
842
// root's only parent is itself, so if next==current we have
line_comment
en
false
89363_1
package models; import exceptions.AlreadyExistingContentException; import exceptions.EmptyStringException; import exceptions.InvalidEmailException; import exceptions.InputException; import util.Verificador; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import javax.persistence.*; import javax.transaction.TransactionScoped; import play.data.validation.Constraints; import play.db.ebean.*; import com.avaje.ebean.Model; //import play.db.ebean.Model; import java.io.Serializable; /** * Created by Tainah Emmanuele on 24/07/2016. */ @Entity public class Usuario extends Model implements Serializable { private static final long serialVersionUID = 1L; @Id public long id; public static String DEFAULT_FOLDER_NAME = "Pasta Pessoal"; public static String SHARING_FOLDER_NAME = "Compartilhados"; public static String TRASH_BIN_NAME = "Lixeira"; public static Model.Finder<Long, Usuario> find = new Model.Finder<Long, Usuario>(Long.class, Usuario.class); private String username; private String email; private String password; @ManyToOne private Directory folder; @ManyToOne private Directory compartilhados; @OneToOne(mappedBy = "usuario") @JoinColumn private Directory lixeira; @ElementCollection private List<String> notificacoes; @Transient private List<IArchive> depositingGarbage; public Usuario() throws EmptyStringException { this.folder = new Directory(DEFAULT_FOLDER_NAME); this.compartilhados = new Directory(SHARING_FOLDER_NAME); this.notificacoes = new ArrayList<String>(); this.notificacoes.add("Bem vindo ao TextDropBox"); this.depositingGarbage = new ArrayList<IArchive>(); this.lixeira = new Directory(TRASH_BIN_NAME); this.lixeira.setListArchive(getDepositingGarbage()); try { this.folder.addContent(compartilhados); this.folder.addContent(lixeira); } catch (AlreadyExistingContentException e) { throw new RuntimeException("Erro do sistema"); } } public Usuario(String username, String email, String senha) throws InputException { verify(username, email, senha); this.username = username; this.email = email; this.password = senha; this.folder = new Directory(DEFAULT_FOLDER_NAME); this.compartilhados = new Directory(SHARING_FOLDER_NAME); this.notificacoes = new ArrayList<String>(); this.notificacoes.add("Bem vindo ao TextDropBox"); this.depositingGarbage = new ArrayList<IArchive>(); this.lixeira = new Directory(TRASH_BIN_NAME); this.lixeira.setListArchive(getDepositingGarbage()); try { this.folder.addContent(compartilhados); this.folder.addContent(lixeira); } catch (AlreadyExistingContentException e) { throw new RuntimeException("Erro do sistema"); } } private void verify(String username, String email, String senha) throws InputException { if (!Verificador.verificaString(username) && !Verificador.verificaString(email) && !Verificador.verificaString(senha)) throw new EmptyStringException(); if (!Verificador.verificaString(username) && !Verificador.verificaString(email)) throw new EmptyStringException("Username", "Email"); if (!Verificador.verificaString(username) && !Verificador.verificaString(senha)) throw new EmptyStringException("Username", "Senha"); if (!Verificador.verificaString(email) && !Verificador.verificaString(senha)) throw new EmptyStringException("Email", "Senha"); if (!Verificador.verificaString(username)) throw new EmptyStringException("Username"); if (!Verificador.verificaString(senha)) throw new EmptyStringException("Senha"); if (!Verificador.verificaString(email)) throw new EmptyStringException("Email"); if (!Verificador.verificaEmail(email)) throw new InvalidEmailException(); } public void compartilhar(Usuario user, String tipo, String path) throws AlreadyExistingContentException { Content arquivo = getContent(path); if (!(arquivo.isDirectory()) && !(user.getCompartilhados().hasArchive((IArchive) arquivo))) { ((IArchive) arquivo).compartilhar(user, tipo, this.getUsername()); ArchiveLink linkArchive = new ArchiveLink((IArchive) arquivo); user.getCompartilhados().addContent(linkArchive); } } public void sairCompartilhamento(String path) { Content arquivo = getContent(path); if (!arquivo.isDirectory() && (this.compartilhados.hasArchive((IArchive) arquivo))) { this.getCompartilhados().delContent(arquivo); ((IArchive) arquivo).sairCompartilhamento(this); } } // Metodo para o dono do arquivo cancelar o compartilhamento. public void cancelarCompartilhamento(String path) { IArchive archive = (IArchive) getContent(path); String sharingPath = DEFAULT_FOLDER_NAME + "/" + SHARING_FOLDER_NAME + "/" + archive.getNameType(); archive.cancelarCompartilhamento(sharingPath); } public void removeArchive(String path) { IArchive archive = (IArchive) getContent(path); Directory parent = archive.getParent(); //Adiciona na lixeira this.depositingGarbage.add(archive); //Remove do Diretorio parent.delContent(archive); } //GETTERS public List<IArchive> getDepositingGarbage() { return this.depositingGarbage; } public List<IArchive> getArchives() { return this.folder.getListArchive(); } public List<Directory> getDirectory() { return this.folder.getListDirectory(); } public Directory getCompartilhados() { return this.compartilhados; } public String getEmail() { return this.email; } public String getUsername() { return username; } public Directory getFolder() { return this.folder; } public String getSenha() { return password; } public List<String> getNotificacoes() { return notificacoes; } public long getId() { return id; } public void setId(long id) { this.id = id; } public Content getContent(String path) { String[] pathComponents = path.split("/"); Content content = this.folder; for (int i = 1; i < pathComponents.length; i++) { content = ((Directory) content).getContent(pathComponents[i]); } return content; } //SETTERS public void setNotificacoes(ArrayList<String> notificacoes) { this.notificacoes = notificacoes; } public void setFolderContent(Directory dir, Content conteudo) { conteudo.setParent(dir); } public void setUsername(String username) throws InputException { if (!Verificador.verificaString(username)) throw new EmptyStringException("Username"); this.username = username; } public void setEmail(String email) throws InputException { if (!Verificador.verificaEmail(email)) throw new InvalidEmailException(); this.email = email; } public void setSenha(String password) throws InputException { if (!Verificador.verificaString(password)) throw new EmptyStringException("Senha"); this.password = password; } // EQUALS @Override public boolean equals(Object obj) { if (obj instanceof Usuario) { Usuario usuario = (Usuario) obj; if (usuario.getUsername().equals(this.getUsername()) && usuario.getEmail() == this.getEmail()) { return true; } else { return false; } } return false; } public Directory getLixeira() { return lixeira; } public void setLixeira(Directory lixeira) { this.lixeira = lixeira; } }
tainahemmanuele/projetosi-final
app/models/Usuario.java
1,962
/** * Created by Tainah Emmanuele on 24/07/2016. */
block_comment
en
true
89534_42
import java.util.List; import java.util.Iterator; import java.lang.NullPointerException; import java.util.ArrayList; import java.util.Random; /** @file Cpu.java @brief Automatic player. */ /** @class Cpu @brief Automatic player with knowledge of previous games. */ public class Cpu{ private Knowledge _knowledge; ///< Knwoledge of winner sequencies private Chess _chess; ///< Reference to global chess object private int _profundity; ///< Profunidty level for search the possibilities movements tree. private PieceColor _color; ///< Color of the CPU player /** @brief Default CPU constructor @pre chess is not null, profundity > 0 and color is not null @param knowledge Reference to the knowledge @param chess Reference to the Chess */ public Cpu(Knowledge knowledge,Chess chess,int profundity,PieceColor color){ if(chess==null)throw new NullPointerException("chess given argument cannot be null"); else if(color==null)throw new NullPointerException("color given argument cannot be null"); else if(profundity<=0)throw new IllegalArgumentException("profunidty argument cannot be less or equal to zero"); else{ _knowledge=knowledge; _chess=chess; _profundity=profundity; _color=color; } } /** @brief Makes a movement @pre -- @return Returns a pair which indicates the origin position and final position of the pice movmement choose. */ public Pair<Position,Position> doMovement(){ if(_knowledge!=null){ //If we have knowledge Pair<Position,Position> movement = _knowledge.buscarConeixament(_chess,_color); if(movement!=null){ //If we find knowledge saved we choose the movement to do from the knowledge return movement; } else return minMax();//If we dont find any stored movement we choose from the minmax algorithm } else return minMax();//If we dont have knowledge we choose from the minmax } /** @biref Returns the optimal movement to do. @pre Cpu can do a movement @return Returns the optimal movement to do inside the decision tree with profundity @c _profunidty. */ private Pair<Position,Position> minMax(){ Pair<Position,Position> movement = new Pair<Position,Position>(null,null); i_minMax(0,0,0,movement,Integer.MIN_VALUE,Integer.MAX_VALUE,_chess); return movement; } /** @brief Immersion function for minMaxAlgorsim @pre -- @return Returns the puntuation choosen for the @p playerType of this @p profundity. */ private int i_minMax(Integer score,int profundity,int playerType,Pair<Position,Position> movement,int biggestAnterior,int smallerAnterior,Chess tauler){ if(profundity==_profundity)return score; else if(playerType==0){ //Turn of the cpu player (we will maximize score here) Integer max = Integer.MIN_VALUE; List<Pair<Position,Position>> equealMovementsFirstLevel = new ArrayList<Pair<Position,Position>>();//list to save movements with same puntuation at profunity 1 List<Pair<Position,Piece>> pieces,piecesContrincant; if(_color==PieceColor.White)pieces=tauler.pListWhite(); else pieces=tauler.pListBlack(); Boolean follow = true; Iterator<Pair<Position,Piece>> itPieces = pieces.iterator(); while(itPieces.hasNext() && follow){//for each peice Pair<Position,Piece> piece = itPieces.next(); List<Pair<Position,Integer>> destinyWithScores= tauler.allPiecesDestiniesWithValues(piece.first);//take all possibles movements for this piece which the socre asssociated at this movement Iterator<Pair<Position,Integer>> itMoviments = destinyWithScores.iterator(); while(itMoviments.hasNext() && follow){//for each movement Chess taulerCopia = (Chess)tauler.clone();//We copy the chess and we will work with that copy for not affecting next movements Pair<Position,Integer> pieceMovement = itMoviments.next(); Integer result=pieceMovement.second + score;//add actul + score for actual movement into result Pair<List<MoveAction>,List<Position>> check= taulerCopia.checkMovement(piece.first,pieceMovement.first);//necessary for the chess class, it needs to know the pieces which will die and(list of positions), the list of moveAction is for Console/Visual game class List<MoveAction> actions = taulerCopia.applyMovement(piece.first,pieceMovement.first,check.second,false);//we apply this movement with the returnend parameters on the checkMovement if(_color==PieceColor.White)piecesContrincant=taulerCopia.pListBlack();//take contrincant pieces else piecesContrincant=taulerCopia.pListWhite(); if(!taulerCopia.isCheck(piecesContrincant)){//we look if this movement will cause check if it does we omit it actions.forEach((action)->{ if(action==MoveAction.Promote){//if this movement cause a promotion we choose the biggest puntuation piece to promote List<PieceType> typePieces = taulerCopia.typeList(); Iterator<PieceType> itTypePieces = typePieces.iterator(); PieceType piecetype = itTypePieces.next(); while(itTypePieces.hasNext()){ PieceType nextPieceType = itTypePieces.next(); if(nextPieceType.ptValue()>piecetype.ptValue())piecetype=nextPieceType; } taulerCopia.promotePiece(pieceMovement.first,piecetype); } }); result = i_minMax(result,profundity+1,1,movement,biggestAnterior,smallerAnterior,taulerCopia); //recursive call minMax with playerType = 1 to make the optimal simulation for the other plyer if(result>=max){ if(profundity==0 && result > max){ equealMovementsFirstLevel.clear(); equealMovementsFirstLevel.add(new Pair<Position,Position>( (Position) piece.first.clone(),(Position) pieceMovement.first.clone())); } else if(profundity==0 && result==max)equealMovementsFirstLevel.add(new Pair<Position,Position>((Position) piece.first.clone(),(Position) pieceMovement.first.clone())); if(result>biggestAnterior)biggestAnterior=result; max=result; } /*If the new biggest is bigger than smallest on the anterior node (because anterior will choose the samllest) we dont have to continue inspecinting this branch so we cut it. */ if(smallerAnterior<biggestAnterior){follow=false;} } } } if(profundity==0){/*At first level for CPU player we need to choose the movement if there's more than one with same puntuation we will choose one random. With that we cant be sure that cpu vs cpu will not always choose same movements */ Random rand = new Random(); int n = rand.nextInt(equealMovementsFirstLevel.size()); Pair<Position,Position> choosed = equealMovementsFirstLevel.get(n); movement.first = choosed.first; movement.second = choosed.second; } if(max==Integer.MIN_VALUE)return -100+score;//if the max == MIN_VALUE it means that all movements possibles of CPU puts himself in check(loose game) so we return a value of -100(king value) + preuvious score else return max;//else we return the max value possible } else{ /*Here we will choose the lowest because we want to minamize our negative score the socre here will be negative because the positive for the other player is negative for the cpu*/ //codi del contrincant Integer min = Integer.MAX_VALUE; List<Pair<Position,Piece>> pieces,piecesContrincant; if(_color==PieceColor.Black)pieces=tauler.pListWhite();//peçes del contrincant else pieces=tauler.pListBlack(); Boolean follow = true; Iterator<Pair<Position,Piece>> itPieces = pieces.iterator(); while(itPieces.hasNext() && follow){//FOR EACH PIECE Pair<Position,Piece> piece = itPieces.next(); List<Pair<Position,Integer>> destinyWithScores=tauler.allPiecesDestiniesWithValues(piece.first); Iterator<Pair<Position,Integer>> itMoviments = destinyWithScores.iterator(); while(itMoviments.hasNext() && follow){//FOR EACH MOVEMENT Chess taulerCopia = (Chess)tauler.clone();//We copy the chess and we will work with that copy for not affecting next movements Pair<Position,Integer> pieceMovement = itMoviments.next(); Integer result= -pieceMovement.second + score; Pair<List<MoveAction>,List<Position>> check= taulerCopia.checkMovement(piece.first,pieceMovement.first); List<MoveAction> actions=taulerCopia.applyMovement(piece.first,pieceMovement.first,check.second,false); if(_color==PieceColor.Black)piecesContrincant=taulerCopia.pListBlack();//take contrincant pieces else piecesContrincant=taulerCopia.pListWhite(); if(!taulerCopia.isCheck(piecesContrincant)){//we look if this movement will cause check if it does we omit it actions.forEach((action)->{ if(action==MoveAction.Promote){//if this movement cause a promotion we choose the biggest puntuation piece to promote List<PieceType> typePieces = taulerCopia.typeList(); Iterator<PieceType> itTypePieces = typePieces.iterator(); PieceType piecetype = itTypePieces.next(); while(itTypePieces.hasNext()){ PieceType nextPieceType = itTypePieces.next(); if(nextPieceType.ptValue()>piecetype.ptValue())piecetype=nextPieceType; } taulerCopia.promotePiece(pieceMovement.first,piecetype); } }); result = i_minMax(result,profundity+1,0,movement,biggestAnterior,smallerAnterior,taulerCopia);//recrusive call if(result<=min){//if the result is less than the actual min we update it if(result<smallerAnterior)smallerAnterior=result;//if its smaller than the anteirorSmaller we also updatate this one min=result; } /*If the new smallest is smaller than biggest on the anterior node (because anterior will choose the bigger) we dont have to continue inspecinting this branch so we cut it. */ if(biggestAnterior>smallerAnterior){follow=false;} } } } if(min==Integer.MAX_VALUE)return 100+score;//if contricant cant choose any movement then it means that all of his movements put himself into check so he cant do anythink (he loose) else return min;//else we return the minimum value possible } } }
udg-propro-spring-2020/projecte-2020-a3
src/Cpu.java
2,655
//if its smaller than the anteirorSmaller we also updatate this one
line_comment
en
false
89581_4
package charactercreator; import java.io.Serializable; /* * This class defines Skill objects, which allow the character to interact with the game world in a wide variety of ways. They represent the * crystallization of some type of knowledge and/or training the character has practiced (or is naturally gifted at.) */ public class Skill extends Thing implements Serializable { protected String[] classes; // a list of classes that could use each feature protected String[] tags; // a list of tag words assoiated with this feature -- included for future versions. protected String relevantAbilityScore = "Strength"; // Which ability score will be used when calculating ability bonus values. protected boolean isProficient = false; // Whether or not the character is proficient with this skill, and will receive their Proficiency Bonus when using it. protected int miscBonus = 0; // Any additional bonuses the character has to this skill. //Constructor to be used when reading in data from skills.json public Skill(String idIn, String nameIn, String descriptionIn, String[] classesIn, String relevantAbilityScoreIn, String[] tagsIn) { super(idIn, nameIn, descriptionIn); this.classes = classesIn; this.relevantAbilityScore = relevantAbilityScoreIn; this.tags = tagsIn; this.isProficient = false; this.miscBonus = 0; } // end constructor method // Setters and getters. // For associated tags public String[] getTags() { return this.tags; } public void setTags(String[] newTagsIn) { this.tags = newTagsIn; } // For associated classTypes public String[] getClasses() { return this.classes; } public void setClasses(String[] newClassesIn) { this.classes = newClassesIn; } // For relevant ability score. public void setRelevantAbilityScore(String relevantAbilityScoreIn) { this.relevantAbilityScore = relevantAbilityScoreIn; } public String getRelevantAbilityScore() { return this.relevantAbilityScore; } // For isProficient. public void setIsProficient(boolean isProficientIn) { this.isProficient = isProficientIn; } // shouldn't this be in character.java? public boolean getIsProficient() { return this.isProficient; } // shouldn't this be in character.java? // For miscellaneous bonus. public void setMiscBonus(int miscBonusIn) { this.miscBonus = miscBonusIn; } public int getMiscBonus() { return this.miscBonus; } }
Ian-RSager/CMSC495
src/Skill.java
603
// Whether or not the character is proficient with this skill, and will receive their Proficiency Bonus when using it.
line_comment
en
false
90042_1
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.Random; /** * * @author Pranav */ public class Rm_girl { /** * * @param gi */ public Rm_girl(int gi) { int j, k; try { FileWriter fileOut = new FileWriter("girl.csv");/** Emptying the file*/ fileOut.write(""); fileOut.close(); } catch (Exception e) { System.out.println(e.getMessage()); } String output = ""; char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray(); String sb = ""; Random random = new Random(); /** Generating Random Values for Attributes of Girls*/ for (k = 0; k < gi; k++) { sb = ""; for (j = 0; j < 8; j++) { char c = chars[random.nextInt(chars.length)]; sb += c; } output = sb.toString(); int i = random.nextInt(10); output += "," + i; i = random.nextInt(10); output += "," + i; i = random.nextInt(10000); output += "," + i; output += ",null,single"; // System.out.println(output); /** Saving the data generated in the csv file for Girls*/ try { BufferedWriter bw = new BufferedWriter(new FileWriter("girl.csv", true)); bw.write(output + "\r\n"); bw.flush(); } catch (Exception e) { System.out.println(e.getMessage()); } } } }
PPL-IIITA/ppl-assignment-pranav05
Q2/Rm_girl.java
411
/** * * @param gi */
block_comment
en
true
90065_0
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Q1; /** * * @author Vika$h */ public class Girl { String name; int attractiveness; int intelligence; int maintenance; }
PPL-IIITA/ppl-assignment-IIT2015043
Q1/Girl.java
92
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */
block_comment
en
true
90506_0
/* * Decompiled with CFR 0_110. * * Could not load the following classes: * java.io.FileDescriptor * java.io.PrintWriter * java.lang.IllegalArgumentException * java.lang.IllegalStateException * java.lang.Object * java.lang.String * java.lang.StringBuilder */ import java.io.FileDescriptor; import java.io.PrintWriter; public class bm<D> { int a; b<D> b; a<D> c; boolean d; boolean e; boolean f; boolean g; boolean h; public String a(D d2) { StringBuilder stringBuilder = new StringBuilder(64); dj.a(d2, stringBuilder); stringBuilder.append("}"); return stringBuilder.toString(); } public final void a() { this.d = true; this.f = false; this.e = false; this.b(); } public void a(int n2, b<D> b2) { if (this.b != null) { throw new IllegalStateException("There is already a listener registered"); } this.b = b2; this.a = n2; } public void a(a<D> a2) { if (this.c != null) { throw new IllegalStateException("There is already a listener registered"); } this.c = a2; } public void a(b<D> b2) { if (this.b == null) { throw new IllegalStateException("No listener register"); } if (this.b != b2) { throw new IllegalArgumentException("Attempting to unregister the wrong listener"); } this.b = null; } public void a(String string2, FileDescriptor fileDescriptor, PrintWriter printWriter, String[] arrstring) { printWriter.print(string2); printWriter.print("mId="); printWriter.print(this.a); printWriter.print(" mListener="); printWriter.println(this.b); if (this.d || this.g || this.h) { printWriter.print(string2); printWriter.print("mStarted="); printWriter.print(this.d); printWriter.print(" mContentChanged="); printWriter.print(this.g); printWriter.print(" mProcessingChange="); printWriter.println(this.h); } if (this.e || this.f) { printWriter.print(string2); printWriter.print("mAbandoned="); printWriter.print(this.e); printWriter.print(" mReset="); printWriter.println(this.f); } } protected void b() { } public void b(a<D> a2) { if (this.c == null) { throw new IllegalStateException("No listener register"); } if (this.c != a2) { throw new IllegalArgumentException("Attempting to unregister the wrong listener"); } this.c = null; } public boolean c() { return this.d(); } protected boolean d() { return false; } public void e() { this.d = false; this.f(); } protected void f() { } public void g() { this.e = true; this.h(); } protected void h() { } public void i() { this.j(); this.f = true; this.d = false; this.e = false; this.g = false; this.h = false; } protected void j() { } public String toString() { StringBuilder stringBuilder = new StringBuilder(64); dj.a(this, stringBuilder); stringBuilder.append(" id="); stringBuilder.append(this.a); stringBuilder.append("}"); return stringBuilder.toString(); } public static interface a<D> { } public static interface b<D> { } }
BeCandid/CFR
java/bm.java
918
/* * Decompiled with CFR 0_110. * * Could not load the following classes: * java.io.FileDescriptor * java.io.PrintWriter * java.lang.IllegalArgumentException * java.lang.IllegalStateException * java.lang.Object * java.lang.String * java.lang.StringBuilder */
block_comment
en
true
90849_0
import java.io.*; import java.util.*; import org.graphstream.graph.*; import org.graphstream.graph.implementations.*; import org.graphstream.ui.view.Viewer; public class PTGen { private static final int DOMAIN_SIZE = 2; private static final int BRANCH_SIZE = 2; private static final int MAX_VALUE = 100; private static int nodeID = 1; static String chain(Graph graph, String id, int l) { String oldid = id, newid; for (int i = 0; i < l; i++) { newid = Integer.valueOf(nodeID++).toString(); Node node = graph.addNode(newid); node.addAttribute("ui.label", newid); graph.addEdge(newid + "--" + oldid, newid, oldid); oldid = newid; } return oldid; } static void subtrees(Graph graph, String id, int h, int l, Random rand) { if (h >= 1) { String node = chain(graph, id, l); if (rand.nextBoolean()) for (int i = 0; i < BRANCH_SIZE; i++) subtrees(graph, node, h - 1, l, rand); } } static Collection<Node> children(Graph pt, int index) { Collection<Node> hs = new HashSet<Node>(); Node node = pt.getNode(index); for (Edge edge : node.getEdgeSet()) if (edge.getOpposite(node).getIndex() > index) hs.add(edge.getOpposite(node)); return hs; } static void computedescendants(Graph pt, int index, List<Collection<Node>> descendants) { for (Node ch : children(pt, index)) { computedescendants(pt, ch.getIndex(), descendants); descendants.get(index).add(pt.getNode(ch.getId())); descendants.get(index).addAll(descendants.get(ch.getIndex())); } } static void printconstraint(PrintWriter wcsp, Edge e, Random rand) { int n = (int)Math.pow(DOMAIN_SIZE, 2); wcsp.println(String.format("2 %d %d 0 %d", e.getNode0().getIndex(), e.getNode1().getIndex(), n)); for (int i = 0; i < n; i++) wcsp.println(String.format("%d %d %d", i / DOMAIN_SIZE, i % DOMAIN_SIZE, rand.nextInt(MAX_VALUE))); } public static void main(String[] args) throws IOException { System.setProperty("org.graphstream.ui.renderer", "org.graphstream.ui.j2dviewer.J2DGraphRenderer"); int h = Integer.parseInt(args[0]); int l = Integer.parseInt(args[1]); Random rand = new Random(Integer.parseInt(args[2])); Graph pt = new SingleGraph("pt"); pt.addAttribute("ui.antialias"); pt.addAttribute("ui.stylesheet", "node { size: 20px; fill-color: #FFFFFF; stroke-width: 2px;" + "stroke-mode: plain;shadow-mode: plain; shadow-width: 0px;" + "shadow-color: #CCC; shadow-offset: 3px, -3px; text-style: bold; }" + "node.root {size: 30px; stroke-width: 2px; text-size: 12; }"); Node root = pt.addNode("0"); root.addAttribute("ui.label", "R"); root.addAttribute("ui.class", "root"); chain(pt, "0", h * l); for (int i = Math.abs(rand.nextInt()) % 2; i < h; i++) for (int j = 0; j < BRANCH_SIZE - 1; j++) subtrees(pt, Integer.valueOf(i * l).toString(), h - i, l, rand); pt.display(); Graph primal = Graphs.clone(pt); List<Collection<Node>> descendants = new ArrayList<Collection<Node>>(); for (int i = 0; i < pt.getNodeCount(); i++) descendants.add(new HashSet<Node>()); computedescendants(pt, 0, descendants); for (int i = 0; i < pt.getNodeCount(); i++) descendants.get(i).removeAll(children(pt, i)); for (Node node : pt.getEachNode()) for (Node desc : descendants.get(node.getIndex())) { //System.out.println(node.getId() + "--" + desc.getId()); //if (rand.nextBoolean()) primal.addEdge(node.getId() + "--" + desc.getId(), node.getId(), desc.getId()); } //primal.display(); PrintWriter wcsp = new PrintWriter(args[3], "UTF-8"); wcsp.println(String.format("%s %d %d %d %d", args[2], primal.getNodeCount(), DOMAIN_SIZE, primal.getEdgeCount(), Integer.MAX_VALUE)); for (int i = 0; i < pt.getNodeCount() - 1; i++) wcsp.print(String.format("%d ", DOMAIN_SIZE)); wcsp.println(String.format("%d", DOMAIN_SIZE)); for (Edge edge : primal.getEachEdge()) printconstraint(wcsp, edge, rand); wcsp.close(); } }
filippobistaffa/ptgen
PTGen.java
1,393
//System.out.println(node.getId() + "--" + desc.getId());
line_comment
en
true
91144_1
import java.util.Stack; /************************************************************************* * Compilation: javac Graph.java * Execution: java Graph input.txt * Dependencies: Bag.java In.java StdOut.java * Data files: http://algs4.cs.princeton.edu/41undirected/tinyG.txt * * A graph, implemented using an array of sets. * Parallel edges and self-loops allowed. * * % java Graph tinyG.txt * 13 vertices, 13 edges * 0: 6 2 1 5 * 1: 0 * 2: 0 * 3: 5 4 * 4: 5 6 3 * 5: 3 4 0 * 6: 0 4 * 7: 8 * 8: 7 * 9: 11 10 12 * 10: 9 * 11: 9 12 * 12: 11 9 * * % java Graph mediumG.txt * 250 vertices, 1273 edges * 0: 225 222 211 209 204 202 191 176 163 160 149 114 97 80 68 59 58 49 44 24 15 * 1: 220 203 200 194 189 164 150 130 107 72 * 2: 141 110 108 86 79 51 42 18 14 * ... * *************************************************************************/ /** * The <tt>Graph</tt> class represents an undirected graph of vertices named 0 * through <em>V</em> - 1. It supports the following two primary operations: add * an edge to the graph, iterate over all of the vertices adjacent to a vertex. * It also provides methods for returning the number of vertices <em>V</em> and * the number of edges <em>E</em>. Parallel edges and self-loops are permitted. * <p> * This implementation uses an adjacency-lists representation, which is a * vertex-indexed array of {@link Bag} objects. All operations take constant * time (in the worst case) except iterating over the vertices adjacent to a * given vertex, which takes time proportional to the number of such vertices. * <p> * For additional documentation, see * <a href="http://algs4.cs.princeton.edu/41undirected">Section 4.1</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class Graph { private final int V; private int E; private Bag<Integer>[] adj; private Mark[] marked; private boolean isCycle = false; private enum Mark { WHITE, GRAY, BLACK }; /** * Initializes an empty graph with <tt>V</tt> vertices and 0 edges. param V * the number of vertices * * @throws java.lang.IllegalArgumentException * if <tt>V</tt> < 0 */ public Graph(int V) { if (V < 0) throw new IllegalArgumentException("Number of vertices must be nonnegative"); this.V = V; this.E = 0; adj = (Bag<Integer>[]) new Bag[V]; marked = new Mark[V]; for (int v = 0; v < V; v++) { adj[v] = new Bag<Integer>(); marked[v] = Mark.WHITE; } } /** * Initializes a graph from an input stream. The format is the number of * vertices <em>V</em>, followed by the number of edges <em>E</em>, followed * by <em>E</em> pairs of vertices, with each entry separated by whitespace. * * @param in * the input stream * @throws java.lang.IndexOutOfBoundsException * if the endpoints of any edge are not in prescribed range * @throws java.lang.IllegalArgumentException * if the number of vertices or edges is negative */ public Graph(In in) { this(in.readInt()); int E = in.readInt(); if (E < 0) throw new IllegalArgumentException("Number of edges must be nonnegative"); for (int i = 0; i < E; i++) { int v = in.readInt(); int w = in.readInt(); addEdge(v, w); } } /** * Initializes a new graph that is a deep copy of <tt>G</tt>. * * @param G * the graph to copy */ public Graph(Graph G) { this(G.V()); this.E = G.E(); for (int v = 0; v < G.V(); v++) { // reverse so that adjacency list is in same order as original Stack<Integer> reverse = new Stack<Integer>(); for (int w : G.adj[v]) { reverse.push(w); } for (int w : reverse) { adj[v].add(w); } } } /** * Returns the number of vertices in the graph. * * @return the number of vertices in the graph */ public int V() { return V; } /** * Returns the number of edges in the graph. * * @return the number of edges in the graph */ public int E() { return E; } /** * Adds the undirected edge v-w to the graph. * * @param v * one vertex in the edge * @param w * the other vertex in the edge * @throws java.lang.IndexOutOfBoundsException * unless both 0 <= v < V and 0 <= w < V */ public void addEdge(int v, int w) { if (v < 0 || v >= V) throw new IndexOutOfBoundsException(); if (w < 0 || w >= V) throw new IndexOutOfBoundsException(); E++; adj[v].add(w); // for an undirected edges uncomment below // for directed edges leave the line below commented // adj[w].add(v); } private void dfs(int v) { System.out.println("visiting:" + v); marked[v] = Mark.GRAY; for (int w : adj[v]) { if (marked[w] == Mark.WHITE) dfs(w); } marked[v] = Mark.BLACK; } private void dfs2(int v) { System.out.println("visiting:" + v); marked[v] = Mark.GRAY; for (int w : adj[v]) { if (marked[w] == Mark.GRAY) { isCycle = true; } if (marked[w] == Mark.WHITE) dfs2(w); } marked[v] = Mark.BLACK; } private void cycle(int v) { while(notVisited()!=-1){ dfs2(notVisited()); } if(isCycle) System.out.println("There is a cylce"); else System.out.println("there is no cycle"); } // function returns -1 if there are no more unvisited nodes private int notVisited() { for (int i = 0; i < V - 1; i++) { if (marked[i] == Mark.WHITE) return i; } return -1; } private void connectedComponents(int v) { int count = 0; // while unvisited nodes while (notVisited() != -1) { System.out.println("\nComponent " + count); dfs(notVisited()); count++; } System.out.println("There are " + count + " components"); } /** * Returns the vertices adjacent to vertex <tt>v</tt>. * * @return the vertices adjacent to vertex <tt>v</tt> as an Iterable * @param v * the vertex * @throws java.lang.IndexOutOfBoundsException * unless 0 <= v < V */ public Iterable<Integer> adj(int v) { if (v < 0 || v >= V) throw new IndexOutOfBoundsException(); return adj[v]; } /** * Returns a string representation of the graph. This method takes time * proportional to <em>E</em> + <em>V</em>. * * @return the number of vertices <em>V</em>, followed by the number of * edges <em>E</em>, followed by the <em>V</em> adjacency lists */ public String toString() { StringBuilder s = new StringBuilder(); String NEWLINE = System.getProperty("line.separator"); s.append(V + " vertices, " + E + " edges " + NEWLINE); for (int v = 0; v < V; v++) { s.append(v + ": "); for (int w : adj[v]) { s.append(w + " "); } s.append(NEWLINE); } return s.toString(); } /** * Unit tests the <tt>Graph</tt> data type. */ public void makeSet(int x){ KrusNode node = new KrusNode(); } public static void main(String[] args) { In in = new In(args[0]); Graph G = new Graph(in); StdOut.println(G); // System.out.println("\n"); // G.connectedComponents(0); G.cycle(0); } }
sirjudge/Graph
Graph.java
2,486
/** * The <tt>Graph</tt> class represents an undirected graph of vertices named 0 * through <em>V</em> - 1. It supports the following two primary operations: add * an edge to the graph, iterate over all of the vertices adjacent to a vertex. * It also provides methods for returning the number of vertices <em>V</em> and * the number of edges <em>E</em>. Parallel edges and self-loops are permitted. * <p> * This implementation uses an adjacency-lists representation, which is a * vertex-indexed array of {@link Bag} objects. All operations take constant * time (in the worst case) except iterating over the vertices adjacent to a * given vertex, which takes time proportional to the number of such vertices. * <p> * For additional documentation, see * <a href="http://algs4.cs.princeton.edu/41undirected">Section 4.1</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */
block_comment
en
false