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 |
---|---|---|---|---|---|---|---|---|
124639_0 |
import java.awt.event.*;
import java.awt.*;
import java.applet.*;
/*<applet code=ListDemo height=300 width=400></applet> */
public class ListDemo extends Applet implements ActionListener{
String msg = "";
List os,browser;
public void init(){
os = new List(3,false);
os.add("win",0);
os.add("mac",1);
os.add("linux",2);
browser = new List(3,false);
browser.add("brave",0);
browser.add("chrome",1);
browser.add("firefox",2);
add(os);
add(browser);
os.addActionListener(this);
browser.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
repaint();
}
public void paint(Graphics g){
int idx[];
msg = "Current OS :";
idx = os.getSelectedIndexes();
for (int i = 0; i < idx.length; i++) {
msg+=os.getItem(idx[i]) + "";
}
g.drawString(msg, 100 , 100);
msg="Current Broswer";
msg+=browser.getSelectedItem();
g.drawString(msg, 6 , 140);
}
}
| 0xVikasRushi/java-swing | ListDemo.java | 312 | /*<applet code=ListDemo height=300 width=400></applet> */ | block_comment | en | true |
125231_0 | import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
/**
* Framework for making bots.
*
* @author Jelmer Mulder
* @author Sebastian Österlund
* @author Yoran Sturkenboom
* Date: 11/01/2014
*/
public abstract class Bot15 {
public static final int NEUTRAL = 0,
FRIENDLY = 1,
HOSTILE = 2;
static Logger logger;
/**
* Function for selecting the planet from which to send ships.
*
*
* @param pw PlanetWars15 object from which to derive game state.
* @return The planet from which to send ships.
*/
public abstract Action15 getAction(PlanetWars15 pw);
/**
* Completes a turn. Falls back on CustomBot15 if the determined action is invalid..
* @param pw Base state.
* @param action Action15 to issue.
*/
private static void DoTurn(PlanetWars15 pw, Action15 action) {
if (action.isValid()){
pw.IssueOrder(action.source, action.target);
} else {
System.err.println("Custombot");
//Action15 customAction = (new CustomBot15()).getAction(pw);
//pw.IssueOrder(customAction.source, customAction.target);
}
}
public static void execute(Bot15 bot) {
logger = getLogger(bot);
String line = "";
String message = "";
int c;
try {
while ((c = System.in.read()) >= 0) {
switch (c) {
case '\n':
if (line.equals("go")) {
PlanetWars15 pw = new PlanetWars15(message);
Action15 action = null;
try {
action = bot.getAction(pw);
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pbw = new PrintWriter(sw);
e.printStackTrace(pbw);
pw.log(sw.toString());
logger.info((sw.toString()));
}
DoTurn(pw, action);
pw.FinishTurn();
message = "";
} else {
message += line + "\n";
}
line = "";
break;
default:
line += (char) c;
break;
}
}
} catch (Exception e) {
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
String stackTrace = writer.toString();
System.err.println(stackTrace);
System.exit(1); //just stop now. we've got a problem
}
}
/**
* Returns a logger which can be used to write to a log file.
*
* @return the logger.
*/
public static Logger getLogger(Bot15 bot){
Logger logger = Logger.getLogger("MyLog");
FileHandler fh;
try {
// This block configure the logger with handler and formatter
fh = new FileHandler(System.getProperty("user.dir")+"/../logs/"+ bot.getClass().getSimpleName()+"-" + String.valueOf(System.currentTimeMillis()) + ".txt");
logger.addHandler(fh);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
// the following statement is used to log any messages
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return logger;
}
}
| jelmr/IntelligentSystems | src/Bot15.java | 917 | /**
* Framework for making bots.
*
* @author Jelmer Mulder
* @author Sebastian Österlund
* @author Yoran Sturkenboom
* Date: 11/01/2014
*/ | block_comment | en | true |
125847_0 |
// Wenn (Farbe Farbe, Wert Wert) sind die enum Klassen im globalen scope nicht mehr aufrufbar, da ueberschattet von lokalen variablen
public record Karte(Farbe KartenFarbe, Wert KartenWert){
public String toString() {
return KartenFarbe.toString()+KartenWert.toString();
}
public static Karte neueKarte(Farbe f, Wert w) {
Karte nKarte = new Karte(f,w);
return nKarte;
}
public static Karte neueKarte(String f, String w) {
return Karte.neueKarte(Farbe.valueOf(f), Wert.valueOf(w));
}
public static int kombinationen() {
return Farbe.values().length * Wert.values().length;
}
public static Karte[] skatblatt(){
Karte[] res = new Karte[kombinationen()];
int i = 0;
for(Farbe IFarbe : Farbe.values()) {
for(Wert IWert : Wert.values()) {
res[i] = neueKarte(IFarbe, IWert);
i++;
}
}
return res;
}
public boolean bedient(Karte other) {
if(this.KartenWert == Wert.BUBE) {
return true;
} else if(this.KartenFarbe == other.KartenFarbe) {
return true;
} else if(this.KartenWert == other.KartenWert) {
return true;
}
return false;
}
public boolean bedienbar(Karte... kn) {
for(Karte IKarte : kn) {
if(IKarte.bedient(this)) {
return true;
}
}
return false;
}
public static void druckeDoppelBedienungen() {
Karte[] Skatblatt = skatblatt();
for(Karte IKarte: Skatblatt) {
for(Karte IKarte2: Skatblatt) {
if(IKarte.bedient(IKarte2) && IKarte2.bedient(IKarte) && !IKarte.equals(IKarte2)) {
System.out.println(IKarte + " bedient " + IKarte2 + " und " + IKarte2 + " bedient " + IKarte);
}
}
}
}
}
| Programmierung-Nils-Jonathan/Programmierung_Uebungsblatt_4_Aufgabe_3_5 | Karte.java | 615 | // Wenn (Farbe Farbe, Wert Wert) sind die enum Klassen im globalen scope nicht mehr aufrufbar, da ueberschattet von lokalen variablen | line_comment | en | true |
125851_0 | /*
* I declare that this code was written by me.
* I do not copy or allow others to copy my code.
* I understand that copying code is considered as plagiarism.
*
* Student Name: Hedil Rahamad
* Student ID: 22013393
* Class: E65F
* Date/Time created: Saturday 03-12-2022 00:41
*/
/**
* @author 22013393
*
*/
public class Ward {
private String ward;
private String description;
private int bedCount;
private double bedCharge;
public Ward(String ward, String description, int bedCount, double bedCharge) {
this.ward=ward;
this.description=description;
this.bedCount=bedCount;
this.bedCharge=bedCharge;
}
public String getWard() {
return ward;
}
public String getDescription() {
return description;
}
public int getBedCount() {
return bedCount;
}
public double getBedCharge() {
return bedCharge;
}
}
| 22013393-Hedil/JavaGA | Ward.java | 294 | /*
* I declare that this code was written by me.
* I do not copy or allow others to copy my code.
* I understand that copying code is considered as plagiarism.
*
* Student Name: Hedil Rahamad
* Student ID: 22013393
* Class: E65F
* Date/Time created: Saturday 03-12-2022 00:41
*/ | block_comment | en | true |
126214_2 | /**
* Knight is an observer that reacts to warning
* @author Adam Nguyen
*
*/
public class Knight implements Observer{
/**
* subject watchman variable gets set to parameter in constructor and is added to observer list
*/
private Subject watchman;
public Knight(Subject watchman)
{
this.watchman=watchman;
watchman.registerObserver(this);
}
/**
* update method decides how knight reacts based on severity of warning
*/
public void update(int warning)
{
if(warning==1)
System.out.println("Knight:Helps everyone get home safe");
else if(warning==2)
System.out.println("Knight:Prepares for battle");
else
System.out.println("Invalid warning");
}
}
| DopaiHub/Town | src/Knight.java | 204 | /**
* update method decides how knight reacts based on severity of warning
*/ | block_comment | en | true |
126295_0 | /*
What are Threads??
Threads are independent sequences of execution within the same program that share the same code and data address.Each thread has its own stack to make method calls and store local variables.
Advantages of Threads:
1:Handle concurrent operations.Server applications can handle multiple clients by granting each client its own thread.
2:Lengthy computations can be performed in the background without disturbing the user.
3:Threads make a code simpler.
4:Provide a high degree of control.
*/
| Ban-zee/Learning | Threads.java | 118 | /*
What are Threads??
Threads are independent sequences of execution within the same program that share the same code and data address.Each thread has its own stack to make method calls and store local variables.
Advantages of Threads:
1:Handle concurrent operations.Server applications can handle multiple clients by granting each client its own thread.
2:Lengthy computations can be performed in the background without disturbing the user.
3:Threads make a code simpler.
4:Provide a high degree of control.
*/ | block_comment | en | true |
126309_0 | /*Develop a program to perform a binary search on
a one-dimensional integer array LIST of dimension N.
You should develop an independent search method (call
it BinSearch), and write your program so that the
BinSearch method is invoked from your main program
or another method. The BinSearch method should
accept a search key parameter and return a Boolean
value (Success). Maintain a count of the number of
comparisons attempted during the execution of the
method. Assume the array is already sorted in
ascending order, and that there are no duplicate
entries. Use a while loop for the binary search.
Repeat the above assignment using a recursive method
for the binary search instead of the while loop.
Repeat the above to perform a sequential search
on the same array. In each of the above cases,
maintain a count of the number of iterations needed
to perform the different search functions on the same
array. I all cases, remember to include the condition
when a search key is NOT found in the array.
*/
import java.lang.Math.*;
import java.util.*;
public class Assignment9
{
public static void main (String args[])
{
Scanner scan = new Scanner(System.in);
System.out.println("Specify how long the list is, N");
int N = Integer.parseInt(scan.nextLine());
System.out.println("What integer would you like to search for?");
int search = Integer.parseInt(scan.nextLine());
System.out.println(BinSearch(N, search));
}
public static int BinSearch(int N, int x)
{
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i=0; i<N; i++)
{
list.add(i+1);
}
int min = 0, max = N-1;
int guess = (min + max / 2);
int count = 0;
boolean check = true;
while (check == true)
{
if (list.get(guess) == x)
{
check = false;
count ++;
System.out.println("Count =" + count);
}
else if (list.get(guess) < x)
{
min = guess + 1;
count ++;
check = true;
System.out.println("Count =" + count);
}
else if (list.get(guess) > x)
{
max = guess -1;
count ++;
check = true;
System.out.println("Count =" + count);
}
}return guess;
}
}
| tuffacton/CSC_200_Work | Assignment9.java | 604 | /*Develop a program to perform a binary search on
a one-dimensional integer array LIST of dimension N.
You should develop an independent search method (call
it BinSearch), and write your program so that the
BinSearch method is invoked from your main program
or another method. The BinSearch method should
accept a search key parameter and return a Boolean
value (Success). Maintain a count of the number of
comparisons attempted during the execution of the
method. Assume the array is already sorted in
ascending order, and that there are no duplicate
entries. Use a while loop for the binary search.
Repeat the above assignment using a recursive method
for the binary search instead of the while loop.
Repeat the above to perform a sequential search
on the same array. In each of the above cases,
maintain a count of the number of iterations needed
to perform the different search functions on the same
array. I all cases, remember to include the condition
when a search key is NOT found in the array.
*/ | block_comment | en | true |
126555_6 | import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
/**
*
* @author Arezoo Vejdanparast <[email protected]> & Ali Karami <[email protected]>
*/
public class OneHopOptimal {
private ArrayList<Camera> cameras;
private ArrayList<Object> objects;
private Double[] zooms;
private int steps;
private Double threshold;
private String outputPath;
private int[] step0CamConfig;
private int tempMinK; //for internal use with recursive function
private int[] tempCamConfig; //for internal use with recursive function
/**
* Constructor
* @param settings An instance of Settings class that contains all scenario settings.
* @param steps Number of time steps the simulation will run for.
* @param threshold The selected confidence threshold to determine whether an object
* is detectable or not.
* @param outputPath The path to output folder.
*/
public OneHopOptimal(Settings settings, int steps, Double threshold, String outputPath) {
System.out.println("Running Optimal algorithm ....\n");
this.cameras = settings.cameras;
this.objects = settings.objects;
this.zooms = this.cameras.get(0).zooms;
this.steps = steps;
this.threshold = threshold;
this.outputPath = outputPath;
this.step0CamConfig = new int[cameras.size()];
Arrays.fill(step0CamConfig, 0);
run();
}
/**
* Runs the optimal algorithm simulation
*/
private void run() {
int[] minKCover = new int[steps];
int[] z = new int[cameras.size()];
for (int n=0 ; n<cameras.size() ; n++)
z[n] = -1;
for (int step=0 ; step<steps ; step++) {
tempMinK = 0;
tempCamConfig = new int[cameras.size()];
System.out.print("step "+step+" .... ");
computeMinKCover(cameras.size(), new int[cameras.size()], z);
z = tempCamConfig.clone();
minKCover[step] = tempMinK;
if (step==0)
step0CamConfig = tempCamConfig.clone();
updateObjects();
System.out.println("COMPLETE");
}
long tableCount = (long)Math.pow(zooms.length, cameras.size());
System.out.println("Table Count = "+tableCount+"\n");
exportResult(minKCover);
}
/**
* Computes the minimum k-covers for a given step by finding the table with maximum min k and
* saves the value in a global variable (tempMinK) to be used in run().
* @param size The number of cameras in each (recursive) run.
* @param zoomList An (initially empty) auxiliary list for keeping the configuration indexes.
* @param step The current time step.
*/
private void computeMinKCover(int size, int[] zoomList, int[] zIndex) {
if (size==0) {
int tableResult = getMinK(zoomList);
if (tableResult > tempMinK) {
tempMinK = tableResult;
tempCamConfig = zoomList.clone();
}
}
else {
if (zIndex[0]==-1) {
for (int z=0 ; z<zooms.length ; z++) {
zoomList[size-1] = z;
computeMinKCover(size-1, zoomList, zIndex);
}
}
else {
for (int z=0 ; z<zooms.length ; z++) {
if (Math.abs(z-zIndex[size-1])<2) {
zoomList[size-1] = z;
computeMinKCover(size-1, zoomList, zIndex);
}
}
}
}
}
/**
* Returns the minimum number of cameras that detect each object.
* @param zoomList List of selected cameras' zoom indexes.
* @return the k value of k-cover with a specific (given) camera configuration.
*/
private int getMinK(int[] zoomList) {
int[] objCover = new int[objects.size()];
for (int n=0 ; n<cameras.size() ; n++) {
int z = zoomList[n];
for (int m=0 ; m<objects.size() ; m++) {
if (isDetectable(m, n, z))
objCover[m]++;
}
}
return minimum(objCover);
}
/**
* Checked whether an object is detectable by a camera with a specified zoom (FOV).
* @param m The index of the object in the list of objects
* @param n The index of the camera in the list of cameras
* @param z The index of the zoom level in the list of zoom values
* @return True if the object is within FOV (zoom range) AND the camera can see it
* with a confidence above threshold. False otherwise.
*/
private boolean isDetectable(int m, int n, int z) {
Double distance = Math.sqrt(Math.pow((cameras.get(n).x-objects.get(m).x), 2) + Math.pow((cameras.get(n).y-objects.get(m).y), 2));
if (distance > cameras.get(n).zooms[z])
return false;
else {
double b = 15;
Double conf = 0.95 * (b / (cameras.get(n).zooms[z] * distance)) - 0.15;
return (conf >= threshold);
}
}
/**
* Returns the minimum value of a list of integers < 10000.
* @param list The list of integer
* @return The minimum integer value in the list
*/
private static int minimum(int[] list) {
int min = 10000;
for (int i : list){
if (i < min)
min = i;
}
return min;
}
/**
* Updates all objects one time step.
*/
private void updateObjects() {
for (Object obj : objects)
obj.update();
}
/**
* Writes the result to '*-oneHopOptimal.csv' file.
* @param minKCover The array of minimum k-cover values
*/
private void exportResult(int[] minKCover) {
FileWriter outFile;
try {
outFile = new FileWriter(outputPath+"-oneHopOptimal.csv");
PrintWriter out = new PrintWriter(outFile);
out.println("1-hop optimal");
for (int k : minKCover)
out.println(k);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Gives read access to the camera configurations that is selected in step 0 of the runtime
* @return A list camera configurations that is optimised for step 0
*/
public int[] getStep0CamConfig() {
return step0CamConfig;
}
}
| alijy/CamSimLite | src/OneHopOptimal.java | 1,783 | /**
* Returns the minimum number of cameras that detect each object.
* @param zoomList List of selected cameras' zoom indexes.
* @return the k value of k-cover with a specific (given) camera configuration.
*/ | block_comment | en | false |
127308_3 |
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JOptionPane;
public class Card {
// define data members
private int card_val;
private String suit;
private static int[] num = new int[]{1,2,3,4,5,6,7,8,9,10,11,12,13};
private static String[] suits = new String[]{"spades", "clubs", "hearts","diamonds"};
//default constructor
public Card () {
// initialization
card_val = 0;
suit = "";
}
//Assume one of the suits from {"spades", "clubs", "hearts","diamonds"} will be passed in, not some random string
public Card (int card_val, String suit)
{
this.card_val = card_val;
this.suit = suit;
}
public static void buildDeck(ArrayList<Card> deck) {
// Given an empty deck, construct a standard deck of playing cards
deck.clear(); // clear deck so that when rebuilding the deck, it won't use the deck that remains
//build a 52-card deck, 1-Ace, 11-Jack, 12-Queen, 13-King
for(int i = 0;i < num.length;i++)
{
for(int j = 0;j < suits.length;j++)
{
Card c1 = new Card(num[i],suits[j]); //calling the 2-parameter constructor
deck.add(c1);
}
}
}
public static void initialDeal(ArrayList<Card> deck, ArrayList<Card> playerHand, ArrayList<Card> dealerHand){
// Deal two cards from the deck into each of the player's hand and dealer's hand
//rebuild the deck, or renew the deck, every time a new round starts. so the size of deck is always 52 at the beginning of each round
buildDeck(deck);
//System.out.println(deck.size());
//clear both hands to make sure the hands from last round don't carry on to the new round
playerHand.clear();
dealerHand.clear();
//check if the deck indeed has at least 4 cards to complete the initial deal.
if(deck.size() >= 4)
{
Random rand = new Random();
//no need to use for loops since we're only drawing 2 cards for each side
playerHand.add(deck.remove(rand.nextInt(deck.size()))); //each card is drawn from a random index
playerHand.add(deck.remove(rand.nextInt(deck.size())));
dealerHand.add(deck.remove(rand.nextInt(deck.size())));
dealerHand.add(deck.remove(rand.nextInt(deck.size())));
}
//output a line instead of crashing the program
else
{
System.out.println("There're fewer than 4 cards in the deck");
}
}
public static void dealOne(ArrayList<Card> deck, ArrayList<Card> hand){
// this should deal a single card from the deck to the hand
//check if the deck indeed has at least 1 card to complete the deal.
if(deck.size() >= 1)
{
Random rand = new Random();
hand.add(deck.remove(rand.nextInt(deck.size()))); //draw card from random index
}
//output a line instead of crashing the program
else
{
System.out.println("There's fewer than 1 card in the deck");
}
}
public static boolean checkBust(ArrayList<Card> hand){
// This should return whether a given hand's value exceeds 21
int total = 0;
for(int i = 0; i < hand.size();i++)
{
if(hand.get(i).card_val > 10)
{
total += 10;
}
else
{
total += hand.get(i).card_val;
/* Because we're checking for bust, it's easier(safer) to always
treat Ace as 1 */
}
}
if(total > 21)
{
return true;
}
else{
return false;
}
}
public static boolean dealerTurn(ArrayList<Card> deck, ArrayList<Card> hand){
// This should conduct the dealer's turn and
// Return true if the dealer busts; false otherwise
int total = SumHand(hand);
while(total < 17)
{
dealOne(deck, hand); //draw a card from deck to hand while total is smaller than 17
total = SumHand(hand); //updates total
}
if(total > 21) //bust
{
return true;
}
else{
return false;
}
}
public static int whoWins(ArrayList<Card> playerHand, ArrayList<Card> dealerHand){
// This should return 1 if the player wins and 2 if the dealer wins
if(SumHand(playerHand) <= SumHand(dealerHand)) //compare values for both hands, dealer wins even when they tie
{
return 2;
}
else
{
return 1;
}
}
public static String displayCard(ArrayList<Card> hand){
// Return a string describing the card which has index 1 in the hand
if(hand.get(1).card_val == 1) //1->Ace
{
return "Ace " + "of " + hand.get(1).suit;
}
else if(hand.get(1).card_val == 11) //11->Jack
{
return "Jack " + "of " + hand.get(1).suit;
}
else if(hand.get(1).card_val == 12) //12-->Queen
{
return "Queen " + "of " + hand.get(1).suit;
}
else if(hand.get(1).card_val == 13) //13->King
{
return "King " + "of " + hand.get(1).suit;
}
else //ok to use original numbers to represent value of card
{
return hand.get(1).card_val + " of " + hand.get(1).suit;
}
}
public static String displayHand(ArrayList<Card> hand){
// Return a string listing the cards in the hand
String result = "|"; //to seperate each card with "|"
for(int i = 0; i < hand.size();i++)
{
if(hand.get(i).card_val == 1)
{
result += "Ace of " + hand.get(i).suit + "|"; //1->Ace
}
else if(hand.get(i).card_val == 11)
{
result += "Jack of " + hand.get(i).suit + "|"; //11->Jack
}
else if(hand.get(i).card_val == 12)
{
result += "Queen of " + hand.get(i).suit + "|";//12-->Queen
}
else if(hand.get(i).card_val == 13)
{
result += "King of " + hand.get(i).suit + "|"; //13->King
}
else
{
result += hand.get(i).card_val + " of " + hand.get(i).suit + "|";
}
}
return result;
}
public static int SumHand(ArrayList<Card> hand) //added method that computes the sum in hand
{
int values = 0; //total values of cards in hand
int Ace = 0; //number of aces
for(int i = 0; i < hand.size();i++)
{
if(hand.get(i).card_val == 1)
{
values += 1; //use lower bound of ace value
Ace+=1;
}
else if(hand.get(i).card_val > 10)
{
values += 10; //jack, queen, king = 10
}
else
{
values += hand.get(i).card_val;
}
}
while(values<12 && Ace > 0) //make one ace's value 11 if total value doesn't exceed 12
{
values += 10;
Ace -= 1;
}
return values;
}
//override toString() method to display card objects
@Override
public String toString() {
return card_val + " of " + suit;
}
public static void main(String[] args) {
int playerChoice, winner;
ArrayList<Card> deck = new ArrayList<Card> ();
buildDeck(deck);
playerChoice = JOptionPane.showConfirmDialog(null, "Ready to Play Blackjack?", "Blackjack", JOptionPane.OK_CANCEL_OPTION);
if((playerChoice == JOptionPane.CLOSED_OPTION) || (playerChoice == JOptionPane.CANCEL_OPTION))
System.exit(0);
Object[] options = {"Hit","Stand"};
boolean isBusted, dealerBusted;
boolean isPlayerTurn;
ArrayList<Card> playerHand = new ArrayList<>();
ArrayList<Card> dealerHand = new ArrayList<>();
do{ // Game loop
initialDeal(deck, playerHand, dealerHand);
isPlayerTurn=true;
isBusted=false;
dealerBusted=false;
while(isPlayerTurn){
// Shows the hand and prompts player to hit or stand
playerChoice = JOptionPane.showOptionDialog(null,"Dealer shows " + displayCard(dealerHand) + "\n Your hand is: " + displayHand(playerHand) + "\n What do you want to do?","Hit or Stand",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if(playerChoice == JOptionPane.CLOSED_OPTION)
System.exit(0);
else if(playerChoice == JOptionPane.YES_OPTION){
dealOne(deck, playerHand);
isBusted = checkBust(playerHand);
if(isBusted){
// Case: Player Busts
playerChoice = JOptionPane.showConfirmDialog(null,"Player has busted!", "You lose", JOptionPane.OK_CANCEL_OPTION);
if((playerChoice == JOptionPane.CLOSED_OPTION) || (playerChoice == JOptionPane.CANCEL_OPTION))
System.exit(0);
isPlayerTurn=false;
}
}
else{
isPlayerTurn=false;
}
}
if(!isBusted){ // Continues if player hasn't busted
dealerBusted = dealerTurn(deck, dealerHand);
if(dealerBusted){ // Case: Dealer Busts
playerChoice = JOptionPane.showConfirmDialog(null, "The dealer's hand: " +displayHand(dealerHand) + "\n \n Your hand: " + displayHand(playerHand) + "\nThe dealer busted.\n Congrautions!", "You Win!!!", JOptionPane.OK_CANCEL_OPTION);
if((playerChoice == JOptionPane.CLOSED_OPTION) || (playerChoice == JOptionPane.CANCEL_OPTION))
System.exit(0);
}
else{ //The Dealer did not bust. The winner must be determined
winner = whoWins(playerHand, dealerHand);
if(winner == 1){ //Player Wins
playerChoice = JOptionPane.showConfirmDialog(null, "The dealer's hand: " +displayHand(dealerHand) + "\n \n Your hand: " + displayHand(playerHand) + "\n Congrautions!", "You Win!!!", JOptionPane.OK_CANCEL_OPTION);
if((playerChoice == JOptionPane.CLOSED_OPTION) || (playerChoice == JOptionPane.CANCEL_OPTION))
System.exit(0);
}
else{ //Player Loses
playerChoice = JOptionPane.showConfirmDialog(null, "The dealer's hand: " +displayHand(dealerHand) + "\n \n Your hand: " + displayHand(playerHand) + "\n Better luck next time!", "You lose!!!", JOptionPane.OK_CANCEL_OPTION);
if((playerChoice == JOptionPane.CLOSED_OPTION) || (playerChoice == JOptionPane.CANCEL_OPTION))
System.exit(0);
}
}
}
}while(true);
}
} | rexzhang123/Blackjack | Card.java | 3,099 | //Assume one of the suits from {"spades", "clubs", "hearts","diamonds"} will be passed in, not some random string | line_comment | en | false |
127481_6 |
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* This class represents a single movie.
* @author alchambers
*/
public class Movie {
private int year;
private int movieId;
private String title;
private Map<Integer, Integer> ratings;
/**
* Constructs a new movie with the given id
* @param theId Movie id
*/
public Movie(int theId){
year = 0;
movieId = theId;
title = "";
ratings = new HashMap<>();
}
/**
* Constructs a new movie with the given information
* @param theId Movie id
* @param theYear Movie year
* @param theTitle Movie title
*/
public Movie(int theId, int theYear, String theTitle){
year = theYear;
movieId = theId;
title = theTitle;
ratings = new HashMap<>();
}
/**
* Records a rating for the movie
* @param userId The id of the user rating the movie
* @param rating The rating given by the uesr
*/
public void addRating(int userId, int rating){
if(userId < 0 || rating < 0){
throw new AssertionError("Inputs must be positive.");
}
ratings.put(userId, rating);
}
/**
* Checks if the user has rated the movie
* @param userId The id of the user
* @return true if the user rated the movie, false otherwise
*/
public boolean rated(int userId){
return ratings.containsKey(userId);
}
/**
* Returns a user's rating of the movie
* @param userId The id of the user
* @return The user's rating or -1 if the user has not rated the movie
*/
public int getRating(int userId){
Integer rating = ratings.get(userId);
if(rating == null){
return -1;
}
return rating;
}
/**
* Returns the number of ratings for the movie
* @return The number of user's who have rated the movie
*/
public int numRatings(){
return ratings.size();
}
/**
* Returns a map view of the ratings
* @return A map from the rating to the frequency of that rating
*/
public Map<Integer, Integer> getRatings(){
return ratings;
}
/**
* Set the year of the movie
* @param year The year the movie was released
*/
public void setYear(int year){
this.year = year;
}
/**
* Set the title of the movie
* @param title The title of the movie
*/
public void setTitle(String title){
this.title = title;
}
/**
* Returns the year of the movie
* @return The year the movie was released
*/
public int getYear(){
return year;
}
/**
* Returns the movie id
* @return The movie id
*/
public int getMovieId(){
return movieId;
}
/**
* Returns the movie title
* @return The movie title
*/
public String getTitle(){
return title;
}
/**
* Returns a string representation of the users and ratings for the movie
* @return A string representation of the uesrs and ratings for the movie
*/
public String toString(){
String str = "("+ movieId + ") " + title + "\n";
for( Map.Entry<Integer, Integer> entry : ratings.entrySet()){
int userId = entry.getKey();
int rating = entry.getValue();
str += "\tuser=" + userId + " rating=" + rating + "\n";
}
return str;
}
/**
* Determines if two movies are equivalent
* @param other An object to compare against
* @return true if this movie and the other movie are the same, false otherwise
*/
@Override
public boolean equals(Object other){
if(other == this){
return true;
}
if(!(other instanceof Movie)){
return false;
}
Movie m = (Movie) other;
return movieId == m.movieId;
}
/**
* Returns a hashcode for the movie
* @return A hashcode for the movie
*/
@Override
public int hashCode(){
return Objects.hash(movieId);
}
}
| e-carlin/Netflix_Analyzer | src/Movie.java | 963 | /**
* Returns the number of ratings for the movie
* @return The number of user's who have rated the movie
*/ | block_comment | en | true |
127683_3 | class Cons extends Node {
private Node car;
private Node cdr;
private Special form;
// parseList() `parses' special forms, constructs an appropriate
// object of a subclass of Special, and stores a pointer to that
// object in variable form. It would be possible to fully parse
// special forms at this point. Since this causes complications
// when using (incorrect) programs as data, it is easiest to let
// parseList only look at the car for selecting the appropriate
// object from the Special hierarchy and to leave the rest of
// parsing up to the interpreter.
void parseList() { }
// TODO: Add any helper functions for parseList as appropriate.
public Cons(Node a, Node d) {
car = a;
cdr = d;
parseList();
}
void print(int n) {
form.print(this, n, false);
}
void print(int n, boolean p) {
form.print(this, n, p);
}
}
| cleger35/scint | Cons.java | 232 | // special forms at this point. Since this causes complications | line_comment | en | true |
128022_1 | public class Smith {
public static void printSmith(int t1, int t2) {
for (int i = t1; i < t2; i++) {
if (!JavaMathTrain.isPrime(i) &&
JavaMathTrain.sumEach(i) == JavaMathTrain.sumSmith(i)) { // 스미스
System.out.printf("%d는 스미스 수", i);
JavaMathTrain.printPrimeDivide2(i);
}
}
}
public static void main(String[] args) {
// 10000~20000 사이의 스미스 수
printSmith(10000, 20000);
}
}
| jiho-96/Train-Java | Smith.java | 167 | // 10000~20000 사이의 스미스 수 | line_comment | en | true |
128425_0 | import java.util.Scanner;
/**
* Problema 176-Campo de minas
* @author retos_killer
*/
public class p176 {
public static int buscarMinas(char[][] m, int i, int j) {
int[] posF = {1, -1, 0, 0, 1, -1, -1, 1};
int[] posC = {0, 0, 1, -1, 1, -1, 1, -1};
int f, c, minas = 0;
for (int k = 0; k < 8; k++) {
f = i + posF[k];
c = j + posC[k];
if (safe(f, c) && m[f][c] == '*') {
minas++;
}
}
return minas;
}
public static boolean safe(int i, int j) {
if (i >= 0 && i < r && j >= 0 && j < c) {
return true;
}
return false;
}
public static int r;
public static int c;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
char[][] m;
String linea;
while (true) {
c = s.nextInt();
r = s.nextInt();
if (r == 0 || c == 0) System.exit(0);
s.nextLine();
m = new char[r][c];
for (int i = 0; i < r; i++) {
linea = s.nextLine();
for (int j = 0; j < c; j++) {
m[i][j] = linea.charAt(j);
}
}
int minas = 0;
int cantidad;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (m[i][j] == '-') {
cantidad = buscarMinas(m, i, j);
if (cantidad >= 6) minas++;
}
}
}
System.out.println(minas);
}
}
}
| MiYazJE/Acepta-el-reto | p176.java | 517 | /**
* Problema 176-Campo de minas
* @author retos_killer
*/ | block_comment | en | true |
128712_8 | package Survey;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
public class Survey implements Serializable {
private static final long serialVersionUID = 6529685098267757690L;
protected String currentFile;
protected final String SURVEYFOLDER = "surveyFiles";
protected final String TAKENSURVEYFOLDER = "takenSurveyFiles";
protected ArrayList<Question> questions = new ArrayList<Question>();
protected Output out = new ConsoleOutput();
protected HashMap<Question, Integer> sameResp = new HashMap<>();
//this will used mainly when there is a user input to do all the error checking
protected ConsoleInput input = new ConsoleInput();
/*used this to store object and load objects with ease*/
public Survey(String currentFile, ArrayList<Question> questions) {
this.questions = questions;
this.currentFile = currentFile;
this.createDir();
}
//Empty Constructer
public Survey() {this.createDir();}
public void setQuestion(ArrayList<Question> questions) {
this.questions = questions;
}
public ArrayList<Question> getQuestion() {return this.questions;}
public String getCurrentFile() {return this.currentFile;}
public String returnPath(String dir, String fileName) {
return dir + File.separator + fileName;
}
//creates Directories surveyfolder and takensurveyfolder
private void createDir() {
try {
File dir = new File(this.SURVEYFOLDER);
if (!dir.exists()) {
boolean flag = dir.mkdirs();
}
dir = new File(this.TAKENSURVEYFOLDER);
if(!dir.exists()) {
boolean flag = dir.mkdirs();
}
}catch (Exception e) {
e.printStackTrace();
}
}
//list the files in the directory
public File[] listFiles(String directory) {
try {
File folder = new File(directory);
return folder.listFiles();
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
//checks if the file exist in the directory
public boolean isExist(String directory) {
try {
File file = new File(returnPath(directory, this.currentFile));
return file.exists();
}catch (Exception e) {
e.printStackTrace();
}
return false;
}
//displays all the questions in the survey
public void display() {
for(int i =0; i < this.questions.size();i++) {
out.print("Question " +(i+1) + ". " );
this.questions.get(i).display();
}
}
//displays all the questions and ask the user which question to modify
public int modify() {
int num;
this.display();
do {
num = input.checkNumChoice("Which question number would you like to modify?") - 1;
if (num >= this.questions.size()) {
out.print("Please select in range");
continue;
}
this.questions.get(num).modify();
break;
}while(true);
return num;
}
//simply ask the user for the answer to the related questions and assign it and stores it in response class
// response class would have saved all the responses so it mostly used for tabulation purposes
public void Take(Responses r1) {
for(int i =0; i < this.questions.size();i++) {
out.print("Question " + (i + 1) + ". ");
this.questions.get(i).userResponse();
out.print("");
}
try {
for (Question question : this.questions)
r1.addHashPrompt(question.prompt, question);
}catch (Exception e){
e.printStackTrace();
}
}
//tabulates all the responses
public void Tabulate(Responses r1) {
//first it prints out all the responses per question
for(Map.Entry<String, ArrayList<Question>> entry : r1.storedResp.entrySet()) {
boolean flag = true;
int numSameValue =0;
for(Question q: entry.getValue()) {
numSameValue++;
if(flag) {
q.display();
out.print("Responses:");
flag = false;
}
if(q.type.equals("Matching")) {
char ch = 'A';
for (String s : q.saveResp) {
out.print(ch + ") " + s);
ch++;
}
}else {
for (String s : q.saveResp) {
out.print(s);
}
}
}
out.print("");
}
//counts the same response it and maps it to the question
ArrayList<Integer> savedIndex = new ArrayList<>();
for(Map.Entry<String, ArrayList<Question>> entry: r1.storedResp.entrySet()) {
ArrayList<Question> q = entry.getValue();
Question temp = null;
int count =1;
if(q.size()==1) {
sameResp.put(q.get(0),1);
}else {
for(int i=0; i < q.size(); i++) {
if(savedIndex.contains(i)) {
continue;
}
if(i==q.size()-1) {
if(!savedIndex.contains(i))
sameResp.put(q.get(i),1);
break;
}
for(int j=i+1; j < q.size(); j++) {
temp = q.get(i);
if(!savedIndex.contains(j)) {
if (isRespSame(q.get(i), q.get(j))) {
savedIndex.add(j);
count++;
}
}
}
sameResp.put(temp,count);
count=1;
}
}
savedIndex.clear();
}
out.print("Tabulation");
//used compareTo method in question classes to order it in alphabetical order
HashMap<Question, Integer> result = sameResp.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
String type = null;
String prompt = null;
//prints out the result, which are number of same responses per questions
for(Map.Entry<Question, Integer> entry: result.entrySet()) {
Question key = entry.getKey();
if(!key.type.equals(type)){
key.display();
type = key.type;
prompt = key.prompt;
}else {
if(!key.prompt.equals(prompt)) {
key.display();
type = key.type;
prompt = key.prompt;
}
}
out.print("Number of same Response: " + Integer.toString(entry.getValue()));
for(String s: key.saveResp) {
out.print(s);
}
out.print("");
}
result.clear();
sameResp.clear();
}
//used to count if the response is the same for tabulation
public boolean isRespSame(Question q1, Question q2) {
for(String s: q1.saveResp) {
if(!q2.saveResp.contains(s)) {
return false;
}
}
return true;
}
//load the object by passing all the saved non taken survey files
public Object Load(String directory) {
int fileChoice;
int count = 1;
File[] listFiles = this.listFiles(directory);
if(listFiles==null) {
return null;
}
if(listFiles.length== 0) {
return null;
}
for(File f: listFiles) {
if(f.isFile()) {
out.print(count + ". "+ f.getName());
count++;
}
}
do {
fileChoice = input.checkNumChoice("Which File: ")-1;
if(fileChoice>=listFiles.length)
out.print("Please choose in range");
else
break;
}while (true);
//this will load by using the file user has selected
try {
File file = new File(String.valueOf(listFiles[fileChoice]));
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
return ois.readObject();
}catch (Exception e) {
out.print("Error Loading the file." + e);
}
return null;
}
//save the file by using this.currentfile
public void Save(Object obj,String directory) {
try {
File file = new File(returnPath(directory,this.currentFile));
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(obj);
oos.close();
}catch(Exception e) {
out.print("Error Saving file" + e);
}
}
}
| sarthak263/Projects | Survey/Survey.java | 2,048 | //simply ask the user for the answer to the related questions and assign it and stores it in response class
| line_comment | en | false |
129194_0 | /*
* Homework #5 Morgan Kinne (mck7py)
*/
import java.util.ArrayList;
import java.util.Set;
import java.util.TreeSet;
public class User implements Comparable<User>{
private String userName;
private ArrayList<Meme> memesCreated = new ArrayList<>();
Set<Meme> memesViewed = new TreeSet<>(); // make sure all variables are in TreeSet
public User(String userName) {
this.userName = userName;
}
public User() {}
@Override
public String toString() {
return userName + " has rated (" + memesViewed.size() + ") memes, (" + calculateReputation() + ")";
}
@Override
public boolean equals(Object obj) {
if (obj instanceof User) {
User user = (User) obj;
if(this.getUserName().equals(user.getUserName())) {
return true;
}
}
return false;
}
public void rateMeme(Meme meme, int rating) {
if(!(memesCreated.contains(meme))) {
memesViewed.add(meme);
meme.addRating(new Rating (this, rating));
}
}
public boolean rateNextMemeFromFeed(Feed feed, int ratingScore) {
Meme meme = feed.getNewMeme(this);
if (meme != null) {
rateMeme (meme, ratingScore);
return true;
}
else {
return false;
}
}
public Meme createMeme(BackgroundImage bg, String caption) {
Meme meme = new Meme (bg, caption, this);
memesCreated.add(meme);
return meme;
}
public boolean deleteMeme(Meme meme) {
if (this.memesCreated.contains(meme) && meme.getShared() == false) {
memesCreated.remove(meme);
return true;
}
else {
return false;
}
}
public void shareMeme(Meme meme, Feed feed) {
if (meme != null) {
meme.setShared(true);
feed.getMemes().add(meme);
}
}
public double calculateReputation() {
double rep = 0.0;
if (memesCreated.size() == 0 && memesViewed.size() == 0) {
return 0.0;
}
else if (memesCreated.size() == 0) {
return 0.0;
}
else {
for (int i = 0; i < memesCreated.size(); i++) {
rep += memesCreated.get(i).calculateOverallRating();
}
return (rep/memesCreated.size());
}
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public ArrayList<Meme> getMemesCreated() {
return memesCreated;
}
public void setMemesCreated(ArrayList<Meme> memesCreated) {
this.memesCreated = memesCreated;
}
public ArrayList<Meme> getMemesViewed() {
return (ArrayList<Meme>) memesViewed;
}
public void setMemesViewed(Set<Meme> memesViewed) {
this.memesViewed = memesViewed;
}
@Override
public int compareTo(User o) {
if (!this.getUserName().equals(o.getUserName())) {
return this.getUserName().compareTo(o.getUserName());
}
else if(this.getMemesCreated().size()!=o.getMemesCreated().size()) {
if (this.getMemesCreated().size() < o.getMemesCreated().size()) {
return 1;
}
else if (this.getMemesCreated().size() > o.getMemesCreated().size()) {
return -1;
}
}
return 0;
}
} | morganckinne/CS-2110 | User.java | 921 | /*
* Homework #5 Morgan Kinne (mck7py)
*/ | block_comment | en | true |
129405_3 | package finalProject;
/**
* pair
* generates a pair: x, y
*
* @author Chinmay Lalgudi, Rithwik Kerur, Pranav Kakhandiki
* @version May 27, 2019
* @author Period: 5
* @author Assignment: finalProject
*
* @author Sources:
*/
public class Pair<X,Y>
{
private X x;
private Y y;
/**
* creates a pair with parameters x and y
* @param x
* @param y
*/
public Pair(X x, Y y){
this.x = x;
this.y = y;
}
/**
*
* returns x
* @return x
*/
public X getX(){ return x; }
/**
*
* returns y
* @return y
*/
public Y getY(){ return y; }
/**
*
* sets x to parameter
* @param x
*/
public void setX(X x){ this.x = x; }
/**
*
* sets y to parameter
* @param y
*/
public void setY(Y y){ this.y = y; }
}
| pranavkakhandiki/Brawl-Stars-Clone | Pair.java | 287 | /**
*
* returns y
* @return y
*/ | block_comment | en | true |
129597_1 | package com.sarthak.java.b;
public class Human {
public static void main(String[] args) {
System.out.println("hello world");
}
int birthYear;
String name;
long salary;
boolean married;
static int population;
static void info(){
//System.out.println(this.birthYear);
//we cannot use this keyword inside static function because it is references to an object
}
public Human(int year,String name,int salary,boolean married){//this is a constructor
this.birthYear=year;
this.name=name;
this.salary=salary;
this.married=married;
Human.population+=1;
}
}
| SarthakJaiswal001/javaOOps | b/Human.java | 170 | //we cannot use this keyword inside static function because it is references to an object
| line_comment | en | false |
129826_0 | package floobits.common;
import java.net.*;
public class FlooUrl {
public String proto;
public String host;
public String owner;
public String workspace;
public Integer port;
public boolean secure;
public FlooUrl(String url) throws MalformedURLException {
URL u = new URL(url);
String path = u.getPath();
String[] parts = path.split("/");
this.host = u.getHost();
this.owner = parts[1];
this.workspace = parts[2];
if (this.owner.equals("r")) {
this.owner = parts[2];
this.workspace = parts[3];
}
this.port = u.getPort();
this.proto = u.getProtocol();
this.secure = !this.proto.equals("http");
if (this.port < 0) {
if (this.secure) {
this.port = 3448;
} else {
this.port = 3148;
}
}
}
public FlooUrl(String host, String owner, String workspace, Integer port, boolean secure) {
this.host = host;
this.owner = owner;
this.workspace = workspace;
this.port = port < 0 ? 3448 : port;
this.secure = secure;
this.proto = secure ? "https" : "http";
}
public String toString() {
String port = "";
if (this.secure) {
proto = "https";
if (this.port != 3448) {
port = String.format(":%s", this.port);
}
} else {
proto = "http";
if (this.port != 3148) {
port = String.format(":%s", this.port);
}
}
return String.format("%s://%s%s/%s/%s", proto, this.host, port, this.owner, this.workspace);
}
}
| Floobits/eclipse | src/floobits/common/FlooUrl.java | 457 | //%s%s/%s/%s", proto, this.host, port, this.owner, this.workspace); | line_comment | en | true |
130114_0 | // 2870. Minimum Number of Operations to Make Array Empty
class Solution {
public int minOperations(int[] nums) {
HashMap<Integer,Integer> map=new HashMap<>();
for(int i : nums){
if(map.containsKey(i)) map.put(i,map.get(i)+1);
else map.put(i,1);
}
List<Integer> ll=new ArrayList<>();
for(int i : map.keySet()){
ll.add(map.get(i));
}
int ans=0;
for(int i=0;i<ll.size();i++){
if(ll.get(i) == 1 ) return -1;
while(ll.get(i)>1){
ans+=1;
if(ll.get(i) % 3 ==0) ll.set(i,ll.get(i)-3);
else ll.set(i,ll.get(i)-2);
}
}
return ans;
}
} | YatinDora81/Leetcode_Ques | 2870.java | 231 | // 2870. Minimum Number of Operations to Make Array Empty | line_comment | en | false |
130168_0 | import greenfoot.*;
/**
* MyKara is a subclass of Kara. Therefore, it inherits all methods of Kara: <p>
*
* <i>MyKara ist eine Unterklasse von Kara. Sie erbt damit alle Methoden der Klasse Kara:</i> <p>
*
* Actions: move(), turnLeft(), turnRight(), putLeaf(), removeLeaf() <b>
* Sensors: onLeaf(), treeFront(), treeLeft(), treeRight(), mushroomFront()
*/
public class MyKara extends Kara
{
/**
* In the 'act()' method you can write your program for Kara <br>
* <i>In der Methode 'act()' koennen die Befehle fuer Kara programmiert werden</i>
*/
public void act()
{
move();
move();
move();
turnRight();
}
}
| htw-imi-info1/kara-scenario1 | MyKara.java | 214 | /**
* MyKara is a subclass of Kara. Therefore, it inherits all methods of Kara: <p>
*
* <i>MyKara ist eine Unterklasse von Kara. Sie erbt damit alle Methoden der Klasse Kara:</i> <p>
*
* Actions: move(), turnLeft(), turnRight(), putLeaf(), removeLeaf() <b>
* Sensors: onLeaf(), treeFront(), treeLeft(), treeRight(), mushroomFront()
*/ | block_comment | en | true |
130210_9 | package bomberman;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This is the engine of the Bomberman-game, where everything is initialised. It calls to Menu, which is the initial gameframe,
* when a game is started it instantiates a Floor and a BombermanFrame. It is also home to the timer-methods that create the
* time-aspects of the game, more specifically, the tick-method that can be viewed as the main loop. With ReadWithScanner and
* WriteToFile Engine manages settings-parameters and highscores. This class is never instantiated, which is why it only has
* static methods.
*/
public final class Engine
{
// LOGGER is static because there should only be one logger per class.
private static final Logger LOGGER = Logger.getLogger(Engine.class.getName() );
// Constants are static by definition.
//Default values if file-reading fails.
private static final int TIME_STEP = 30;
private static final int NANO_SECONDS_IN_SECOND = 1000000000;
// The following fields are static since they they are general settings or properties for the game.
private static int width = 5;
private static int height = 5;
private static int nrOfEnemies = 1;
private static long startTime = 0L;
private static long elapsedTime = 0L;
private static Timer clockTimer = null;
private Engine() {}
// Main methods are static by definition.
public static void main(String[] args) {
// Inspector complains on the result of Menu not being used, as well as the main-method of Engine,
// but a frame is opened within it, and that instance is disposed when the user starts a new game.
// It is unnecessary to store it.
new Menu();
}
// This method is static because it is the "general" instantiation of the game, and is not
// belonging to an Engine-object. Engine is never instantiated.
public static void startGame() {
readSettings();
Floor floor = new Floor(width, height, nrOfEnemies);
BombermanFrame frame = new BombermanFrame("Bomberman", floor);
startTime = System.nanoTime();
floor.addFloorListener(frame.getBombermanComponent());
Action doOneStep = new AbstractAction()
{
public void actionPerformed(ActionEvent e) {
tick(frame, floor);
}
};
clockTimer = new Timer(TIME_STEP, doOneStep);
clockTimer.setCoalesce(true);
clockTimer.start();
}
// Engine is never instantiated, therefore this method needs to be static.
private static void readSettings() {
Parser parser = new Parser("settings.txt");
try {
parser.processLineByLine();
//Set the values read from file.
width = parser.getWidth();
height = parser.getHeight();
nrOfEnemies = parser.getNrOfEnemies();
} catch (IOException ioe) {
JOptionPane.showMessageDialog(null, "Trouble reading from settings file: " + ioe.getMessage() +
". Creating new file with standard settings.");
writeNewSettings();
}
}
// Engine is never instantiated, therefore this method needs to be static.
private static void gameOver(BombermanFrame frame, Floor floor) {
long endTime = System.nanoTime();
elapsedTime = (endTime - startTime) / NANO_SECONDS_IN_SECOND;
clockTimer.stop();
if (floor.getEnemyList().isEmpty()) {
if (getRank() > 10) {
JOptionPane.showMessageDialog(null, "You beat the game! But you didn't make the highscorelist. :(");
} else {
String name =
JOptionPane.showInputDialog("You beat the game and made the highscorelist!\nPlease input your handle");
writeHighscore(name, (int) elapsedTime);
}
} else {
JOptionPane.showMessageDialog(null, "Game over!");
UIManager.put("JOptionPane.okButtonMnemonic", "O"); // for Setting 'O' as mnemonic
}
frame.dispose();
if (askUser("Do you want to play again?")) {
startGame();
}
}
// Engine is never instantiated, therefore this method needs to be static.
private static void writeHighscore(String name, int newHighscore) {
ArrayList<String> highscoreList = HighscoreFrame.readHighscore();
highscoreList.remove(highscoreList.size() - 1);
String newScore = name + ":" + Integer.toString(newHighscore);
highscoreList.add(newScore);
highscoreList = HighscoreFrame.sortHighscore(highscoreList);
WriteToFile.writeToFile(highscoreList, "highscore.txt");
}
// Engine is never instantiated, therefore this method needs to be static.
private static void writeNewSettings() {
Collection<String> settingsList = new ArrayList<>();
String strWidth = "width=" + Integer.toString(width);
settingsList.add(strWidth);
String strHeight = "height=" + Integer.toString(height);
settingsList.add(strHeight);
String strNrOfEnemies = "nrOfEnemies=" + Integer.toString(nrOfEnemies);
settingsList.add(strNrOfEnemies);
WriteToFile.writeToFile(settingsList, "settings.txt");
}
// Engine is never instantiated, therefore this method needs to be static.
private static int getRank() {
try (BufferedReader br = new BufferedReader(new FileReader("highscore.txt"))) {
int positionCounter = 0;
while (br.readLine() != null && positionCounter < 10) {
positionCounter++;
int listedScore = Integer.parseInt(br.readLine().split(":")[1]);
if (elapsedTime < listedScore) {
return positionCounter;
}
}
} catch (IOException ioe) {
LOGGER.log(Level.FINE, "Trouble reading from the file: " + ioe.getMessage() );
System.out.println("Trouble reading from the file: " + ioe.getMessage());
}
return 10 + 1;
}
// Engine is never instantiated, therefore this method needs to be static.
private static boolean askUser(String question) {
return JOptionPane.showConfirmDialog(null, question, "", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION;
}
// Engine is never instantiated, therefore this method needs to be static.
private static void tick(BombermanFrame frame, Floor floor) {
if (floor.getIsGameOver()) {
gameOver(frame, floor);
} else {
floor.moveEnemies();
floor.bombCountdown();
floor.explosionHandler();
floor.characterInExplosion();
floor.notifyListeners();
}
}
}
| perfall/Bomberman | Engine.java | 1,674 | // This method is static because it is the "general" instantiation of the game, and is not | line_comment | en | false |
130484_0 | package hgm;
import java.util.List;
import java.util.Set;
/**
* Created by Hadi Afshar.
* Date: 19/09/13
* Time: 4:55 PM
*/
public interface IQuery {
Set<InstantiatedVariable> getEvidence();
Set<Variable> getNonInstantiatedEvidenceVariables();
List<Variable> getQueries();
}
| ssanner/xadd-inference | src/hgm/IQuery.java | 101 | /**
* Created by Hadi Afshar.
* Date: 19/09/13
* Time: 4:55 PM
*/ | block_comment | en | true |
130605_5 | /**
* @author Pushkar Taday
*/
/**
* This class represents a station where passengers embark the train from
*/
public class Station {
private static int passengerCount=1;
private int totalFirstClassPassengers=0;
private int totalSecondClassPassengers=0;
private PassengerQueue firstClass;
private PassengerQueue secondClass;
private BooleanSource firstArrival;
private BooleanSource secondArrival;
public int firstClassPeopleServed=0;
public int secondClassPeopleServed=0;
public double firstClassTotalWait=0.0;
public double secondClassTotalWait=0.0;
/**
* This is a parameterized constructor for this class which gets instantiated with the appropriate parameters
* @param firstArrivalProbability
* The probability of passengers to arrive in the first class
* @param secondArrivalProbability
* The probability of passengers to arrive in the second class
*/
Station(double firstArrivalProbability,double secondArrivalProbability)
{
firstArrival=new BooleanSource(firstArrivalProbability);
secondArrival=new BooleanSource(secondArrivalProbability);
firstClass=new PassengerQueue();
secondClass=new PassengerQueue();
}
/**
* This method simulates the scenario at the station for each min.
*/
public void simulateTimestep()
{
if(firstArrival.occurs()&&LIRRSimulator.i<=LIRRSimulator.lastArrivalTime)
{
System.out.println("First class passenger "+passengerCount+" ID arrives");
Passenger passenger=new Passenger(passengerCount,LIRRSimulator.i,true);
firstClass.enqueue(passenger);
passengerCount++;
totalFirstClassPassengers++;
}
else
{
System.out.println("No first class passenger arrives");
}
if(secondArrival.occurs()&&LIRRSimulator.i<=LIRRSimulator.lastArrivalTime)
{
System.out.println("Second class passenger "+passengerCount+" ID arrives");
Passenger passenger=new Passenger(passengerCount,LIRRSimulator.i,false);
secondClass.enqueue(passenger);
passengerCount++;
totalSecondClassPassengers++;
}
else
{
System.out.println("No second class passenger arrives");
}
System.out.println("Queues:");
System.out.print("First "+firstClass);
System.out.println();
System.out.println("Second "+secondClass);
System.out.println();
}
/**
* This is an accessor method for the total numbers of passengers which travelled through the trains during entire simulation.
* @return
* total number of passengers
*/
public static int getPassengerCount() {
return passengerCount;
}
/**
* This is an accessor method for the total numbers of passengers which travelled through the first class of the trains during entire simulation.
* @return
* total number of first class passengers
*/
public int getTotalFirstClassPassengers() {
return firstClass.getCount();
}
/**
* This is an accessor method for the total numbers of passengers which travelled through the second class of the trains during entire simulation.
* @return
* total number of second class passengers
*/
public int getTotalSecondClassPassengers() {
return secondClass.getCount();
}
/**
* This is an accessor method for the queue of passengers in the first class
* @return
* first class passengers queue
*/
public PassengerQueue getFirstClass() {
return firstClass;
}
/**
* This is an accessor method for the queue of passengers in the second class
* @return
* second class passengers queue
*/
public PassengerQueue getSecondClass() {
return secondClass;
}
}
| ptaday/LIRR-Simulator | Station.java | 859 | /**
* This is an accessor method for the total numbers of passengers which travelled through the first class of the trains during entire simulation.
* @return
* total number of first class passengers
*/ | block_comment | en | false |
130952_7 | public class Person {
private String name;
private int age;
private String favoriteColor;
/**
* Person constructor.
*
* @param name the name
* @param age the age
* @param favoriteColor the favorite color
*/
public Person(String name, int age, String favoriteColor) {
this.name = name;
this.age = age;
this.favoriteColor = favoriteColor;
}
/**
* Sets the name
*
* @param name the name
*/
public void setName(String name) {
this.name = name;
}
/**
* Sets the age
*
* @param age the age
*/
public void setAge(int age) {
this.age = age;
}
/**
* Sets the favorite color
*
* @param favoriteColor the favorite color
*/
public void setFavoriteColor(String favoriteColor) {
this.favoriteColor = favoriteColor;
}
/**
* Gets the name of the Person
*
* @return the name
*/
public String getName() {
return this.name;
}
/**
* Gets the age of the Person
*
* @return the age
*/
public int getAge() {
return this.age;
}
/**
* Gets the favorite color of the Person
*
* @return the favorite color
*/
public String getFavoriteColor() {
return this.favoriteColor;
}
/**
* Produces a string representation of the Person, e.g. Bob, 30 (favorite color: blue)
*
* @return a string representation of the Person
*/
public String toString() {
return this.name + ", " + this.age + " (favorite color: " + this.favoriteColor + ")";
}
}
| Endeared/CSE174 | Person.java | 409 | /**
* Produces a string representation of the Person, e.g. Bob, 30 (favorite color: blue)
*
* @return a string representation of the Person
*/ | block_comment | en | false |
130982_0 | package com.evhacks.qrmenu;
import java.util.ArrayList;
/**
* Created by rohan on 2/7/2015.
*/
public class Restaurant {
String name;
boolean isFavorite = false;
ArrayList<Item> menu = new ArrayList<Item>();
public Restaurant(String n, ArrayList<Item> m){
name = n;
menu = m;
}
public String toString(){
String a = name + "/n";
for(int i = 0 ; i < menu.size(); i++){
a+=menu.get(i).toString() + "/n";
}
return a;
}
public ArrayList<Item> getMenu(){
return menu;
}
public String getName(){
return name;
}
public boolean getFavorite(){
return isFavorite;
}
public void setFavorite(){
isFavorite = !isFavorite;
}
}
| sauprankul/foodies | Restaurant.java | 209 | /**
* Created by rohan on 2/7/2015.
*/ | block_comment | en | true |
131223_0 | package testAbstact;
//Секое плаќање преку картичка има некои подобности. Имено државата сакајќи
//да го поттикне користењето на картичките, нуди поволни услови за плаќање.
//Да се моделира основна абстрактна класа Kartichka како и класи Master и Maestro кои ја
//наследуваат. Една картичка е опишана со својот идентификациски број, како и
//со салдото на сметката која ја претставува.
//При плаќање со маестро картичка, секоја сума се плаќа со попуст од 5% за
//СИТЕ корисници на маестро картичка. Овој процент е фиксен и не смее да се
//менува!
//При плаќање со мастер картичка, ако лимитот на картичката е над 6000 денари
//тогаш попустот е 10%, наместо стандардните 3% за картички со лимит под 6000
//денари.
//Попустот од 10% е ист за сите корисници, но тој може да биде променет од
//страна на Народна Банка.
// Example usage
class NoMoneyException extends Exception{
public NoMoneyException(double amount, double saldo) {
super("Ne mozes da plates " + amount + "den. oti imas na saldoto samo " + saldo +"den.");
}
}
abstract class Karticka{
private String id;
private double saldo;
public Karticka(String id, double saldo) {
this.id = id;
this.saldo = saldo;
}
public String getId() {
return id;
}
public double getSaldo() {
return saldo;
}
public void setSaldo(double saldo) {
this.saldo = saldo;
}
public abstract double platiSoKartichka(double paymentAmount) throws NoMoneyException;
}
class Maestro extends Karticka{
private static final double MAESTROPOPUST = 5.0;
public Maestro(String id, double saldo) {
super(id, saldo);
}
@Override
public double platiSoKartichka(double paymentAmount) throws NoMoneyException {
double popust = 1.0 - (MAESTROPOPUST/100);
double cenaSoPopust = paymentAmount * popust;
if(getSaldo() < cenaSoPopust){
throw new NoMoneyException(cenaSoPopust,getSaldo());
}
setSaldo(getSaldo() - cenaSoPopust);
return cenaSoPopust;
}
@Override
public String toString() {
return "TIP: MESTRO CARD\nID: " + getId() + "\nSALDO: " + getSaldo();
}
}
class Master extends Karticka{
private double limit;
private static int POPUSTNADLIMIT = 10;
private static final int POPUSTPODLIMIT = 3;
public Master(String id, double saldo, double limit) {
super(id, saldo);
this.limit = limit;
}
public double getLimit() {
return limit;
}
@Override
public double platiSoKartichka(double paymentAmount) throws NoMoneyException {
double popust = 1.0 - (POPUSTPODLIMIT/100.0);
double cenaSoPopust = paymentAmount * popust;
if(getSaldo() < cenaSoPopust){
throw new NoMoneyException(cenaSoPopust,getSaldo());
}
if(limit >= 6000){
popust = 1.0 - (POPUSTNADLIMIT/100.0);
cenaSoPopust = paymentAmount * popust;
}
setSaldo(getSaldo() - cenaSoPopust);
return cenaSoPopust;
}
public static void setPOPUSTNADLIMIT(int POPUSTNADLIMIT) {
Master.POPUSTNADLIMIT = POPUSTNADLIMIT;
}
@Override
public String toString() {
return "TIP: MASTER CARD\nID: " + getId() + "\nSALDO: " + getSaldo() + "\nLIMIT: " + getLimit();
}
}
public class Main {
public static void main(String[] args) {
// Creating instances of Master and Maestro cards
Master masterCard = new Master("123456789", 7000,6100);
Maestro maestroCard = new Maestro("987654321", 5000);
// Making payments
double paymentAmount = 1000;
double masterCardPayment = 0;
double maestroCardPayment = 0;
try {
masterCardPayment = masterCard.platiSoKartichka(paymentAmount);
System.out.println("MasterCard Payment: " + masterCardPayment);
System.out.println(masterCard);
System.out.println();
maestroCardPayment = maestroCard.platiSoKartichka(paymentAmount);
System.out.println("MaestroCard Payment: " + maestroCardPayment);
System.out.println(maestroCard);
} catch (NoMoneyException e) {
System.out.println(e.getMessage());
}
// Output the results
//900
//950
//
//6000
//4050
System.out.println();
Master.setPOPUSTNADLIMIT(5);
try {
masterCardPayment = masterCard.platiSoKartichka(1000);
System.out.println("MasterCard Payment with 5% discount: " + masterCardPayment);
System.out.println(masterCard);
} catch (NoMoneyException e) {
System.out.println(e.getMessage());
}
System.out.println();
//950
//Saldo: 5150
System.out.println();
Master masterCardUnderLimit = new Master("123456777", 4000,3000);
double masterCardUnderLimitPayment = 0;
try {
masterCardUnderLimitPayment = masterCardUnderLimit.platiSoKartichka(paymentAmount);
System.out.println("Master Card Under Limit Payment: " + masterCardUnderLimitPayment);
System.out.println(masterCardUnderLimit);
} catch (NoMoneyException e) {
System.out.println(e.getMessage());
}
// 970
// 3030
System.out.println();
double smetka = 7000;
//6,650
//-1,650
Maestro maestroCardWith5k = new Maestro("112233445",5000);
double maestroWith5kPayment = 0;
try {
maestroWith5kPayment = maestroCardWith5k.platiSoKartichka(smetka);
System.out.println("Maestro Card With 5k Payment: " + maestroWith5kPayment);
System.out.println(maestroCardWith5k);
} catch (NoMoneyException e) {
System.out.println(e.getMessage());
}
}
}
| GligorcoGligorov/OOP-M | Main.java | 1,972 | //Секое плаќање преку картичка има некои подобности. Имено државата сакајќи
| line_comment | en | true |
131317_0 | /*
* Solution to Project Euler problem 46
* By Nayuki Minase
*
* http://nayuki.eigenstate.org/page/project-euler-solutions
* https://github.com/nayuki/Project-Euler-solutions
*/
public final class p046 implements EulerSolution {
public static void main(String[] args) {
System.out.println(new p046().run());
}
public String run() {
for (int i = 2; ; i++) {
if (!satisfiesConjecture(i))
return Integer.toString(i);
}
}
private boolean satisfiesConjecture(int n) {
if (n % 2 == 0 || isPrime(n))
return true;
// Now n is an odd composite number
for (int i = 1; i * i * 2 <= n; i++) {
if (isPrime(n - i * i * 2))
return true;
}
return false;
}
private boolean[] isPrime = {};
private boolean isPrime(int n) {
if (n >= isPrime.length)
isPrime = Library.listPrimality(n * 2);
return isPrime[n];
}
}
| JoaoCalhau/CenasUni | BsC/PI/Project-Euler-solutions-master/Project-Euler-solutions-master/p046.java | 315 | /*
* Solution to Project Euler problem 46
* By Nayuki Minase
*
* http://nayuki.eigenstate.org/page/project-euler-solutions
* https://github.com/nayuki/Project-Euler-solutions
*/ | block_comment | en | true |
131339_1 | /*
* Copyright © 2016 Keith Packard <[email protected]>
*
* 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 3 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.
*/
/*
* This code uses ideas and algorithms from Dire Wolf, an amateur
* radio packet TNC which was written by John Langner, WB2OSZ. That
* project is also licensed under the GPL, either version 3 of the
* License or (at your option) any later version.
*/
package org.altusmetrum.aprslib_1;
public class AprsAgc {
float attack, decay;
float peak, valley;
public float sample(float in) {
if (in >= peak)
peak = in * attack + peak * (1.0f - attack);
else
peak = in * decay + peak * (1.0f - decay);
if (in <= valley)
valley = in * attack + valley * (1.0f - attack);
else
valley = in * decay + valley * (1.0f - decay);
if (peak <= valley)
return 0.0f;
return (in - 0.5f * (peak + valley)) / (peak - valley);
}
public AprsAgc(float attack, float decay) {
this.attack = attack;
this.decay = decay;
peak = 0.0f;
valley = 0.0f;
}
}
| keith-packard/aprslib | AprsAgc.java | 467 | /*
* This code uses ideas and algorithms from Dire Wolf, an amateur
* radio packet TNC which was written by John Langner, WB2OSZ. That
* project is also licensed under the GPL, either version 3 of the
* License or (at your option) any later version.
*/ | block_comment | en | true |
131598_0 | import java.util.Date;
import org.json.JSONException;
import org.json.JSONObject;
public final class bww
extends bwt
{
public String a;
private String b;
private String c;
private String d;
private int e;
private int f;
private String g;
private String h;
private Date i;
public bww(bus parambus, bva parambva, String paramString1, String paramString2, String paramString3, String paramString4, String paramString5, int paramInt1, int paramInt2)
{
super(bux.j, parambus, parambva, paramString1);
a = paramString2;
b = paramString3;
if (paramString4 == null) {
throw new RuntimeException("cardNumber should not be null. If it is, then you're probably trying to tokenize a card that's already been tokenized.");
}
c = paramString4;
d = paramString5;
e = paramInt1;
f = paramInt2;
}
public final String b()
{
JSONObject localJSONObject = new JSONObject();
localJSONObject.accumulate("payer_id", a);
localJSONObject.accumulate("cvv2", d);
localJSONObject.accumulate("expire_month", Integer.valueOf(e));
localJSONObject.accumulate("expire_year", Integer.valueOf(f));
localJSONObject.accumulate("number", c);
localJSONObject.accumulate("type", b);
return localJSONObject.toString();
}
public final void c()
{
JSONObject localJSONObject = n();
try
{
g = localJSONObject.getString("id");
String str = localJSONObject.getString("number");
if ((h == null) || (!h.endsWith(str.substring(str.length() - 4)))) {
h = str;
}
i = bwf.a(localJSONObject.getString("valid_until"));
return;
}
catch (JSONException localJSONException)
{
d();
}
}
public final void d()
{
b(n());
}
public final String e()
{
return "{\"id\":\"CARD-50Y58962PH1899901KFFBSDA\",\"valid_until\":\"2016-03-19T00:00:00.000Z\",\"state\":\"ok\",\"type\":\"visa\",\"number\":\"xxxxxxxxxxxx" + c.substring(c.length() - 4) + "\",\"expire_month\":\"" + e + "\",\"expire_year\":\"" + f + "\",\"links\":[{\"href\":\"https://api.sandbox.paypal.com/v1/vault/credit-card/CARD-50Y58962PH1899901KFFBSDA\",\"rel\":\"self\",\"method\":\"GET\"}]}";
}
public final String u()
{
return g;
}
public final String v()
{
return h;
}
public final Date w()
{
return i;
}
public final String x()
{
return b;
}
public final int y()
{
return e;
}
public final int z()
{
return f;
}
}
/* Location:
* Qualified Name: bww
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | reverseengineeringer/com.ubercab | src/bww.java | 784 | //api.sandbox.paypal.com/v1/vault/credit-card/CARD-50Y58962PH1899901KFFBSDA\",\"rel\":\"self\",\"method\":\"GET\"}]}"; | line_comment | en | true |
132124_1 | import java.time.*;
public class blood {
public String bloodGroup;
public String ironLevel;
public String rhFactor;
public LocalDate collectionDate;
public LocalDate expiryDate;
public boolean isAvailable;
//constructor to initialize blood group so that the blood can be stored
public blood(String bloodGroup, LocalDate collectionDate, LocalDate expiryDate){
this.bloodGroup = bloodGroup;
this.collectionDate = collectionDate;
this.expiryDate = expiryDate;
}
//constructor to initialize blood in terms of blood group...
public blood(String bloodGroup){
this.bloodGroup = bloodGroup;
}
public String getBloodGroup() {
return bloodGroup;
}
public String getIronLevel() {
return ironLevel;
}
public String getRhFactor() {
return rhFactor;
}
public LocalDate getCollectionDate() { return collectionDate; }
public LocalDate getExpiryDate() {
return expiryDate;
}
public void setBloodGroup(String bloodGroup) {
this.bloodGroup = bloodGroup;
}
public void setIronLevel(String ironLevel) {
this.ironLevel = ironLevel;
}
public void setRhFactor(String rhFactor) {
this.rhFactor = rhFactor;
}
public void setCollectionDate(LocalDate collectionDate) {
this.collectionDate = collectionDate;
}
public void setExpiryDate(LocalDate expiryDate){
this.expiryDate = expiryDate;
}
public boolean isAvailable(){
return this.isAvailable;
}
} | mahadkamran3/Se-3-A | blood.java | 348 | //constructor to initialize blood in terms of blood group... | line_comment | en | true |
132195_1 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.ArrayList;
/**
* Write a description of class BloodMoon here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class BloodMoon extends Effect
{
private static boolean happening = false;
private GreenfootSound ominousSound = new GreenfootSound("spoopy.wav");
public BloodMoon(int duration) {
super(duration, 90);
// static variable to make sure two blood moons don't happen simultaneously
happening = true;
// play sound when blood moon starts
ominousSound.play();
}
public void addedToWorld(World w) {
// set image
VehicleWorld vw = (VehicleWorld)w;
image = drawBloodMoon(vw.getWidth(), vw.getHeight(), 100, 690, 10);
setImage(image);
// make entities faster
for (Entity e : vw.getObjects(Entity.class)) {
e.scaleSpeed(3);
}
// make vehicles swerve in sine wave pattern
for (Vehicle v : vw.getObjects(Vehicle.class)) {
v.startSwerving();
}
}
public void act() {
// undo effects on world
if (fadeDuration == 0) {
VehicleWorld vw = (VehicleWorld)getWorld();
for (Entity e : vw.getObjects(Entity.class)) {
e.resetSpeed();
}
for (Vehicle v : vw.getObjects(Vehicle.class)) {
v.stopSwerving();
}
happening = false;
}
super.act();
}
public static GreenfootImage drawBloodMoon(int width, int height, int transparency, int moonX, int moonY) {
GreenfootImage ret = new GreenfootImage(width, height);
GreenfootImage moon = new GreenfootImage("moon.png");
ret.drawImage(moon, moonX, moonY);
ret.setColor(new Color(255, 0, 0, transparency));
ret.fill();
return ret;
}
public static boolean happening() {
return happening;
}
}
| edzhuang/vehicle-sim-2022-v2 | BloodMoon.java | 518 | /**
* Write a description of class BloodMoon here.
*
* @author (your name)
* @version (a version number or a date)
*/ | block_comment | en | true |
132855_15 | package com.Studio_Shravan.BST;
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static class Node{
Node left;
Node right;
int data;
public Node(int data, Node left, Node right) {
this.data=data;
this.left=left;
this.right=right;
}
}
public static Node construct(int[] arr, int start, int end) {
if (start > end) {
return null;
}
int mid = (start + end) / 2;
Node lc = construct(arr, start, mid-1);
Node rc = construct(arr, mid + 1, end);
Node root = new Node(arr[mid], lc, rc);
return root;
}
public static Node construct(ArrayList<Integer> arr, int start, int end) {
if (start > end) {
return null;
}
int mid = (start + end) / 2;
Node lc = construct(arr, start, mid-1);
Node rc = construct(arr, mid + 1, end);
Node root = new Node(arr.get(mid), lc, rc);
return root;
}
public static void display(Node root) {
if (root == null) {
return;
}
System.out.print(root.data + " ");
display(root.left);
display(root.right);
}
public static int size(Node root) {
if (root == null) {
return 0;
}
int size=1;
int ls = size(root.left);
int rs = size(root.right);
return ls+rs+size;
}
public static int sum(Node root) {
if (root == null) {
return 0;
}
int sum=root.data;
int ls = sum(root.left);
int rs = sum(root.right);
return ls+rs+sum;
}
public static int min(Node root) {
if (root == null) {
return Integer.MAX_VALUE;
}
if (root.left == null) {
return root.data;
}
int lm = min(root.left);
return lm;
}
public static int max(Node root) {
if (root == null) {
return Integer.MIN_VALUE;
}
if (root.right == null) {
return root.data;
}
int rm = max(root.right);
return rm;
}
public static boolean findNode(Node root, int data) {
if (root == null) {
return false;
}
if (root.data == data) {
return true;
}
if (data < root.data) {
return findNode(root.left, data);
} else if (data > root.data) {
return findNode(root.right, data);
}
return false;
}
public static Node Insert(Node root, int data) {
if (root == null) {
return new Node(data, null, null);
}
if (root.data == data) {
return null;
}
if (data < root.data) {
root.left= Insert(root.left, data);
} else if (data > root.data) {
root.right= Insert(root.right, data);
}
return root;
}
public static Node removeNode(Node root, int data) {
if (root == null) {
return null;
}
if (data < root.data) {
root.left = removeNode(root.left, data);
} else if (data > root.data) {
root.right = removeNode(root.right, data);
}else{
if (root.left != null && root.right != null) {
int lmax = max(root.left);
root.data=lmax;
root.left=removeNode(root.left, lmax);
} else if (root.left != null) {
return root.left;
} else if (root.right != null) {
return root.right;
}else{
return null;
}
}
return root;
}
static int sum=0;
public static Node sumOfLarger(Node root) {
if (root == null) {
return null;
}
sumOfLarger(root.right);
int temp=root.data;
root.data = sum;
sum+=temp;
sumOfLarger(root.left);
return root;
}
public static int lca(Node root, int a, int b) {
if ((root.data > a && root.data < b) || (root.data < a && root.data > b)) {
return root.data;
}
if (a<root.data && b < root.data) {
return lca(root.left, a, b);
} else if (a > root.data && b > root.data) {
return lca(root.right, a, b);
}
return root.data;
}
public static void printInRange(Node root, int a, int b) {
if (root == null) {
return;
}
printInRange(root.left, a, b);
if(root.data>=a && root.data <= b){
System.out.print(root.data+" ");
}
printInRange(root.right, a, b);
}
public static Node leastGreaterElement(Node root) {
if (root == null) {
return null;
}
leastGreaterElement(root.left);
int k=root.data;
ArrayList<Integer> a =new ArrayList<>();
inOrder(root,a, k);
if (!a.isEmpty()) {
root.data = a.get(0);
}else {
root.data = -1;
}
leastGreaterElement(root.right);
return root;
}
// public static Node mergeBST(Node root1, Node root2) {
// ArrayList<Integer> a1=new ArrayList<>();
// ArrayList<Integer> a2=new ArrayList<>();
// inOrder(root1, a1);
// inOrder(root2, a2);
// for (int i = 0; i < a2.size(); i++) {
// a1.add(a2.get(i));
// }
// Collections.sort(a1);
// return construct(a1, 0, a1.size() - 1);
// }
public static void inOrder(Node root, ArrayList<Integer> arrayList,int k) {
if (root == null) {
return ;
}
inOrder(root.left, arrayList,k);
if(root.data>k) {
arrayList.add(root.data);
}
inOrder(root.right, arrayList,k);
}
// public static int medianBST(Node root) {
// ArrayList<Integer> a = new ArrayList<>();
// inOrder(root, a);
// int size=0;
// if (a.size() % 2 != 0) {
// size=a.size()-1/2;
// return a.get(size);
// }else{
// size=a.size()/2;
// int temp=size-1;
// return (a.get(temp)+a.get(size))/2;
// }
// }
static int count=1;
public static int newBst(Node root,int median){
if (root == null) {
return count;
}
newBst(root.left, median);
count++;
if(count==median){
return root.data;
}
count++;
newBst(root.right, median);
return root.data;
}
public static int median(Node root) {
int size = size(root);
if (size % 2 != 0) {
return newBst(root, (size-1)/2);
}else{
int a=newBst(root,size/2);
int b = newBst(root, a - 1);
return (a+b)/2;
}
}
public static void main(String[] args) {
int[] a = {1, 4, 8, 12, 15, 19, 21, 42, 52, 59};
int[] b = {13, 17, 22, 34, 57, 80, 89, 91, 99};
Node root1= construct(a, 0, a.length-1);
Node root2 = construct(b, 0, b.length-1);
// Insert(root, 10);
// removeNode(root, 42);
// sumOfLarger(root);
// root1 = mergeBST(root1, root2);
root1 = leastGreaterElement(root1);
display(root1);
System.out.println();
// System.out.println(medianBST(root1));
// System.out.println(median(root1));
// System.out.println();
// display(root2);
// System.out.println(lca(root,59,21));
// printInRange(root,12,45);
// System.out.println(size(root));
// System.out.println(sum(root));
// System.out.println(min(root));
// System.out.println(max(root));
// System.out.println(findNode(root,20));
}
}
| ShravanJanwade/DSA-Questions-Solutions | Main.java | 2,315 | // if (a.size() % 2 != 0) {
| line_comment | en | true |
133828_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
*/
class Strong {
}
| varshagupta09/java | Strong.java | 62 | /*
* 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 |
133971_0 | /*******************************************************************************
* 26) Escreva um programa que exiba os números de 1 a 100 na tela em ordem
* decrescente.
*******************************************************************************/
import java.util.Scanner;
public class Exercicio {
public static void main(String[] args) {
Scanner entrada = new Scanner(System.in);
for(int x =100;x>0;x--){
System.out.println(x);
}
}
}
| victorperin/Exercicios-Java | Lista - 64 Exercicios/26/Exercicio.java | 116 | /*******************************************************************************
* 26) Escreva um programa que exiba os números de 1 a 100 na tela em ordem
* decrescente.
*******************************************************************************/ | block_comment | en | true |
134073_0 | /*******************************************************************************
* Copyright (c) 2013 Eric Dill -- [email protected]. North Carolina State University. All rights reserved.
* This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*
* Contributors:
* Eric Dill -- [email protected] - initial API and implementation
* James D. Martin -- [email protected] - Principal Investigator
******************************************************************************/
package ui;
public class PrintChars {
public static void main(String[] args) {
char a = 0;
for(int i = 0; i < 255; i++) {
System.out.println(i + ": " + a++);
}
}
}
| TheMartinLab/CrystalSim | src/ui/PrintChars.java | 219 | /*******************************************************************************
* Copyright (c) 2013 Eric Dill -- [email protected]. North Carolina State University. All rights reserved.
* This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*
* Contributors:
* Eric Dill -- [email protected] - initial API and implementation
* James D. Martin -- [email protected] - Principal Investigator
******************************************************************************/ | block_comment | en | true |
134758_3 | package logica;
import java.sql.SQLException;
import java.time.LocalDate;
import dao.SeasonDAO;
import utils.BusquedaResultado;
public class Season implements DUILogic, LikeName {
private int id;
private String name;
private LocalDate startDate;
private LocalDate terminationDate;
private String description;
private String typeOfSeason;
private int accommodationContractId;
private BusquedaResultado busquedaResultado; // atributo para las tareas de busqueda
public Season(int id, String name, LocalDate startDate,
LocalDate terminationDate, String description,
String typeOfSeason, int accommodationContractId) { // Constructor a nivel de base datos
super();
this.id = id;
this.name = name;
this.startDate = startDate;
this.terminationDate = terminationDate;
this.description = description;
this.typeOfSeason = typeOfSeason;
this.accommodationContractId = accommodationContractId;
}
public Season(String name, LocalDate startDate,
LocalDate terminationDate, String description,
String typeOfSeason, int accommodationContractId) { // Constructor a nivel de logica
super();
this.name = name;
this.startDate = startDate;
this.terminationDate = terminationDate;
this.description = description;
this.typeOfSeason = typeOfSeason;
this.accommodationContractId = accommodationContractId;
}
public Season(String name, LocalDate startDate,
LocalDate terminationDate, String description,
String typeOfSeason) { // Constructor a nivel de logica (para las tareas de inserccion temporales)
super();
this.name = name;
this.startDate = startDate;
this.terminationDate = terminationDate;
this.description = description;
this.typeOfSeason = typeOfSeason;
}
public Season() { // Constructor temporal
this.id = -1;
}
public void actualizarCampos(String name, LocalDate startDate,
LocalDate terminationDate, String description,
String typeOfSeason, int accommodationContractId) { // Metodo para actualizar los campos de la clase
this.name = name;
this.startDate = startDate;
this.terminationDate = terminationDate;
this.description = description;
this.typeOfSeason = typeOfSeason;
this.accommodationContractId = accommodationContractId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDate getStartDate() {
return startDate;
}
public void setStartDate(LocalDate startDate) {
this.startDate = startDate;
}
public LocalDate getTerminationDate() {
return terminationDate;
}
public void setTerminationDate(LocalDate terminationDate) {
this.terminationDate = terminationDate;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTypeOfSeason() {
return typeOfSeason;
}
public void setTypeOfSeason(String typeOfSeason) {
this.typeOfSeason = typeOfSeason;
}
public int getAccommodationContractId() {
return accommodationContractId;
}
public void setAccommodationContractId(int accommodationContractId) {
this.accommodationContractId = accommodationContractId;
}
@Override
public void insert() throws SQLException {
this.id = SeasonDAO.getInstancie().insert(this);
}
@Override
public void update() throws SQLException {
SeasonDAO.getInstancie().update(this);
}
@Override
public void delete() throws SQLException {
SeasonDAO.getInstancie().delete(this.id);
}
// Operaciones
// Metodo para comprobar semejanza de nombre
public boolean isSameName(String name) {
boolean veredicto = false;
String nameComparar = "";
if (!name.equalsIgnoreCase("")) {
for (int i = 0, j = 0, l = 0; i < this.name.length() && !veredicto; i++) {
nameComparar += this.name.charAt(i);
j++;
if (j == name.length()) {
if (name.equalsIgnoreCase(nameComparar)) {
veredicto = true;
this.busquedaResultado = new BusquedaResultado(nameComparar, i - (j - 1), i);
} else {
nameComparar = "";
this.busquedaResultado = null;
}
j = 0;
i = l++;
}
}
} else {
veredicto = true;
this.busquedaResultado = null;
}
return veredicto;
}
public boolean isEqualsType(String type) {
return this.typeOfSeason.equalsIgnoreCase(type);
}
// Fin Metodo para comprobar semejanza de nombre
public boolean verificarIntervaloFechas() {
return ((this.startDate != null && this.terminationDate != null) && this.terminationDate.isAfter(this.startDate));
}
public boolean verificarFechasInContract(LocalDate startDateContract, LocalDate terminationDateContract) {
return (this.startDate.isAfter(startDateContract) || this.startDate.isEqual(startDateContract)) && (this.terminationDate.isBefore(terminationDateContract) ||
this.terminationDate.isEqual(terminationDateContract));
}
// Fin de Operaciones
}
| NairAd02/Know-Cuba-Proyect | Logica/logica/Season.java | 1,281 | // Constructor a nivel de logica (para las tareas de inserccion temporales) | line_comment | en | true |
135400_0 | /*
* Copyright (C) 2005 Luca Veltri - University of Parma - Italy
*
* This file is part of MjSip (http://www.mjsip.org)
*
* MjSip 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.
*
* MjSip 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 MjSip; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author(s):
* Luca Veltri ([email protected])
*/
package org.zoolu.tools;
import java.util.Vector;
/** HashSet
*/
public class HashSet
{
Vector set;
public HashSet()
{ set=new Vector();
}
public int size()
{ return set.size();
}
public boolean isEmpty()
{ return set.isEmpty();
}
public boolean add(Object o)
{ set.addElement(o);
return true;
}
public boolean remove(Object o)
{ return set.removeElement(o);
}
public boolean contains(Object o)
{ return set.contains(o);
}
public Iterator iterator()
{ return new Iterator(set);
}
}
| coralcea/bigbluebutton | sipphone/src/org/zoolu/tools/HashSet.java | 426 | /*
* Copyright (C) 2005 Luca Veltri - University of Parma - Italy
*
* This file is part of MjSip (http://www.mjsip.org)
*
* MjSip 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.
*
* MjSip 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 MjSip; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author(s):
* Luca Veltri ([email protected])
*/ | block_comment | en | true |
135700_0 | package connection;
import java.io.IOException;
public abstract class MenuItem {
/**
* This class represents a menu-item.
* It can be either (sub)menu or menu-point.
* It cannot be instantiated without adding a label to it.
* It also has an instance-method called launch().
* If the instance is a (sub)menu, it gives User the opportunity to choose from preset menu-items.
* If the instance is a menu-point, launch() simply invokes preset method.
*/
protected String label;
public MenuItem(String label) {
this.label = label;
}
public String getLabel() { return label; }
public abstract boolean launch() throws ClassCastException, ClassNotFoundException, IOException;
}
| AdamVegh/Javanymous_Team | connection/MenuItem.java | 175 | /**
* This class represents a menu-item.
* It can be either (sub)menu or menu-point.
* It cannot be instantiated without adding a label to it.
* It also has an instance-method called launch().
* If the instance is a (sub)menu, it gives User the opportunity to choose from preset menu-items.
* If the instance is a menu-point, launch() simply invokes preset method.
*/ | block_comment | en | false |
135838_2 | import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Modes {
//make a frame to hold the buttons of the modes
//make a button for each mode
//there should be not more than 3 buttons in the same y coordinates
JFrame frame = new JFrame("Modes");
JPanel panel = new JPanel();
JButton classic = new JButton("Classic");
JButton zen = new JButton("Zen");
JButton fast = new JButton("Fast");
JButton back = new JButton("Back");
JButton exit = new JButton("Exit");
JButton classicinfo = new JButton("?");
JButton zeninfo = new JButton("?");
JButton fastinfo = new JButton("?");
public Modes() {
frame.setSize(1000, 650);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setLayout(null);
ImageIcon logo = new ImageIcon("logo.png");
frame.setIconImage(logo.getImage());
frame.setVisible(true);
panel.setLayout(null);
panel.setBackground(Color.BLACK);
panel.setBounds(0, 0, 1000, 650);
panel.setBorder(BorderFactory.createEmptyBorder(100, 100, 100, 100));
classic.setBackground(Color.GREEN);
classic.setForeground(Color.WHITE);
classic.setFont(new Font("Comic Sans MS", Font.PLAIN, 30));
classic.setBorder(BorderFactory.createEtchedBorder());
classic.setBounds(100, 150, 200, 100);
classic.setFocusable(false);
classic.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SnakeGameClassic.main(null);
frame.dispose();
}
});
panel.add(classic);
zen.setBackground(Color.GREEN);
zen.setForeground(Color.WHITE);
zen.setFont(new Font("Comic Sans MS", Font.PLAIN, 30));
zen.setBorder(BorderFactory.createEtchedBorder());
zen.setBounds(590, 150, 200, 100);
zen.setFocusable(false);
zen.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SnakeGameZen.main(null);
frame.dispose();
}
});
panel.add(zen);
fast.setBackground(Color.GREEN);
fast.setForeground(Color.WHITE);
fast.setFont(new Font("Comic Sans MS", Font.PLAIN, 30));
fast.setBorder(BorderFactory.createEtchedBorder());
fast.setBounds(100, 260, 200, 100);
fast.setFocusable(false);
fast.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SnakeGameFast.main(null);
frame.dispose();
}
});
panel.add(fast);
back.setBackground(Color.GREEN);
back.setForeground(Color.WHITE);
back.setFont(new Font("Comic Sans MS", Font.PLAIN, 30));
back.setBorder(BorderFactory.createEtchedBorder());
back.setBounds(250, 400, 200, 100);
back.setFocusable(false);
back.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new Menu();
frame.dispose();
}
});
panel.add(back);
exit.setBackground(Color.GREEN);
exit.setForeground(Color.WHITE);
exit.setFont(new Font("Comic Sans MS", Font.PLAIN, 30));
exit.setBorder(BorderFactory.createEtchedBorder());
exit.setBounds(460, 400, 200, 100);
exit.setFocusable(false);
exit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
frame.dispose();
}
});
panel.add(exit);
classicinfo.setBackground(Color.GREEN);
classicinfo.setForeground(Color.WHITE);
classicinfo.setFont(new Font("Comic Sans MS", Font.PLAIN, 30));
classicinfo.setBorder(BorderFactory.createEtchedBorder());
classicinfo.setBounds(310, 150, 100, 100);
classicinfo.setFocusable(false);
classicinfo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ClassicInfoFrame.main(null);
frame.dispose();
}
});
panel.add(classicinfo);
zeninfo.setBackground(Color.GREEN);
zeninfo.setForeground(Color.WHITE);
zeninfo.setFont(new Font("Comic Sans MS", Font.PLAIN, 30));
zeninfo.setBorder(BorderFactory.createEtchedBorder());
zeninfo.setBounds(800, 150, 100, 100);
zeninfo.setFocusable(false);
zeninfo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ZenInfoFrame.main(null);
frame.dispose();
}
});
panel.add(zeninfo);
fastinfo.setBackground(Color.GREEN);
fastinfo.setForeground(Color.WHITE);
fastinfo.setFont(new Font("Comic Sans MS", Font.PLAIN, 30));
fastinfo.setBorder(BorderFactory.createEtchedBorder());
fastinfo.setBounds(310, 260, 100, 100);
fastinfo.setFocusable(false);
fastinfo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
FastInfoFrame.main(null);
frame.dispose();
}
});
panel.add(fastinfo);
frame.add(panel);
}
public static void main(String[] args) {
new Modes();
}
}
| GenDelta/Snake-Game | Modes.java | 1,439 | //there should be not more than 3 buttons in the same y coordinates
| line_comment | en | false |
136004_2 | package linAlgCalc;
import java.io.IOException;
import java.util.Scanner;
public class CalcMain {
/**
* Main method that displays the main menu to the user.
*
* @param args Unused.
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean done = false;
System.out.println("\n\n\n Welcome to the Linear Algebra Calculator.\n");
while (!done) {
System.out.println(" Please select from these four options.\n\n"
+ " [Enter 1] [Enter 3]\n"
+ " Build a matrix to compute it's: Build a set of vectors in"
+ " order to: \n"
+ " - Inverse - Determine if a vector\n"
+ " - Reduced Row Echelon Form is within the set's span\n"
+ " - Adjoint - Determine if the set\n"
+ " - Upper Triangular Form is linearly independent\n"
+ " - Transpose - Determine if the set forms\n"
+ " - Determinant a basis for R^n\n"
+ " - Null Space - Compute a vector with\n"
+ " - Scalar Multiple respect to a basis\n"
+ " - Compute a transition matrix\n"
+ " [Enter 2] from one basis to another\n"
+ " Build two matrices in order to: - Apply the Gram-Schmidt\n"
+ " - Multiply Matrices process to compute an\n"
+ " - Add Matrices orthogonal basis\n"
+ " - Subtract Matrices - Compute an orthogonal\n"
+ " complement to an \n"
+ " orthogonal basis\n\n"
+ " [Enter 0]\n"
+ " - Quit\n");
int userChoice = 99;
while (userChoice < 0 || userChoice > 3) {
while(!input.hasNextInt()) {
input.next();
}
userChoice = input.nextInt();
}
switch (userChoice) {
case 1:
oneMatrix(input);
break;
case 2:
twoMatrix(input);
break;
case 3:
vectorSet(input);
break;
case 0:
done = true;
break;
}
}
System.out.println("\n\n\n Goodbye.\n\n\n");
}
/**
* Pauses the program from returning to a menu. Prompts the user to press enter to continue.
*/
private static void enterToContinue() {
System.out.println("Press ENTER to continue.\n");
try {
System.in.read();
} catch (IOException e) {
}
}
/**
* The menu for conducting operations on a single matrix.
*
* @param input The scanner to take in user input.
*/
private static void oneMatrix(Scanner input) {
Matrix oneMatrix = new Matrix(input);
if (oneMatrix.getMatrixArray().length < 2 || oneMatrix.getMatrixArray()[0].length < 2) {
System.out.println("Vectors are not supported by this option.\n");
return;
}
System.out.println("Your matrix is now created.\n");
boolean done = false;
while(!done) {
System.out.println(" What would you like to compute?\n\n"
+ "Enter: [1] Inverse [9] Show dimensions\n"
+ " [2] Row Reduced Echelon Form (RREF) [0] Show matrix\n"
+ " [3] Adjoint\n"
+ " [4] An Upper Triangular Form\n"
+ " [5] Transpose\n"
+ " [6] Determinant\n"
+ " [7] Null Space [90] Quit\n"
+ " [8] Scalar Multiple\n");
int userChoice = 99;
while ((userChoice < 0 || userChoice > 9 ) && userChoice != 90) {
while(!input.hasNextInt()) {
input.next();
}
userChoice = input.nextInt();
}
input.nextLine();
switch (userChoice) {
case 1:
chooseInverseMethod(input, oneMatrix);
break;
case 2:
oneMatrix.getRREF();
enterToContinue();
break;
case 3:
oneMatrix.getAdjoint();
enterToContinue();
break;
case 4:
oneMatrix.getUpperTriangularForm();
enterToContinue();
break;
case 5:
oneMatrix.getTranspose();
enterToContinue();
break;
case 6:
oneMatrix.getDeterminant();
enterToContinue();
break;
case 7:
oneMatrix.getNullSpace();
enterToContinue();
break;
case 8:
oneMatrix.getScaledMatrix(input);
enterToContinue();
break;
case 9:
oneMatrix.getNumRows();
oneMatrix.getNumColumns();
enterToContinue();
break;
case 0:
oneMatrix.print();
enterToContinue();
break;
case 90:
done = true;
break;
}
}
}
/**
* The menu for choosing which method to use in computing the inverse of a matrix. The row
* reduction method will show each step in the row reduction of the augmented matrix that
* contains the matrix and the identity matrix. Choosing the adjoint method will only display
* the resulting inverse.
*
* @param input The scanner to take in user input.
* @param oneMatrix The matrix to be inverted.
*/
private static void chooseInverseMethod(Scanner input, Matrix oneMatrix) {
MatrixOperator operator = new MatrixOperator();
boolean invertible = operator.checkInvertibility(oneMatrix.getMatrixArray());
if (!invertible) {
System.out.println("This matrix is not invertible. Please select another option.\n");
enterToContinue();
return;
}
System.out.println("Please choose which method to compute the inverse with.\n\n"
+ " [Enter 1] [Enter 2]\n\n"
+ "- Row Reduction Method - Adjoint Method");
int userChoice = 99;
while ((userChoice < 0 || userChoice > 9 ) && userChoice != 90) {
while(!input.hasNextInt()) {
input.next();
}
userChoice = input.nextInt();
}
switch (userChoice) {
case 1:
oneMatrix.getRowReducedInverse();;
enterToContinue();
break;
case 2:
oneMatrix.getAdjointInverse();
enterToContinue();
break;
}
}
/**
* The menu for conducting matrix multiplication, addition, or subtraction involving to
* matrices.
*
* @param input The scanner to take in user input.
*/
private static void twoMatrix(Scanner input) {
MatrixOperator operator = new MatrixOperator();
Matrix oneMatrix = new Matrix(input);
Matrix twoMatrix = new Matrix(input);
System.out.println("Your matrices are now created.\n");
boolean done = false;
while(!done) {
System.out.println(" What would you like to compute?\n\n"
+ "Enter: [1] Multiply [5] Show first matrix dimensions\n"
+ " [2] Add [6] Show first matrix\n"
+ " [3] Subtract [7] Show second matrix dimensions\n"
+ " [4] Swap matrix order [8] Show second matrix\n\n"
+ " [90] Quit");
int userChoice = 99;
while ((userChoice < 0 || userChoice > 8 ) && userChoice != 90) {
while(!input.hasNextInt()) {
input.next();
}
userChoice = input.nextInt();
}
switch (userChoice) {
case 1:
operator.multiplyMatrices(oneMatrix.getMatrixArray(), twoMatrix.getMatrixArray());
enterToContinue();
break;
case 2:
operator.addSubtractMatrices(oneMatrix.getMatrixArray(),
twoMatrix.getMatrixArray(), true);
enterToContinue();
break;
case 3:
operator.addSubtractMatrices(oneMatrix.getMatrixArray(),
twoMatrix.getMatrixArray(), false);
enterToContinue();
break;
case 4:
Matrix tempMatrix = oneMatrix;
oneMatrix = twoMatrix;
twoMatrix = tempMatrix;
System.out.println("The first matrix is now:");
oneMatrix.print();
System.out.println("The second matrix is now:");
twoMatrix.print();
enterToContinue();
break;
case 5:
oneMatrix.getNumRows();
oneMatrix.getNumColumns();
enterToContinue();
break;
case 6:
oneMatrix.print();
enterToContinue();
break;
case 7:
twoMatrix.getNumRows();
twoMatrix.getNumColumns();
enterToContinue();
break;
case 8:
twoMatrix.print();
enterToContinue();
break;
case 90:
done = true;
break;
}
}
}
/**
* Prompts the user to choose whether or not they want to compute the orthogonal complement of
* the orthogonal basis that was just computed, and outputs it to the user if they chose yes.
*
* @param input The scanner to take in user input.
* @param vectorSet The set of vectors the the orthogonal basis was computed from.
* @param operator The vector set operator that computes the orthogonal complement.
*/
public static void orthogonalComplement(Scanner input, VectorSet vectorSet,
VectorSetOperator operator) {
System.out.println("Would you like to compute the orthogonal complement(W-perp) as well?\n"
+ "\n [Enter 1] [Enter 2]\n\n"
+ " - Yes - No");
int userChoice = 99;
while ((userChoice < 0 || userChoice > 9 ) && userChoice != 90) {
while(!input.hasNextInt()) {
input.next();
}
userChoice = input.nextInt();
}
switch (userChoice) {
case 1:
vectorSet.getOrthogonalComplement(vectorSet.getVectorSetArr());;
break;
case 2:
break;
}
}
/**
* The menu for conducting operations on a set of vectors.
*
* @param input The scanner to take in user input.
*/
public static void vectorSet(Scanner input) {
VectorSetOperator operator = new VectorSetOperator();
VectorSet vectorSet = new VectorSet(input);
boolean done = false;
while(!done ) {
System.out.println(" What would you like to do?\n"
+ "Enter: [1] Determine if a vector is within the span\n"
+ " [2] Determine if the set is linearly independent\n"
+ " [3] Determine if the set forms a basis for R^n\n"
+ " [4] Transform a vector to a vector with respect to a basis\n"
+ " [5] Compute a transition matrix from one basis to another\n"
+ " [6] Apply the Gram-Schmidt process to compute an orthogonal basis\n"
+ " [7] Show current set of vectors\n\n"
+ " [90] Quit");
int userChoice = 99;
while ((userChoice < 0 || userChoice > 7 ) && userChoice != 90) {
while(!input.hasNextInt()) {
input.next();
}
userChoice = input.nextInt();
}
input.nextLine();
switch (userChoice) {
case 1:
vectorSet.getVectorWithinSpan(input);
enterToContinue();
break;
case 2:
vectorSet.getLinearDependence();
enterToContinue();
break;
case 3:
vectorSet.getIsBasisForRn();
enterToContinue();
break;
case 4:
vectorSet.getVrespectS(input);
enterToContinue();
break;
case 5:
vectorSet.getTransitionMatrix(input);
enterToContinue();
break;
case 6:
vectorSet.getOrthogonalBasis();
orthogonalComplement(input, vectorSet, operator);
enterToContinue();
break;
case 7:
vectorSet.print();
enterToContinue();
break;
case 90:
done = true;
break;
}
}
}
}
| Alereik/linearAlgebraCalculator | CalcMain.java | 3,293 | /**
* The menu for conducting operations on a single matrix.
*
* @param input The scanner to take in user input.
*/ | block_comment | en | true |
136548_4 | package teams;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import tournaments.Award;
import userinterface.ConsoleWindow;
/**
* Stores all the data for a FIRST Tech Challenge team. Stores the team's name,
* number, and other assorted info. Also stores the team's QP and RP totals for
* the current competition, as well as their average score over all competitions
* and the awards that they have won.
*
* <blockquote><ul>
* <li>Number: The team's <b>identification number</b>.
* <li>Name: The team's <b>name</b>.
* <li>Description: A short description of the team, where they're from, etc.
* </ul></blockquote>
*
* <p>Also contains the capability to store and load teams' data as a serialized object.
*
* <p>I'm planning to add more data points, such as number of balls scored, average
* height of the tubes, autonomous routines, etc.
*
* @author Jonathan Thomas
*/
public class Team implements Serializable{
/**
*
*/
private static final long serialVersionUID = -1036964836902877837L;
// Important team data. Name and number
private int teamNumber = 0;
private String teamName = "NO NAME";
// Qualifying points and round points for this competition. This information is not stored in the team's data file
private transient int qp = 0;
private transient int rp = 0;
// Total points earned and total matches played. Used to calculate the average points a team earns.
private int totalPoints = 0;
private int totalMatches = 0;
// A short description of the team
private String description = "";
private ArrayList<Award> awards = new ArrayList<Award>();
// File path and extension for saving team data
public static String teamsDataPath = "data/teams/";
public static String teamsFileExt = ".dat";
// Console window used for outputting text
public transient ConsoleWindow cons = new ConsoleWindow();
/**
*
*/
public Team(){}
/**
* Constructor that sets team name and number.
*
* @param teamNumber An integer number, used to identify the team.
* @param teamName A String containing the team's name.
*/
public Team(int teamNumber, String teamName){
this.teamNumber = teamNumber;
this.teamName = teamName;
}
/**
* Constructor that sets team number only.
*
* @param teamNumber An integer number, used to identify the team.
*/
public Team(int teamNumber){
this.teamNumber = teamNumber;
}
/**
* Create a Team object directly from a file.
* <p>This constructor loads the team's data directly from a file.
* It parses the file for the team's information, and populates
* the object's data fields with what it finds. <p>If there is a
* problem with the file, the method will print a message to the
* console.
*
* @param file The File object to load the team's information from.
*/
public Team(File file){
// Try to load the team from a file
load(file);
}
/**
* @return The team's number identifier.
*/
public int getTeamNumber(){
return teamNumber;
}
/**
* Sets the team's number identifier.
*
* @param number
*/
public void setTeamNumber(int number){
teamNumber = number;
cons.printConsoleLine("Set " + teamName + "'s number to " + teamNumber);
}
/**
* @return The team's name.
*/
public String getTeamName(){
return teamName;
}
/**
* Sets the team's name
*
* @param name A String with the team's name
*/
public void setTeamName(String name){
teamName = name;
cons.printConsoleLine("Set team " + teamNumber + "'s name to " + teamName);
}
/**
* Set the team's qualifying points total.
*
* @param qp
*/
public void setQP(int qp){
this.qp = qp;
cons.printConsoleLine("Set " + toString() + "'s Qualifying Points to " + qp);
}
/**
* @return The team's qualifying points total.
*/
public int getQP(){
return qp;
}
/**
* Add qualifying points to a team. The parameter amount is added to the team's current QP total.
*
* @param qp The number of points you would like to add.
*/
public void addQP(int qp){
this.qp += qp;
cons.printConsoleLine("Added " + qp + " qualifying points to team " + toString());
}
/**
* Set the team's round points total.
*
* @param rp
*/
public void setRP(int rp){
this.rp = rp;
cons.printConsoleLine("Set " + toString() + "'s Round Points to " + rp);
}
/**
* @return The team's round points total.
*/
public int getRP(){
return rp;
}
/**
* Add round points to a team. The parameter amount will be added to the team's current RP total.
*
* @param rp The number of points that you would like to add.
*/
public void addRP(int rp){
this.rp += rp;
cons.printConsoleLine("Added " + rp + " round points to team " + toString());
}
/**
* <b>CURRENTLY RETURNS SINGLE-DIMENSIONAL ARRAY. WILL FIX.</b>
* <p>Returns a list of awards that the team has won, in the form of a two-dimensional array. The first
* dimension is split by competition. Each element is a different event. The second dimension is the list
* for that event. The first element of every second-level array is the title of the competition, and the
* following elements are the list of awards. An example:
* <blockquote><ul>
* <li>{"Dayton Regional Qualifier", "Think Award"}
* <li>{"Columbus Regional Qualifier", "PTC Design Award", "Finalist Alliance Member"}
* <li>{"Ohio State Championship", "Inspire Award", "Winning Alliance Member"}
* </ul></blockquote?
*
* @return A String array containing a list of awards that the team has won.
*/
public String[] getAwardsList(){
String[] newList = new String[awards.size()];
for(int i = 0; i < awards.size(); i++)
newList[i] = Award.awardTitles[awards.get(i).getAwardType()];
return newList;
}
/**
* Add an award to the team's history. The parameter value is the identifier for the award you would like
* to add. The Award class has static constants for use in identifying awards.
*
* <p><b>THIS DOESN'T WORK THE WAY I WANT IT TO. WILL FIX.</b>
*
* @param awardType The identifier for the award you want to add.
*/
public void addAwards(int awardType){
awards.add(new Award(awardType));
}
/**
* Returns the team name and number in a formatted string. Example:
* <blockquote><b>"5029 : Powerstackers"</b></blockquote>
*/
public String toString(){
return teamNumber + " : " + teamName;
}
/**
* Returns the team's name and number in a formatted string for use as a file name. Example:
* <blockquote><b>5029_Powerstackers</b></blockquote>
*/
public String getSaveFileName(){
return teamNumber + "_" + teamName;
}
/**
* Save the team's information to a file.
* <p>This method currently saves in properties file-type notation, with the name of the value and the
* value itself separated by an equals sign. Example:
*
* <blockquote>teamName=Powerstackers
* <br>teamNumber=5029</blockquote>
*
* <p>If there is a problem with the file, the method will print a message to the console and the data
* will not be saved. Currently, the method only saves the team name and number. I'm planning to add
* the other information into the file, once I work out a way to separate data by competition.
*/
public static void save(Team team){
try{
// Create an object output stream to write to the file
ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream(teamsDataPath + team.getSaveFileName() + teamsFileExt));
// Write the object to the file
out.writeObject(team);
out.close();
}catch(FileNotFoundException ex){
team.cons.printConsoleLine("There was an error saving team data");
} catch (IOException e) {
// TODO Auto-generated catch block
team.cons.printConsoleLine("There was an error saving team data");
}
}
/**
* Load the team's information from a file.
* <p>This method reads in properties file-type notation, with the name of the value and the
* value itself separated by an equals sign. Example:
*
* <blockquote>teamName=Powerstackers
* <br>teamNumber=5029</blockquote>
*
* <p>If there is a problem with the file, the method will throw an exception and the data
* will not be loaded. Currently, the method only loads the team name and number. I'm planning to add
* the other information into the file, once I work out a way to separate data by competition.
*
* @param file The File object that stores the data you want to load.
* @throws FileNotFoundException Thrown if the file does not exist.
*/
public static Team load(File file){
Team team = null;
try {
// Create an object input stream to read in the file
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
// Try to load the object from the file
team = (Team) in.readObject();
// Remember to close the input stream!
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
// If for some reason the team wasn't loaded, create an empty team
if(team==null){
team = new Team();
team.cons.printConsoleLine("There was a problem loading team data");
}
// Return the team
return team;
}
/**
* Add 1 match to the total matches played, and add the specified number of points to the team's total.
* This helps in calculating the team's average score.
*
* @param points
*/
public void addToAveragePoints(int points){
totalMatches++;
totalPoints += points;
}
/**
* Calculate the team's average score through all matches played.
*
* @return The team's average score.
*/
public int getAverageScore() {
if(totalMatches == 0)
return 0;
else
return (int) totalPoints / totalMatches;
}
/**
* Set the team's short description.
* @param description
*/
public void setDescription(String description){
this.description = description;
}
/**
* @return The team's short description.
*/
public String getDescription(){
return description;
}
public static void main(String args[]){
Team team1 = new Team(5029, "Powerstackers");
Team team2 = new Team(4251, "Cougars");
Team team3 = new Team(5501, "USS Enterprise");
Team.save(team1);
Team.save(team2);
Team.save(team3);
}
}
| powerstackers/Scouter | src/teams/Team.java | 3,003 | // Total points earned and total matches played. Used to calculate the average points a team earns. | line_comment | en | true |
136807_1 | //https://leetcode.com/problems/binary-tree-pruning/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode pruneTree(TreeNode root) {
if(root == null) return null;
TreeNode output = new TreeNode(root.val);
output.left = pruneTree(root.left);
output.right = pruneTree(root.right);
if(output.val == 0 && output.left == null && output.right == null){
return null;
}
return output;
}
}
| RuchiDeshmukh/leetcode100 | 37.java | 221 | /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/ | block_comment | en | true |
136826_0 | public class PetersLCG {
public static void main(String[] args){
//implementacion del un generador propuesto por Ivan
int period=10,a=121,c=553,m=177;
float xi=0,seed=23,ramdomNumber=0;
for(int ite=0;ite<period;ite ++){
xi=((a*seed)+c)%m;
seed=xi;
ramdomNumber=xi/(m-1);
System.out.println(ramdomNumber);
}
}
}
| SteveBartmoss/Algoritmos | PetersLCG.java | 134 | //implementacion del un generador propuesto por Ivan | line_comment | en | true |
136842_0 | /**
* Created by Peter on 1/2/14.
*/
public class Inky extends Ghost {
public Inky(double ex, double why) {
super(1, ex, why);
}
}
| Wallabies/Pac-Man | src/Inky.java | 55 | /**
* Created by Peter on 1/2/14.
*/ | block_comment | en | true |
137241_0 | import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class GUI extends JPanel implements KeyListener {
public String[][] wall;
public int x = 5, y = 5;
public GUI(String[][] walla) {
this.wall = walla;
}
public void paint(Graphics g) {
super.paint(g);
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 20; j++) {
if (wall[i][j] == "@") {
g.setColor(Color.BLACK);
g.fillRect(i * 20, j * 20, 20, 20);
} else if (wall[i][j] == " ") {
g.setColor(Color.YELLOW);
g.fillRect(i * 20, j * 20, 20, 20);
}
}
}
g.setColor(Color.WHITE);
g.fillOval(x, y, 20, 20);
repaint();
}
//Her er et forsøg på at lave en keylistener som kan styre en oval
@Override
public void keyPressed (KeyEvent e){
int c = e.getKeyCode();
if (c == KeyEvent.VK_W) {
y-=4;
}
if (c == KeyEvent.VK_S) {
y+=4;
}
if (c == KeyEvent.VK_A) {
x-=4;
}
if (c == KeyEvent.VK_D) {
x+=4;
}
}
@Override
public void keyReleased (KeyEvent e){
}
@Override
public void keyTyped (KeyEvent e){
}
}
| mikkelmedm/JavaMaze | GUI.java | 424 | //Her er et forsøg på at lave en keylistener som kan styre en oval | line_comment | en | true |
137923_1 | //jDownloader - Downloadmanager
//Copyright (C) 2009 JD-Team [email protected]
//
//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 3 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, see <http://www.gnu.org/licenses/>.
package jd.plugins.hoster;
import java.io.IOException;
import jd.PluginWrapper;
import jd.http.Browser;
import jd.http.URLConnectionAdapter;
import jd.nutils.encoding.Encoding;
import jd.parser.Regex;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
@HostPlugin(revision = "$Revision$", interfaceVersion = 3, names = { "pussy.com" }, urls = { "http://(www\\.)?bangyoulater\\.com/(embed\\.php\\?id=\\d+|[a-z0-9]+/\\d+/.{1})|https?://(?:www\\.)?pussy\\.com/[A-Za-z0-9\\-_]+" })
public class PussyCom extends PluginForHost {
public PussyCom(PluginWrapper wrapper) {
super(wrapper);
}
private String dllink = null;
@Override
public String getAGBLink() {
return "http://www.bangyoulater.com/dmca/";
}
@Override
public String rewriteHost(String host) {
if ("bangyoulater.com".equals(getHost())) {
if (host == null || "bangyoulater.com".equals(host)) {
return "pussy.com";
}
}
return super.rewriteHost(host);
}
private static final String type_old = "http://(?:www\\.)?bangyoulater\\.com/(?:embed\\.php\\?id=\\d+|[a-z0-9]+/\\d+/.{1})";
@SuppressWarnings("deprecation")
@Override
public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException {
dllink = null;
this.setBrowserExclusive();
if (downloadLink.getDownloadURL().matches(type_old)) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
if (downloadLink.getDownloadURL().matches("http://pussy.com/([\\d]+|categories|dmca|favorites|myuploads|privacypolicy|search|terms|There|upload|view-2257)")) {
logger.info("Unsupported/invalid link: " + downloadLink.getDownloadURL());
return AvailableStatus.FALSE;
}
final String name_url = new Regex(downloadLink.getDownloadURL(), "pussy\\.com/(.+)").getMatch(0);
downloadLink.setName(name_url);
br.setFollowRedirects(true);
br.getPage(downloadLink.getDownloadURL());
// ">This video is no longer available" is always in the html
if (br.getURL().equals("http://pussy.com/") || br.getHttpConnection().getResponseCode() == 404 || br.containsHTML("class=\"thumbnail err\"")) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
String filename = br.getRegex("property=\"og:title\" content=\"([^<>\"]+)\"").getMatch(0);
if (filename == null) {
/* Fallback */
filename = name_url;
}
dllink = br.getRegex("\\'(?:file|video)\\'[\t\n\r ]*?:[\t\n\r ]*?\\'(http[^<>\"]*?)\\'").getMatch(0);
if (dllink == null) {
dllink = br.getRegex("(?:file|url):[\t\n\r ]*?(?:\"|\\')(http[^<>\"]*?)(?:\"|\\')").getMatch(0);
}
if (dllink == null) {
dllink = br.getRegex("videoUrl = \\'(http://[^<>\"]*?)\\'").getMatch(0);
}
if (filename == null || dllink == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dllink = Encoding.htmlDecode(dllink);
filename = filename.trim();
final String ext = getFileNameExtensionFromString(dllink, ".mp4");
downloadLink.setFinalFileName(Encoding.htmlDecode(filename) + ext);
Browser br2 = br.cloneBrowser();
// In case the link redirects to the finallink
br2.setFollowRedirects(true);
URLConnectionAdapter con = null;
try {
con = br2.openHeadConnection(dllink);
if (!con.getContentType().contains("html")) {
downloadLink.setDownloadSize(con.getLongContentLength());
} else {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
return AvailableStatus.TRUE;
} finally {
try {
con.disconnect();
} catch (Throwable e) {
}
}
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception {
requestFileInformation(downloadLink);
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, true, 0);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return -1;
}
@Override
public void reset() {
}
@Override
public void resetPluginGlobals() {
}
@Override
public void resetDownloadlink(DownloadLink link) {
}
}
| substanc3-dev/jdownloader2 | src/jd/plugins/hoster/PussyCom.java | 1,510 | //Copyright (C) 2009 JD-Team [email protected]
| line_comment | en | true |
138214_0 | /**
* This class defines attributes of a girl and has
* a constructor method
* @author Anurag Kumar
*/
public class Girl{
String name;
int attractiveness;
int main_budget;
int intelligence;
String bf_name;
int type;
public Girl(String na, int attr,int main,int in){
name = na;
attractiveness= attr;
main_budget = main;
intelligence = in;
bf_name="";
type = (int)(Math.random()*3);
}
}
| PPL-IIITA/ppl-assignment-iit2015143 | q2/Girl.java | 147 | /**
* This class defines attributes of a girl and has
* a constructor method
* @author Anurag Kumar
*/ | block_comment | en | false |
139285_6 | // 2022.05.27
// Problem Statement:
// https://leetcode.com/problems/reverse-integer/
// idea: from x's lsb to msb,
// 10*answer + x%10 may cause overflow, have to check answer before this operation
class Solution {
public int reverse(int x) {
int answer = 0;
while (x/10!=0) {
// if (answer>(int)Math.pow(2, 31)-1 || answer<-1*(int)Math.pow(2, 31)) return 0;
// but should not use the 'updated' answer, should check the last answer before calculating 10*answer + x%10
if (answer > (0.1*(Math.pow(2, 31)-1) - 0.1*(x%10)) ||
answer < (-0.1*Math.pow(2, 31) - 0.1*(x%10))) return 0; // absolute value will only get larger,
// so an overflow is certain
answer = 10*answer + x%10;
x = x/10;
}
if (answer > (0.1*(Math.pow(2, 31)-1) - 0.1*(x%10)) ||
answer < (-0.1*Math.pow(2, 31) - 0.1*(x%10))) return 0;
answer = answer*10 + x;
return answer;
}
} | ljn1999/LeetCode-problems | Amazon/q7.java | 360 | // but should not use the 'updated' answer, should check the last answer before calculating 10*answer + x%10 | line_comment | en | false |
139315_3 | package marathon;
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
public class Amazon {
public static void main(String[] args) {
ChromeDriver driver=new ChromeDriver();
driver.get("https://www.amazon.in/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));
driver.findElement(By.id("twotabsearchtextbox")).sendKeys("bags for boys");
driver.findElement(By.id("nav-search-submit-button")).click();
String text = driver.findElement(By.xpath("//div[@class='a-section a-spacing-small a-spacing-top-small']")).getText();
System.out.println(text);
driver.findElement(By.xpath("(//i[@class='a-icon a-icon-checkbox'])[3]")).click();
driver.findElement(By.xpath("(//i[@class='a-icon a-icon-checkbox']/../..)[3]")).click();
String text2 =driver.findElement(By.xpath("//div[@class='a-section a-spacing-small a-spacing-top-small']")).getText();
System.out.println(text2);
String text1= driver.findElement(By.xpath("(//span[@class='a-size-base-plus a-color-base a-text-normal'])[3]")).getText();
System.out.println(text1);
driver.findElement(By.xpath("//span[@class='a-button-text a-declarative']")).click();
driver.findElement(By.xpath("//a[text()='Newest Arrivals']")).click();
String text3 = driver.findElement(By.xpath("(//span[@class='a-size-base-plus a-color-base a-text-normal'])[2]")).getText();
System.out.println(text3);
String text4 = driver.findElement(By.xpath("//span[text()='(66% off)']")).getText();
System.out.println(text4);
}
}
| MaheswariSivalingam/TestScript | Amazon.java | 505 | //i[@class='a-icon a-icon-checkbox']/../..)[3]")).click();
| line_comment | en | true |
139462_6 | package db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import model.Restaurant;
import org.json.JSONArray;
import org.json.JSONObject;
import yelp.YelpAPI;
public class DBConnection {
private Connection conn = null;
private static final int MAX_RECOMMENDED_RESTAURANTS = 10;
private static final int MIN_RECOMMENDED_RESTAURANTS = 3;
public DBConnection() {
this(DBUtil.URL);
}
public DBConnection(String url) {
try {
//Forcing the class representing the MySQL driver to load and initialize.
// The newInstance() call is a work around for some broken Java implementations
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url);
} catch (Exception e) {
e.printStackTrace();
}
}
public void close(){
if (conn != null) {
try {
conn.close();
} catch (Exception e) { /* ignored */}
}
}
private void executeUpdateStatement(String query) {
if (conn == null) {
return;
}
try {
Statement stmt = conn.createStatement();
System.out.println("\nDBConnection executing query:\n" + query);
stmt.executeUpdate(query);
} catch (Exception e) {
e.printStackTrace();
}
}
private ResultSet executeFetchStatement(String query) {
if (conn == null) {
return null;
}
try {
Statement stmt = conn.createStatement();
System.out.println("\nDBConnection executing query:\n" + query);
return stmt.executeQuery(query);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void SetVisitedRestaurants(String userId, List<String> businessIds) {
for (String businessId : businessIds) {
executeUpdateStatement("INSERT INTO history (`user_id`, `business_id`) VALUES (\""
+ userId + "\", \"" + businessId + "\")");
}
}
public void UnsetVisitedRestaurants(String userId, List<String> businessIds) {
for (String businessId : businessIds) {
executeUpdateStatement("DELETE FROM history WHERE `user_id`=\""
+ userId + "\" and `business_id` = \"" + businessId + "\"");
}
}
private Set<String> getCategories(String businessId) {
try {
String sql = "SELECT categories from restaurants WHERE business_id='"
+ businessId + "'";
ResultSet rs = executeFetchStatement(sql);
if (rs.next()) {
Set<String> set = new HashSet<>();
String[] categories = rs.getString("categories").split(",");
for (String category : categories) {
// ' Japanese ' -> 'Japanese'
set.add(category.trim());
}
return set;
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return new HashSet<String>();
}
private Set<String> getBusinessId(String category) {
Set<String> set = new HashSet<>();
try {
// if category = Chinese, categories = Chinese, Korean, Japanese, it's a match
String sql = "SELECT business_id from restaurants WHERE categories LIKE '%"
+ category + "%'";
ResultSet rs = executeFetchStatement(sql);
while (rs.next()) {
String businessId = rs.getString("business_id");
set.add(businessId);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return set;
}
public Set<String> getVisitedRestaurants(String userId) {
Set<String> visitedRestaurants = new HashSet<String>();
try {
String sql = "SELECT business_id from history WHERE user_id="
+ userId;
ResultSet rs = executeFetchStatement(sql);
while (rs.next()) {
String visitedRestaurant = rs.getString("business_id");
visitedRestaurants.add(visitedRestaurant);
}
} catch (Exception e) {
e.printStackTrace();
}
return visitedRestaurants;
}
public JSONObject getRestaurantsById(String businessId, Boolean isVisited) {
try {
String sql = "SELECT * from "
+ "restaurants where business_id='" + businessId + "'" + " ORDER BY stars DESC";
ResultSet rs = executeFetchStatement(sql);
if (rs.next()) {
Restaurant restaurant = new Restaurant(
rs.getString("business_id"),
rs.getString("name"),
rs.getString("categories"),
rs.getString("city"),
rs.getString("state"),
rs.getFloat("stars"),
rs.getString("full_address"),
rs.getFloat("latitude"),
rs.getFloat("longitude"),
rs.getString("image_url"),
rs.getString("url"));
JSONObject obj = restaurant.toJSONObject();
obj.put("is_visited", isVisited);
return obj;
}
} catch (Exception e) { /* report an error */
System.out.println(e.getMessage());
}
return null;
}
/*
private Set<String> getMoreCategories(String category, int maxCount) {
Set<String> allCategories = new HashSet<>();
if (conn == null) {
return null;
}
Statement stmt;
try {
stmt = conn.createStatement();
String sql = "SELECT second_id from USER_CATEGORY_HISTORY WHERE first_id=\""
+ category + "\" ORDER BY count DESC LIMIT " + maxCount;
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String visited_restaurant = rs.getString("second_id");
allCategories.add(visited_restaurant);
}
} catch (SQLException e) {
e.printStackTrace();
}
return allCategories;
}
private Set<String> getMoreCategories(Set<String> existingCategories) {
Set<String> allCategories = new HashSet<>();
for (String category : existingCategories) {
allCategories.addAll(getMoreCategories(category, 5));
}
return allCategories;
}*/
public JSONArray RecommendRestaurants(String userId) {
try {
if (conn == null) {
return null;
}
Set<String> visitedRestaurants = getVisitedRestaurants(userId);
Set<String> allCategories = new HashSet<>();// why hashSet?
for (String restaurant : visitedRestaurants) {
allCategories.addAll(getCategories(restaurant));
}
Set<String> allRestaurants = new HashSet<>();
for (String category : allCategories) {
Set<String> set = getBusinessId(category);
allRestaurants.addAll(set);
}
Set<JSONObject> diff = new HashSet<>();
int count = 0;
for (String businessId : allRestaurants) {
// Perform filtering
if (!visitedRestaurants.contains(businessId)) {
diff.add(getRestaurantsById(businessId, false));
count++;
if (count >= MAX_RECOMMENDED_RESTAURANTS) {
break;
}
}
}
/*
// offline learning
if (count < MIN_RECOMMENDED_RESTAURANTS) {
diff.clear();
allCategories.addAll(getMoreCategories(allCategories));
for (String category : allCategories) {
Set<String> set = getBusinessId(category);
allRestaurants.addAll(set);
}
for (String businessId : allRestaurants) {
if (!visitedRestaurants.contains(businessId)) {
diff.add(getRestaurantsById(businessId));
count++;
if (count >= MAX_RECOMMENDED_RESTAURANTS) {
break;
}
}
}
}*/
return new JSONArray(diff);
} catch (Exception e) {
System.out.println(e.getMessage());
}
return null;
}
/*
public JSONArray GetRestaurantsNearLoation(String userId, double lat, double lon) {
try {
if (conn == null) {
return null;
}
Set<String> visited = getVisitedRestaurants(userId);
Statement stmt = conn.createStatement();
String sql = "SELECT * from restaurants LIMIT 10";
ResultSet rs = stmt.executeQuery(sql);
List<JSONObject> list = new ArrayList<JSONObject>();
while (rs.next()) {
JSONObject obj = new JSONObject();
obj.put("business_id", rs.getString("business_id"));
obj.put("name", rs.getString("name"));
obj.put("stars", rs.getFloat("stars"));
obj.put("latitude", rs.getFloat("latitude"));
obj.put("longitude", rs.getFloat("longitude"));
obj.put("full_address", rs.getString("full_address"));
obj.put("city", rs.getString("city"));
obj.put("state", rs.getString("state"));
obj.put("categories",
DBImport.stringToJSONArray(rs.getString("categories")));
obj.put("image_url", rs.getString("image_url"));
obj.put("url", rs.getString("url"));
if (visited.contains(rs.getString("business_id"))){
obj.put("is_visited", true);
} else {
obj.put("is_visited", false);
}
list.add(obj);
}
return new JSONArray(list);
} catch (Exception e) {
System.out.println(e.getMessage());
}
return null;
}
*/
public JSONArray SearchRestaurants(String userId, double lat, double lon) {
try {
YelpAPI api = new YelpAPI();
JSONObject response = new JSONObject(
api.searchForBusinessesByLocation(lat, lon));
JSONArray array = (JSONArray) response.get("businesses");
List<JSONObject> list = new ArrayList<JSONObject>();
Set<String> visited = getVisitedRestaurants(userId);
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
Restaurant restaurant = new Restaurant(object);
String businessId = restaurant.getBusinessId();
String name = restaurant.getName();
String categories = restaurant.getCategories();
String city = restaurant.getCity();
String state = restaurant.getState();
String fullAddress = restaurant.getFullAddress();
double stars = restaurant.getStars();
double latitude = restaurant.getLatitude();
double longitude = restaurant.getLongitude();
String imageUrl = restaurant.getImageUrl();
String url = restaurant.getUrl();
JSONObject obj = restaurant.toJSONObject();
if (visited.contains(businessId)){
obj.put("is_visited", true);
} else {
obj.put("is_visited", false);
}
executeUpdateStatement("INSERT IGNORE INTO restaurants " + "VALUES ('"
+ businessId + "', \"" + name + "\", \"" + categories
+ "\", \"" + city + "\", \"" + state + "\", " + stars
+ ", \"" + fullAddress + "\", " + latitude + ","
+ longitude + ",\"" + imageUrl + "\", \"" + url + "\")");
list.add(obj);
}
return new JSONArray(list);
} catch (Exception e) {
System.out.println(e.getMessage());
}
return null;
}
public static void main(String[] args) {
//This is for test purpose
DBConnection conn = new DBConnection();
JSONArray array = conn.SearchRestaurants("1111", 37.38, -122.08);
}
}
| SteveSunTech/TicketMaster | src/db/DBConnection.java | 2,961 | /*
private Set<String> getMoreCategories(String category, int maxCount) {
Set<String> allCategories = new HashSet<>();
if (conn == null) {
return null;
}
Statement stmt;
try {
stmt = conn.createStatement();
String sql = "SELECT second_id from USER_CATEGORY_HISTORY WHERE first_id=\""
+ category + "\" ORDER BY count DESC LIMIT " + maxCount;
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String visited_restaurant = rs.getString("second_id");
allCategories.add(visited_restaurant);
}
} catch (SQLException e) {
e.printStackTrace();
}
return allCategories;
}
private Set<String> getMoreCategories(Set<String> existingCategories) {
Set<String> allCategories = new HashSet<>();
for (String category : existingCategories) {
allCategories.addAll(getMoreCategories(category, 5));
}
return allCategories;
}*/ | block_comment | en | true |
139536_1 | package easy;
import java.util.*;
public class Beautiful_word {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String w = in.next();
boolean b = false;
// int j=0,c=0;
char[] vow = { 'a', 'e', 'i', 'o', 'u', 'y' };
for (int i = 0; i < w.length(); i++) {
if (w.charAt(i) != w.charAt(i + 1)) {
for (int j = 0; j < 6; j++)
if (w.charAt(i) == vow[j]) {
j = 0;
if ((w.charAt(i + 1) == vow[j]) && (j < 6)) {
j++;
b = true;
}
}
}
}
if (b == true) {
System.out.println("no");
} else {
System.out.println("Yes");
}
// Print 'Yes' if the word is beautiful or 'No' if it is not.
in.close();
}
} | jwesly20/HackerRank | Beautiful_word.java | 297 | // Print 'Yes' if the word is beautiful or 'No' if it is not.
| line_comment | en | false |
139646_0 | package cs107;
import java.util.Arrays;
/**
* Utility class used to simulate the Unix command "diff"
* @author Hamza REMMAL ([email protected])
* @version 1.3
* @since 1.0
*/
public final class Diff {
// ============================================================================================
// ======================================= DIFF API ===========================================
// ============================================================================================
/**
* Compare two byte arrays and print in the Terminal
* the difference between them.
* @param b1 (byte[]) - First Array
* @param b2 (byte[]) - Second Array
* @throws AssertionError If one of the arrays is null
*/
public static void diff(byte[] b1, byte[] b2){
assert b1 != null;
assert b2 != null;
if(Arrays.equals(b1, b2))
showSameFileMessage();
else {
var size_to_check = b1.length != b2.length ? sizeWarning(b1.length, b2.length) : b1.length;
compareAndShow(b1, b2, size_to_check);
}
showEnd();
}
/**
* Compare the content of 2 files and print in the Terminal the difference
* between them
* @param file_1 (String) - Path of the first file
* @param file_2 (String) - Path of the second file
* @throws AssertionError if one of the paths is null
*/
public static void diff(String file_1, String file_2){
assert file_1 != null;
assert file_2 != null;
var b1 = Helper.read(file_1);
var b2 = Helper.read(file_2);
showHeader(file_1, file_2, b1, b2);
diff(b1, b2);
}
// ============================================================================================
// Hide default constructor
private Diff(){}
private static void showHeader(String file_1, String file_2, byte[] stream_f1, byte[] stream_f2){
System.out.println("========================================== DIFF ==========================================");
System.out.printf("== File 1 : '%s', size = %d bytes %n", file_1, stream_f1.length);
System.out.printf("== File 2 : '%s', size = %d bytes %n", file_2, stream_f2.length);
System.out.println("==========================================================================================");
}
private static int sizeWarning(int size_1, int size_2){
var min = Integer.min(size_1, size_2);
System.out.printf("== WARNING : The two input have different sizes, we will only check the %d first bytes%n", min);
return min;
}
private static void showSameFileMessage(){
System.out.println("== WARNING : The two inputs have the same content");
}
private static void compareAndShow(byte[] b1, byte[] b2, int size_to_check){
for (var i = 0; i < size_to_check; i++){
if (b1[i] != b2[i]){
System.out.printf("[%06X] ~ %02x ~ %02x%n", i, b1[i], b2[i]);
}
}
}
private static void showEnd(){
System.out.println("========================================= END DIFF =======================================");
}
} | MAL103/ProjectPartMarta | Diff.java | 790 | /**
* Utility class used to simulate the Unix command "diff"
* @author Hamza REMMAL ([email protected])
* @version 1.3
* @since 1.0
*/ | block_comment | en | true |
140667_0 | /*
Create one method as syntaxTechnologies and write the logic for that method in println statement as "Welcome to Syntax Technologies!"
Create another method as syntaxStudents and write the logic for that method in println statement as "Welcome Syntax Students!"
Call both methods
Expected Output:
Welcome to Syntax Technologies!
Welcome Syntax Students!
*/
public class Problem_111 {
public static void main(String[] args) {
Problem_111 m = new Problem_111();
m.syntaxTechnologies();
m.syntaxStudents();
}
void syntaxTechnologies() {
System.out.println("Welcome to Syntax Technologies!");
}
void syntaxStudents() {
System.out.println("Welcome Syntax Students!");
}
}
| wahidullahmayar2020/ReplSolutions | src/Problem_111.java | 166 | /*
Create one method as syntaxTechnologies and write the logic for that method in println statement as "Welcome to Syntax Technologies!"
Create another method as syntaxStudents and write the logic for that method in println statement as "Welcome Syntax Students!"
Call both methods
Expected Output:
Welcome to Syntax Technologies!
Welcome Syntax Students!
*/ | block_comment | en | true |
140900_0 | /*retail stores has the requirement of printing many report .All the reports have diffrent headers .
The headers of different stores contain the following
1.a line containig a character printed 50 times or
2.a title of a report or
3.a line containing a character for specified number of times
pointin of heade is required to be done for allthe reports ,but what is printed in the header differs based on the
specification given above .write the java program using method overloading
*/
package JavaProgram;
public class methodoverloading {
void retailreport() {
char a = 'R';
for (int i = 0; i <= 50; i++)
System.out.println(a);
System.out.println("character " + a + " printed 50 number of times\n");
}
void retailreport(String a) {
System.out.println(a);
System.out.println(a + " is printed \n");
}
void retailreport(char a, int b) {
for (int i = 0; i < b; i++)
System.out.println(a);
System.out.println("Character " + a + " printed " + b + " number of times \n");
}
public static void main(String[] args) {
methodoverloading obj = new methodoverloading();
obj.retailreport();
obj.retailreport("Lord is great");
obj.retailreport('P', 5);
}
}
| hacanand/Java_Program | methodoverloading.java | 343 | /*retail stores has the requirement of printing many report .All the reports have diffrent headers .
The headers of different stores contain the following
1.a line containig a character printed 50 times or
2.a title of a report or
3.a line containing a character for specified number of times
pointin of heade is required to be done for allthe reports ,but what is printed in the header differs based on the
specification given above .write the java program using method overloading
*/ | block_comment | en | true |
141920_1 | /************************************************************/
/* MAC 110 - INTRODUCAO A CIENCIA DA COMPUTACAO */
/* IME-USP - PRIMEIRO SEMESTRE DE 2012 */
/* TURMA 45 - PROFESSOR MARCEL JACKWOSKI */
/* TERCEIRO EXERCICIO-PROGRAMA */
/* ARQUIVO: EP3.java */
/* GERVASIO PROTASIO DOS SANTOS NETO NUMERO USP: 7990996 */
/* VICTOR SANCHES PORTELA NUMERO USP: 7991152 */
/* DATA DE ENTREGA : 25/06/2012 */
/************************************************************/
import java.util.*;
class EP3{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int opcao=0;
String nome = "";
Imagem minhaImagem=null;
while (opcao!=7){//Enquanto o usuário não escolehr sair, o menu semrpe será re-escrito a cada ação, inclusive no inicio do programa.
System.out.println("Menu");
System.out.println("==");
System.out.println("1)Ler imagem");
System.out.println("2)Visualizar imagem");
System.out.println("3)Suavizar com filtro médio");
System.out.println("4)Suavizar com filtro médiano");
System.out.println("5)Suavizar com filtro gaussiano");
System.out.println("6)Gravar imagem");
System.out.println("7)Sair");
opcao = sc.nextInt();
if (opcao==1){//Ler imagem
System.out.println("Digite o nome; da imagem do formato .pgm sem extenção");
sc = new Scanner(System.in);
nome = sc.nextLine() +".pgm";
minhaImagem = LeituraEscritaImagem.leImagem(nome);//Tenta ler imagem
if (minhaImagem == null){
nome = "";
System.out.println("Imagem não existente ou problema ao tentar ler imagem");
}else
System.out.println(nome+" carregado com sucesso");
}
else if (opcao==2){
VisualizadorImagem vis = new VisualizadorImagem();//Visualizador
if (minhaImagem == null)//Caso não tneha imagem carregada, é cancelada a ação
System.out.println("Carregue uma imagem primeiro");
else
vis.mostraImagem(minhaImagem,nome);
}
else if (opcao==3){ // suaviza imagem com filtro medio
if (minhaImagem == null)
System.out.println("Carregue uma imagem primeiro!");
else{
System.out.println("Entre um tamanho para a vizinhanca: ");
int tamanho = sc.nextInt();
minhaImagem.filtroMedio(tamanho);
System.out.println("Imagem suavizada com sucesso!");
VisualizadorImagem vis = new VisualizadorImagem();//Visualizador
vis.mostraImagem(minhaImagem,nome); //Abre imagem apos a suavizacao para que o usuario a visualize;
}
}
else if (opcao==4){ //suaviza imagem com filtro mediano
if (minhaImagem == null)
System.out.println("Carregue uma imagem primeiro!");
else{
System.out.println("Entre um tamanho para a vizinhanca: ");
int tamanho = sc.nextInt();
minhaImagem.filtroMediano(tamanho);
System.out.println("Imagem suavizada com sucesso!");
VisualizadorImagem vis = new VisualizadorImagem();//Visualizador
vis.mostraImagem(minhaImagem,nome); //Abre imagem apos a suavizacao para que o usuario a visualize;
}
}
else if (opcao==5){ //suaviza imagem com filtro gaussiano
if (minhaImagem == null)
System.out.println("Carregue uma imagem primeiro!");
else{
System.out.println("Entre um tamanho para a vizinhanca: ");
int tamanho = sc.nextInt();
System.out.println("Entre um sigma (desvio padrao) para a vizinhanca: ");
int sigma = sc.nextInt();
minhaImagem.filtroGaussiano(tamanho, sigma);
System.out.println("Imagem suavizada com sucesso!");
VisualizadorImagem vis = new VisualizadorImagem();//Visualizador
vis.mostraImagem(minhaImagem,nome); //Abre imagem apos a suavizacao para que o usuario a visualize;
}
}
else if (opcao==6){ // grava a imagem
if (minhaImagem == null)//Cancela ação caso não haja imagem carregada.
System.out.println("Carregue uma imagem primeiro!");
else{
String nomeNovo;
while(true){//Laço que pede o nome do novo arquivo, e caso exista um arquivo com o mesmo nome, o usuário é avisado e é dada
//a opção do usuário cancelar ou redigitar o nome do arquivo.
System.out.println("Digite o nome da copia que você deseja salvar sem extenção. Caso deseje cancelar esta ação, aperte somente enter");
sc = new Scanner(System.in);
nomeNovo = sc.nextLine();
if (nomeNovo.equals(""))
break;
Imagem imagemTemp = LeituraEscritaImagem.leImagem(nomeNovo+ ".pgm");//Tenta carregar a imagem, caso retorne nulo, a imagem nao existe.
if (imagemTemp == null)
break;
else{
System.out.println("Ja existe um arquivo com este nome. Caso deseje sobre escreve-lo, digitite 's', caso contrario aperte enter");
sc = new Scanner(System.in);
String opcao2 = sc.nextLine();
if (opcao2.equals("s") || opcao2.equals("S"))
break;
else
System.out.println("Ação cancelada.O arquivo ainda não foi salvo");
}
}
if (!nomeNovo.equals("")){//Caso o usuário tenha apertado enter, a imagem não é gravada.
nomeNovo = nomeNovo + ".pgm";
LeituraEscritaImagem.escreveImagem(nomeNovo, minhaImagem);
System.out.println("Imagem gravada com sucesso! Imagem salva como:"+nomeNovo);
}
}
}
}
}
} | gnsantos/MAC110 | EP3.java | 1,626 | /* MAC 110 - INTRODUCAO A CIENCIA DA COMPUTACAO */ | block_comment | en | true |
143477_2 | import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Bienvenue dans le donjon aventurier !");
// Création du donjon
Donjon donjon = new Donjon();
// Proposition au joueur de choisir une pièce
System.out.println("Choisissez une pièce où entrer (de 1 à 8) : ");
int choix = scan.nextInt();
// Vérification de la validité du choix du joueur
if (choix >= 1 && choix <= 8) {
donjon.entrerPiece(choix);
} else {
System.out.println("Choix invalide. Fin du programme.");
}
scan.close();
}
} | Longuevville/DonjonQuest | main.java | 202 | // Vérification de la validité du choix du joueur | line_comment | en | true |
143837_3 | import java.util.Scanner;
import java.util.ArrayList;
import java.util.Random;
import java.io.Serializable;
public class Player implements java.io.Serializable{
//private String gameClass;
private int lvl;
private int maxExp, exp; //total & current exp, hp, mana
private int maxHp, hp; //each level up adds 10 hp (for now)
private int maxMana, mana; //each point in magic increases mana by 5
private int gold;
//each class begins with 13 stat points distributed,each level up lets you add 3 where you want
private Character p1; //pONE
//items that are equipped
private Item head, body, feet, arms, ring, wep;
//items that are stored as consumables
private Inventory inv;
//magic skills
private Magic magic;
public Player(){
this.magic = new Magic(this);
this.inv = new Inventory(this);
this.head = body = feet = arms = ring = wep = null;
this.lvl = 1;
this.maxExp = 50;
this.exp = gold = 0;
Scanner sc2 = new Scanner(System.in);
int choice;
boolean loop = true;
while (loop) {
System.out.println("\nClass Selection:");
System.out.println("1. Warrior | 2. Rogue | 3. Mage");
choice = sc2.nextInt();
switch(choice){
case 1:
System.out.println("\nWelcome, Warrior.");
p1 = new Warrior();
p1.createChar();
Item i = new Item("Rusty Sword");
equip(i);
this.maxHp = hp = 50;
this.maxMana = mana = 15 + (p1.getMag()*5);
loop = false;
break;
case 2:
System.out.println("\nWelcome, Rogue.");
this.maxHp = hp = 40;
p1 = new Rogue();
p1.createChar();
i = new Item("Rusty Dagger");
equip(i);
this.maxMana = mana = 15 + (p1.getMag()*5);
loop = false;
break;
case 3:
System.out.println("\nWelcome, Mage.");
this.maxHp = hp = 35;
p1 = new Mage();
p1.createChar();
i = new Item("Old Staff");
equip(i);
this.maxMana = mana = 15 + (p1.getMag()*5);
loop = false;
break;
default:
System.out.println("Invalid choice.");
}
}
}
public void showStats(){
System.out.println("\nHP: " + hp + "/" + maxHp +
" | MP: " + mana + "/" + maxMana +
" | Lvl: " + lvl +
" | Exp: " + exp + "/" + maxExp +
" | Gold: " + gold);
System.out.println("STR: " + p1.getStr() + " | " +
"DEF: " + p1.getDef() + " | " +
"WIS: " + p1.getMag() + " | " +
"SPD: " + p1.getSpd() + " | " +
"LCK: " + p1.getLck());
}
public boolean checkExp(){ //to check if character is able to level up
if (exp >= maxExp) {
this.exp = exp - maxExp;
this.levelUp();
return true;
}
else
return false;
}
public void levelUp(){
System.out.println("\nLEVEL UP!");
this.maxHp += 8;
this.hp = maxHp;
this.maxMana += 2;
this.mana = maxMana;
this.maxExp += 8;
this.exp = 0;
Scanner sc3 = new Scanner(System.in);
int points = 3;
int choice;
int allocate;
while (points > 0) {
System.out.println("You have " + points + " stat points to allocate!");
System.out.println("Choose stat to allocate: ");
System.out.println("1. STR | 2. DEF | 3. SPD | 4. WIS | 5.LCK");
choice = sc3.nextInt();
switch(choice){
case 1:
System.out.println("\nHow many points do you want to allocate to Strength?");
allocate = sc3.nextInt();
if (points - allocate < 0) {
System.out.println("\nYou can allocate only " + points + " point(s).");
break;
}
points -= allocate;
p1.setStr(p1.getStr()+allocate);
break;
case 2:
System.out.println("\nHow many points do you want to allocate to Defense?");
allocate = sc3.nextInt();
if (points - allocate < 0) {
System.out.println("\nYou can allocate only " + points + " point(s).");
break;
}
points -= allocate;
p1.setDef(p1.getDef()+allocate);
break;
case 3:
System.out.println("\nHow many points do you want to allocate to Speed?");
allocate = sc3.nextInt();
if (points - allocate < 0) {
System.out.println("\nYou can allocate only " + points + " point(s).");
break;
}
points -= allocate;
p1.setSpd(p1.getSpd()+allocate);
break;
case 4:
System.out.println("\nHow many points do you want to allocate to Magic?");
allocate = sc3.nextInt();
if (points - allocate < 0) {
System.out.println("\nYou can allocate only " + points + " point(s).");
break;
}
points -= allocate;
p1.setMag(p1.getMag()+allocate);
this.maxMana += p1.getMag()*5;
this.mana = maxMana;
break;
case 5:
System.out.println("\nHow many points do you want to allocate to Luck?");
allocate = sc3.nextInt();
if (points - allocate < 0) {
System.out.println("\nYou can allocate only " + points + " point(s).");
break;
}
points -= allocate;
p1.setLck(p1.getLck()+allocate);
break;
default:
System.out.println("\nInvalid choice.");
break;
}
}
this.lvl++;
System.out.println("\nYou are now Level " + lvl + "!");
// learn new magic skill on level 3, 5, 7 (?)
if (lvl == 2) {
magic.learn(0);
}
else if (lvl == 3) {
magic.learn(1);
}
else if (lvl == 4) {
magic.learn(2);
}
}
public void equip(Item i){
if (i.getType().equals("head")) this.head = i;
if (i.getType().equals("body")) this.body = i;
if (i.getType().equals("feet")) this.feet = i;
if (i.getType().equals("arms")) this.arms = i;
if (i.getType().equals("ring")) this.ring = i;
if (i.getType().equals("wep")) this.wep = i;
p1.setStr(p1.getStr() + i.getStr());
p1.setDef(p1.getDef() + i.getDef());
p1.setSpd(p1.getSpd() + i.getSpd());
p1.setMag(p1.getMag() + i.getMag());
p1.setLck(p1.getLck() + i.getLck());
}
public void unequip(String slot){
Item i = getItem(slot);
p1.setStr(p1.getStr() - i.getStr());
p1.setDef(p1.getDef() - i.getDef());
p1.setSpd(p1.getSpd() - i.getSpd());
p1.setMag(p1.getMag() - i.getMag());
p1.setLck(p1.getLck() - i.getLck());
if (slot.equals("head")) this.head = null;
if (slot.equals("body")) this.body = null;
if (slot.equals("feet")) this.feet = null;
if (slot.equals("arms")) this.arms = null;
if (slot.equals("ring")) this.ring = null;
if (slot.equals("wep")) this.wep = null;
}
public Item getItem(String slot){
if (slot.equals("head")) return this.head;
if (slot.equals("body")) return this.body;
if (slot.equals("feet")) return this.feet;
if (slot.equals("arms")) return this.arms;
if (slot.equals("ring")) return this.ring;
if (slot.equals("wep")) return this.wep;
else return null;
}
public void compareItem(Item item) {
String itemType = item.getType();
Item equippedItem = getItem(itemType);
System.out.println("\nEquipped:");
if (equippedItem!=null){ equippedItem.getStats();}
else { System.out.println("Empty\n"); }
System.out.println("Dropped:");
item.getStats();
System.out.println();
}
public Inventory getInv(){ return this.inv;}
public int getHp(){
if (hp <= 0){ return 0;}
else return hp;
}
public void setHp(int x){ this.hp = x;}
public int getMaxHp(){ return this.maxHp;}
public void setMaxHp(int x){ this.maxHp = x;}
public int getMana(){ return this.mana;}
public void setMana(int x){ this.mana = x;}
public int getMaxMana(){ return this.maxMana;}
public void setMaxMana(int x){ this.maxMana = x;}
public int getExp(){ return this.exp;}
public void setExp(int x){ this.exp = x;}
public int getGold(){ return this.gold;}
public void setGold(int x){ this.gold = x;}
public void takeDmg(int x){ hp -= x;}
public String getGameClass(){ return this.p1.getGameClass();}
public Character getChar(){ return this.p1;}
public Magic getMagic() {return this.magic;}
public void showEquipped(){ //shows equipped items
if (getItem("head") != null){ System.out.println("Head: " + head.getDesc());}
else System.out.println("Head: Empty");
if (getItem("body") != null){ System.out.println("Body: " + body.getDesc());}
else System.out.println("Body: Empty");
if (getItem("arms") != null){ System.out.println("Arms: " + arms.getDesc());}
else System.out.println("Arms: Empty");
if (getItem("feet") != null){ System.out.println("Feet: " + feet.getDesc());}
else System.out.println("Feet: Empty");
if (getItem("ring") != null){ System.out.println("Ring: " + ring.getDesc());}
else System.out.println("Ring: Empty");
if (getItem("wep") != null){ System.out.println("Weapon: " + wep.getDesc());}
else System.out.println("Weapon: Empty");
}
public boolean evadeP(Player player){
Random r = new Random();
int rand = r.nextInt(100); //0-99
rand += (p1.getSpd()*3);
if (rand >= 90) return true; //initial 10% chance to evade, increases with speed
else return false;
}
public boolean critP(Player p){
Random r = new Random();
int rand = r.nextInt(100); //initial 10% chance to crit, increases with luck
rand += (p.getChar().getLck()*3);
if (rand >= 90) return true;
else return false;
}
public boolean playerDead(Player p){ //return true if player health is <= 0
if (p.getHp() <= 0){
System.out.println("\n--------\nYOU DIED\n--------");
return true;
}
else return false;
}
} | marwahaha/Text-Adventure-in-the-Making | Player.java | 3,024 | //each point in magic increases mana by 5
| line_comment | en | true |
144161_3 | import java.util.*;
public class Main {
// 이진 탐색 소스코드 구현(반복문)
public static int binarySearch(int[] arr, int target, int start, int end) {
while (start <= end) {
int mid = (start + end) / 2;
// 찾은 경우 중간점 인덱스 반환
if (arr[mid] == target) return mid;
// 중간점의 값보다 찾고자 하는 값이 작은 경우 왼쪽 확인
else if (arr[mid] > target) end = mid - 1;
// 중간점의 값보다 찾고자 하는 값이 큰 경우 오른쪽 확인
else start = mid + 1;
}
return -1;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// N(가게의 부품 개수)
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
// 이진 탐색을 수행하기 위해 사전에 정렬 수행
Arrays.sort(arr);
// M(손님이 확인 요청한 부품 개수)
int m = sc.nextInt();
int[] targets = new int[n];
for (int i = 0; i < m; i++) {
targets[i] = sc.nextInt();
}
// 손님이 확인 요청한 부품 번호를 하나씩 확인
for (int i = 0; i < m; i++) {
// 해당 부품이 존재하는지 확인
int result = binarySearch(arr, targets[i], 0, n - 1);
if (result != -1) {
System.out.print("yes ");
}
else {
System.out.print("no ");
}
}
}
} | imsong97/python-for-coding-test | 7/5.java | 471 | // 중간점의 값보다 찾고자 하는 값이 큰 경우 오른쪽 확인 | line_comment | en | true |
144288_1 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Worm here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Worm extends Actor
{
/**
* Act - do whatever the Worm wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
// Add your action code here.
}
}
| BHASVIC-CesareMasset23/Java-projects | Greenfoot/modern-crab/Worm.java | 127 | /**
* Write a description of class Worm here.
*
* @author (your name)
* @version (a version number or a date)
*/ | block_comment | en | true |
144751_1 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class DoorTop here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class DoorTop extends Mover
{
/**
* Act - do whatever the DoorTop wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
applyVelocity();
setImage("door_closedTop.png");
openDoorTop();
}
public void openDoorTop()
{
if(getWorld().getObjects(Key.class).size()== 0){
setImage("door_openTop.png");
}
}
}
| ROCMondriaanTIN/project-greenfoot-game-SBechoe | DoorTop.java | 183 | /**
* Write a description of class DoorTop here.
*
* @author (your name)
* @version (a version number or a date)
*/ | block_comment | en | true |
144912_6 | import java.util.Map;
public class App {
// calcule le prix payé par l'utilisateur dans le restaurant, en fonction de type de
// repas qu'il prend (assiette ou sandwich), de la taille de la boisson (petit, moyen, grand), du dessert et
// de son type (normal ou special) et si il prend un café ou pas (yes ou no).
// les prix sont fixes pour chaque type de chose mais des réductions peuvent s'appliquer
// si cela rentre dans une formule!
public int Compute(String type, String name, String size, String dsize, String coffee) {
// prix total à payer pour le client
int total = 0;
// le type ne peut être vide car le client doit déclarer au moins un repas
if (type == null || name == null || type.isEmpty() || name.isEmpty()) return -1;
// si le client prends un plat en assiette
if (type.equals("assiette")) {
total += 15;
// ainsi qu'une boisson de taille:
if (size == "petit") {
total += 2;
// dans ce cas, on applique la formule standard
if (dsize.equals("normal")) {
// pas de formule
// on ajoute le prix du dessert normal
total += 2;
} else {
// sinon on rajoute le prix du dessert special
total += 4;
}
// si on prends moyen
} else if (size=="moyen") {
total += 3;
// dans ce cas, on applique la formule standard
if (dsize.equals("normal")) {
// j'affiche la formule appliquée
System.out.print("Prix Formule Standard appliquée ");
// le prix de la formule est donc 18
total = 18;
} else {
// sinon on rajoute le prix du dessert special
total += 4;
}
} else if (size=="grand") {
total += 4;
// dans ce cas, on applique la formule standard
if (dsize.equals("normal")) {
// pas de formule
// on ajoute le prix du dessert normal
total += 2;
} else {
// dans ce cas on a la fomule max
System.out.print("Prix Formule Max appliquée ");
total = 21;
}
}
}
// mode sandwich
else {
total += 10;
// ainsi qu'une boisson de taille:
if (size == "petit") {
total += 2;
// dans ce cas, on applique la formule standard
if (dsize.equals("normal")) {
// pas de formule
// on ajoute le prix du dessert normal
total += 2;
} else {
// sinon on rajoute le prix du dessert special
total += 4;
}
// si on prends moyen
} else if (size=="moyen") {
total += 3;
// dans ce cas, on applique la formule standard
if (dsize.equals("normal")) {
// j'affiche la formule appliquée
System.out.print("Prix Formule Standard appliquée ");
// le prix de la formule est donc 13
total = 13;
} else {
// sinon on rajoute le prix du dessert special
total += 4;
}
} else if (size=="grand") {
total += 4;
// dans ce cas, on applique la formule standard
if (dsize.equals("normal")) {
// pas de formule
// on ajoute le prix du dessert normal
total += 2;
} else {
// dans ce cas on a la fomule max
System.out.print("Prix Formule Max appliquée ");
total = 16;
}
}
}
if (type.equals("assiette") && size.equals("moyen") && dsize.equals("normal") && coffee.equals("yes")) {
System.out.print(" avec café offert!");
} else {
// Assume coffee costs 1 unit, adding to the total only if coffee is not included
if (!coffee.equals("yes")) {
total += 1;
}
}
return total;
}
} | GetMetamorph/Exo2-DK | App.java | 1,057 | // le type ne peut être vide car le client doit déclarer au moins un repas | line_comment | en | true |
145121_0 | /******************************************************************************
* Compilation: javac Charge.java
* Execution: java Charge x y
*
******************************************************************************/
public class Charge {
private double rx, ry; // position
private double q; // charge
// constructor
public Charge(double x0, double y0, double q0) {
rx = x0;
ry = y0;
q = q0;
}
// public method
public double potentialAt(double x, double y) {
double k = 8.99e09;
double dx = x - rx;
double dy = y - ry;
return k * q / Math.sqrt(dx*dx + dy*dy);
}
public String toString() {
return q + " at " + "(" + rx + ", " + ry + ")";
}
public static void main(String[] args) {
double x = Double.parseDouble(args[0]);
double y = Double.parseDouble(args[1]);
Charge c1 = new Charge(.51, .63, 21.3);
Charge c2 = new Charge(.13, .94, 81.9);
System.out.println(c1);
System.out.println(c2);
double v1 = c1.potentialAt(x, y);
double v2 = c2.potentialAt(x, y);
StdOut.println(v1+v2);
}
}
| yalechang/java_projects | Charge.java | 327 | /******************************************************************************
* Compilation: javac Charge.java
* Execution: java Charge x y
*
******************************************************************************/ | block_comment | en | true |
145384_15 | import java.util.ArrayList;
/**
* Represents a hand of cards.
*
* @since Fall 2023
* @author Chris Sorros and Michael Plekan
*/
public class Hand {
public ArrayList<Card> hand;
/**
* Constructs a hand with no cards.
*/
public Hand() {
this.hand = new ArrayList<Card>();
}
/**
* Constructs a hand with the given cards.
*
* @param cards the cards to add to the hand
*/
public Hand(Card ...cards) {
this.hand = new ArrayList<Card>();
// Add the cards to the hand
for (Card card : cards) {
this.hand.add(card);
}
}
/**
* Returns the card at the given index.
*
* @param index the index of the card to get.
*
* @return the card at the given index.
*/
public Card getCard(int index){
return hand.get(index);
}
/**
* Adds a card to the hand.
*
* @param card the card to add
*/
public void addCard(Card card) {
this.hand.add(card);
}
/**
* Returns the value of the hand.
*
* @return the value of the hand.
*/
public int getValue() {
int value = 0;
for (Card card : hand) {
value += card.value;
}
return value;
}
/**
* Returns the soft value of the hand.
*
* @return the soft value of the hand
*/
public int getSoftValue() {
int value = 0;
for (Card card : hand) {
// If the card is an ace, add 1 instead of 11
value += card.value != 11 ? card.value : 1;
}
return value;
}
/**
* Returns if the hand is a bust.
*
* @return if the hand is a bust
*/
public boolean isBust() {
return getValue() > 21;
}
/**
* Returns if the hand is a blackjack.
*
* @return if the hand is a blackjack
*/
public boolean isBlackjack() {
return getValue() == 21;
}
/**
* Returns if the hand is a soft hand.
*
* @return if the hand is a soft hand.
*/
public boolean isSoft() {
//check each card in the hand to see if it is an ace
//if it is an ace, return true
//if not, return false
for (int i = 0; i < hand.size(); i++) {
if (hand.get(i).name.equals("Ace")) {
return true;
}
}
return false;
}
/**
* Returns if the hand is a pair.
*
* @return if the hand is a pair.
*/
public boolean isPair() {
if (hand.get(0).value == hand.get(1).value) {
return true;
}
return false;
}
/**
* Returns the string representation of the hand.
*
* @return the string representation of the hand
*/
@Override
public String toString() {
return "" + hand;
}
} | DarrenLim4/BlackjackBot | Hand.java | 747 | /**
* Returns if the hand is a pair.
*
* @return if the hand is a pair.
*/ | block_comment | en | false |
145771_0 | /* SELF ASSESSMENT
1. Did I use easy-to-understand meaningful variable names formatted properly (in lowerCamelCase)?
Mark out of 5: 5
Yes I did use easy to understand variable names.
2. Did I indent the code appropriately?
Mark out of 5: 5
Yes.
3. Did I write the initialiseHighScores function correctly (parameters, return type and function body) and invoke it correctly?
Mark out of 15: 15
Yes.I did
4. Did I write the printHighScores function correctly (parameters, return type and function body) and invoke it correctly?
Mark out of 15: 15
Yes I wrote the printHighScores function properly.
5. Did I write the higherThan function correctly (parameters, return type and function body) and invoke it correctly?
Mark out of 15: 15
Yeah I wrote this function correctly too.
6. Did I write the insertScore function correctly (parameters, return type and function body) and invoke it correctly?
Mark out of 20:20
Yes. I wrote this function too without a problem.
7. Did I write the main function body correctly (first asking for the number of scores to be maintained and then repeatedly asking for scores)?
Mark out of 20: 10
I could not figure out how to maintain a number of scores the user wished to maintain however I was able to repeatedly ask for scores.
8. How well did I complete this self-assessment?
Mark out of 5:5
I completed this self assessment well.
Total Mark out of 100 (Add all the previous marks):
*/
import java.util.Scanner;
public class highScores
{
public static int MAX_NUMBER_OF_SCORES = 5;
public static boolean isHigherThan = false;
public static double score;
public static int numberOfScores;
public static double[] highScoreList = new double[MAX_NUMBER_OF_SCORES];
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter your score");
while(numberOfScores<=MAX_NUMBER_OF_SCORES&& numberOfScores >= 0 )
{
try {
if(input.hasNext("reset"))
{
initialiseHighScores( highScoreList);
numberOfScores = 0;
input.next();
System.out.println("Please enter your next score");
}
else
{
score = input.nextDouble();
try
{
highScoreList[numberOfScores] = score;
}
catch(java.lang.ArrayIndexOutOfBoundsException highScoreList)
{
}
numberOfScores++;
higherThan(highScoreList,score);
insertScore(highScoreList, score);
printHighScores(highScoreList);
System.out.println("Please enter your next score");
}
}
catch(java.util.InputMismatchException score)
{
System.out.println("Error: You entered a letter. Please enter any numeric score");
input.next();
}
}
input.close();
}
public static double[] initialiseHighScores( double[] highScoreList)
{
java.util.Arrays.fill(highScoreList, 0, MAX_NUMBER_OF_SCORES, 0);
return highScoreList;
}
public static double[] printHighScores(double[] highScoreList)
{
int count = 1;
System.out.println("The highscores are : ");
while(score >= 0 && count <= 5)
{
switch(count)
{
case 1:
System.out.println(count + ": " + highScoreList[0] );
count++;
break;
case 2:
System.out.println(count + ": " + highScoreList[1] );
count++;
break;
case 3:
System.out.println(count + ": " + highScoreList[2] );
count++;
break;
case 4:
System.out.println(count + ": " + highScoreList[3] );
count++;
break;
case 5:
System.out.println(count + ": " + highScoreList[4] );
count++;
break;
}
}
return highScoreList;
}
public static boolean higherThan(double[] highScoreList,double score)
{
if(score > highScoreList[4])
{
isHigherThan = true;
}
else
{
isHigherThan = false;
}
return isHigherThan;
}
public static void insertScore(double[] highScoreList,double score)
{
if(isHigherThan = true)
{
if(score > highScoreList[0])
{
highScoreList[4] = highScoreList[3];
highScoreList[3] = highScoreList[2];
highScoreList[2] = highScoreList[1];
highScoreList[1] = highScoreList[0];
highScoreList[0] = score;
}
else if(score > highScoreList[1] && score< highScoreList[0])
{
highScoreList[4] = highScoreList[3];
highScoreList[3] = highScoreList[2];
highScoreList[2] = highScoreList[1];
highScoreList[1] = score;
}
else if(score > highScoreList[2] && score< highScoreList[1])
{
highScoreList[4] = highScoreList[3];
highScoreList[3] = highScoreList[2];
highScoreList[2] = score;
}
else if(score > highScoreList[3] && score< highScoreList[2])
{
highScoreList[4] = highScoreList[3];
highScoreList[3] = score;
}
else if(score > highScoreList[4] && score< highScoreList[3] )
{
highScoreList[4] = score;
}
}
}
}
| Alantrivandrum/My_Java_Projects | highScores.java | 1,528 | /* SELF ASSESSMENT
1. Did I use easy-to-understand meaningful variable names formatted properly (in lowerCamelCase)?
Mark out of 5: 5
Yes I did use easy to understand variable names.
2. Did I indent the code appropriately?
Mark out of 5: 5
Yes.
3. Did I write the initialiseHighScores function correctly (parameters, return type and function body) and invoke it correctly?
Mark out of 15: 15
Yes.I did
4. Did I write the printHighScores function correctly (parameters, return type and function body) and invoke it correctly?
Mark out of 15: 15
Yes I wrote the printHighScores function properly.
5. Did I write the higherThan function correctly (parameters, return type and function body) and invoke it correctly?
Mark out of 15: 15
Yeah I wrote this function correctly too.
6. Did I write the insertScore function correctly (parameters, return type and function body) and invoke it correctly?
Mark out of 20:20
Yes. I wrote this function too without a problem.
7. Did I write the main function body correctly (first asking for the number of scores to be maintained and then repeatedly asking for scores)?
Mark out of 20: 10
I could not figure out how to maintain a number of scores the user wished to maintain however I was able to repeatedly ask for scores.
8. How well did I complete this self-assessment?
Mark out of 5:5
I completed this self assessment well.
Total Mark out of 100 (Add all the previous marks):
*/ | block_comment | en | true |
146943_17 | /*
* 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 view;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.List;
import javax.swing.JOptionPane;
import model.Admin;
import model.Employees;
import model.Opinions;
import service.AdminService;
import service.EmployeeService;
import service.OpinionService;
/**
*
* @author GANZA
*/
public class OpinionsForm extends javax.swing.JFrame {
/**
* Creates new form OpinionsForm
*/
public OpinionsForm() {
initComponents();
}
// private void addItemCombo(){
// try{
// Registry theRegistry =LocateRegistry.getRegistry("127.0.0.1",5000);
// EmployeeService service=(EmployeeService) theRegistry.lookup("employee");
// List<Employees> theEmployees=service.allEmployees();
// for (Employees employee :theEmployees ){
// employeecombo.addItem(employee);
// }
// }catch(Exception ex){
// ex.printStackTrace();
// }
//}
/**
* 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() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
namesTxt = new javax.swing.JTextField();
telnumberTxt = new javax.swing.JTextField();
emailTxt = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
opinionTxt = new javax.swing.JTextArea();
registerBtn = new javax.swing.JButton();
jLabel6 = new javax.swing.JLabel();
eidTxt = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Opinions Form");
jLabel2.setText("Names");
jLabel3.setText("Tel Number");
jLabel4.setText("Email");
jLabel5.setText("Opinion");
opinionTxt.setColumns(20);
opinionTxt.setRows(5);
jScrollPane1.setViewportView(opinionTxt);
registerBtn.setText("Submit");
registerBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
registerBtnActionPerformed(evt);
}
});
jLabel6.setText("Employees");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(226, 226, 226)
.addComponent(jLabel1))
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(jLabel2))
.addGap(49, 49, 49)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6)
.addComponent(jLabel5))
.addGap(23, 23, 23)))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(emailTxt)
.addComponent(namesTxt)
.addComponent(telnumberTxt)
.addComponent(eidTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 104, Short.MAX_VALUE))))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(139, 139, 139)
.addComponent(registerBtn)))
.addContainerGap(320, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(39, 39, 39)
.addComponent(jLabel1)
.addGap(59, 59, 59)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(namesTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel6)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(telnumberTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(emailTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(eidTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(31, 31, 31)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel5)
.addGap(53, 279, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(registerBtn)
.addGap(64, 64, 64))))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void registerBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_registerBtnActionPerformed
// Validations
try {
// Validations
String names = namesTxt.getText();
String telNumberText = telnumberTxt.getText();
String email = emailTxt.getText();
String opinion = opinionTxt.getText();
String eidText = eidTxt.getText();
if (names.isEmpty() || telNumberText.isEmpty() || email.isEmpty() || opinion.isEmpty() || eidText.isEmpty()) {
JOptionPane.showMessageDialog(this, "Please fill in all fields.");
return;
}
int telNumber;
int eid;
try {
telNumber = Integer.parseInt(telNumberText);
eid = Integer.parseInt(eidText);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "Invalid numeric input for Tel Number or EID.");
return;
}
// RMI
Registry theRegistry = LocateRegistry.getRegistry("127.0.0.1", 5000);
OpinionService service = (OpinionService) theRegistry.lookup("opinion");
// Create Opinions object
Opinions theEmployee = new Opinions();
theEmployee.setNames(names);
theEmployee.setTelNumber(telNumber);
theEmployee.setEmail(email);
theEmployee.setOpinion(opinion);
// theEmployee.setEid(eid);
// Remote call
Opinions empObj = service.registerOpinion(theEmployee);
if (empObj != null) {
JOptionPane.showMessageDialog(this, "Data Saved");
} else {
JOptionPane.showMessageDialog(this, "Data not Saved");
}
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "An error occurred: " + ex.getMessage());
}
}//GEN-LAST:event_registerBtnActionPerformed
/**
* @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(OpinionsForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(OpinionsForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(OpinionsForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(OpinionsForm.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 OpinionsForm().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField eidTxt;
private javax.swing.JTextField emailTxt;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField namesTxt;
private javax.swing.JTextArea opinionTxt;
private javax.swing.JButton registerBtn;
private javax.swing.JTextField telnumberTxt;
// End of variables declaration//GEN-END:variables
}
| Kami-christella/Stock-Management-System-Client-Side | src/view/OpinionsForm.java | 2,969 | // </editor-fold>//GEN-END:initComponents | line_comment | en | true |
147014_1 | package pull_model;
import java.util.ArrayList;
/**
* Abstract agent class with no established behavior, to be used in {@link Dynamics}.
*
* To define a behavior, one only needs to extend this class and provide
* implementation for the {@link update(ArrayList) update} method.
*
* @param <T> The type of opinions handled by the agent.
*/
public abstract class Agent<T> {
/**
* The sample size required by the agent.
*/
public final int sampleSize;
/**
* The opinion of the agent.
*/
protected T opinion;
/**
* Constructs an agent with the specified sample size and initial opinion.
*
* @param sampleSize The sample size required by the agent.
* @param initialOpinion The inital opinion of the agent.
*/
public Agent(int sampleSize, T initialOpinion) {
this.sampleSize = sampleSize;
this.opinion = initialOpinion;
}
/**
* Returns the opinion of the agent.
*/
public T output() {
return opinion;
}
/**
* Updates the opinion and memory state of the agent depending on an opinion sample.
* This method must be implemented to define the dynamics.
* @param samples Contains a collections of opinions whose size is always equal to {@link sampleSize}.
*/
public abstract void update(ArrayList<T> samples);
}
| RobinVacus/research | src/pull_model/Agent.java | 331 | /**
* The sample size required by the agent.
*/ | block_comment | en | false |
147348_0 | /**
* miniJava Abstract Syntax Tree classes
* @author prins
* @version COMP 520 (v2.2)
*/
package miniJava.AbstractSyntaxTrees;
import miniJava.SyntacticAnalyzer.SourcePosition;
public abstract class AST {
public AST (SourcePosition posn) {
this.posn = posn;
}
public String toString() {
String fullClassName = this.getClass().getName();
String cn = fullClassName.substring(1 + fullClassName.lastIndexOf('.'));
if (ASTDisplay.showPosition)
cn = cn + " " + posn.toString();
return cn;
}
public abstract <A,R> R visit(Visitor<A,R> v, A o);
public SourcePosition posn;
}
| kekevi/miniJava-compiler | src/miniJava/AbstractSyntaxTrees/AST.java | 179 | /**
* miniJava Abstract Syntax Tree classes
* @author prins
* @version COMP 520 (v2.2)
*/ | block_comment | en | false |
147706_5 | public class Account implements java.io.Serializable {
private String number; // 4 digit string
private double balance;
private boolean active;
private int array_number;
private boolean type;
int interest = 5;
public Account(int Account_Number, int total_accounts) {
String Accnt_Num = String.valueOf(Account_Number);
this.number = Accnt_Num;
this.balance = 0;
this.active = true;
this.array_number = total_accounts;
}
//This Method Just Prints Out Account Info and returns the Array Number
int info(){
System.out.println("Account number: " + this.number);
System.out.println("Account balance: " + this.balance);
System.out.println("Active?: " + this.active);
//System.out.println("array number: " + this.array_number);
return this.array_number;
}
//This Method Updates the Deposit Balance for This Account
void addDeposit(double deposit){
System.out.println("\n**Account balance updated**");
this.balance = this.balance + deposit;
this.info();
}
//This Method Updates the Withdraw Balance for This Account
void subWithdraw(double withdraw){
if (withdraw > this.balance){
System.out.println("\nInsufficient Funds!");
}else{
System.out.println("\n**Account balance updated**");
this.balance = this.balance - withdraw;
this.info();
}
}
//This Method Adds To the Balance (Every 5 transactions) The Interest Rate for All Savings Accounts
void addInterest(){
this.balance = this.balance + this.balance * this.interest/100;
}
////////////////////////////////////////////////////////////////////////////////
// Simple Getters and Setters //
////////////////////////////////////////////////////////////////////////////////
int getArray() {
return array_number;
}
String getNumber() {
return this.number;
}
public double getBalance() {
return this.balance;
}
boolean getType() {
return type;
}
void setTypeSavings() {
this.type = true;
}
void setTypeChecking() {
this.type = false;
}
void setActiveFalse() {
this.active = false;
this.balance = 0;
}
boolean getActive() {
return this.active;
}
} | saxena-arpit/ATM-Management-System | p2/Account.java | 607 | //This Method Adds To the Balance (Every 5 transactions) The Interest Rate for All Savings Accounts | line_comment | en | false |
147996_7 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
import java.awt.geom.*;
//Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
public class commons {
//things to do
//2d boards/circular array/torus
//more advanced data structure
static void common_lines(){
NumberFormat num=NumberFormat.getInstance();
num.setMinimumFractionDigits(3);
num.setMaximumFractionDigits(3);
num.setGroupingUsed(false);
}
public static int digit_sum(int n, int b){
int s = 0;
while(n!=0){
s+=n%b;
n/=b;
}
return s;
}
public static double angle(double x, double y){
if(x>0&&y>=0){
return Math.atan(y/x);
}
if(x>0&&y<0){
return Math.atan(y/x)+2.0*Math.PI;
}
if(x<0){
return Math.atan(y/x)+Math.PI;
}
if(x==0&&y<0){
return 1.5*Math.PI;
}
if(x==0&&y>0){
return Math.PI*0.5;
}
return 0.0;
}
static int[] prime_list(int n){
ArrayList<Integer> a = new ArrayList<Integer>();
for(int i=2;i<=n;i++)
if(isPrime(i)) a.add(i);
int[] r = new int[a.size()];
for(int i=0;i<a.size();i++)
r[i] = a.get(i);
return r;
}
static boolean isPrime(int d){
return BigInteger.valueOf(d).isProbablePrime(32);
}
//likely not useful, java can run for 2 min
static int[] prime_seive(int n){
ArrayList<Integer> p = new ArrayList<Integer>();
boolean[] isPrime = new boolean[n + 1];
for (int i = 2; i <= n; i++) {
isPrime[i] = true;
}
for (int i = 2; i*i <= n; i++) {
if (isPrime[i]) {
for (int j = i; i*j <= n; j++) {
isPrime[i*j] = false;
}
}
}
for (int i = 2; i <= n; i++) {
if (isPrime[i]) {
p.add(i);
}
}
int[] b = new int[p.size()];
for(int i=0;i<b.length;i++){
b[i] = p.get(i);
}
return b;
}
public static int sum(int[] a){
int sum = 0;
for(int i=0;i<a.length;i++){
sum+=a[i];
}
return sum;
}
public static int prod(int[] a){
return prodmod(a,2147483647);
}
public static int prodmod(int[] a, int k){
int prod = 1;
for(int i=0;i<a.length;i++){
prod*=(a[i]%k);
prod%=k;
}
return prod;
}
public static long prod(long[] a){
return prodmod(a,9223372036854775807L);
}
public static long prodmod(long[] a, long k){
long prod = 1;
for(int i=0;i<a.length;i++){
prod*=(a[i]%k);
prod%=k;
}
return prod;
}
static String lastkdigit(int n,int k){
String s = padleft(Integer.toString(n),k,'0');
return s.substring(s.length()-k);
}
//pad the string with a character if length < n, O(n^2)
static String padleft(String s, int n, char c){
return n<=s.length()?s:c+padleft(s,n-1,c);
}
//thx to
static String reverse(String s){
return (new StringBuilder(s)).reverse().toString();
}
//repeat the string n time, for example repeat("ab",3) = "ababab", O(|a|n^2)
static String repeat(String a, int n){
return n<1?"":a+repeat(a,n-1);
}
//check if the character is alphanumberic, O(1)
static boolean isAlphaNumeric(char c){
return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".indexOf(c)!=-1;
}
//check if a regular expression matches the entire string. O(|s|)
static boolean regex(String s,String p){
return Pattern.compile(p).matcher(s).matches();
}
//input should be a sorted list of points of the polygonal chain that forms a polygon, exclude the last point
static double polygonArea(ArrayList<Point2D> a){
double s=0;
a.add(a.get(0));
for(int i=0;i<a.size()-1;i++){
s+=a.get(i).getX()*a.get(i+1).getY()-a.get(i+1).getX()*a.get(i).getY();
}
a.remove(a.size()-1);
return 0.5*s;
}
static int gcd(int a, int b){
return a%b==0?b:gcd(b,a%b);
}
static int c(int[][] m, int x, int y){
return m[m.length-(x%m.length)][m[0].length-(y%m.length)];
}
static int c(int[] m, int x){
return m[m.length-(x%m.length)];
}
static void p(int[] a){
for(int i=0;i<a.length;i++){
System.out.print(a[i]+" ");
}
System.out.println();
}
public static int nextInt(InputStream in){
int ret = 0;
boolean dig = false;
try {
for (int c = 0; (c = in.read()) != -1; ) {
if (c >= '0' && c <= '9') {
dig = true;
ret = ret * 10 + c - '0';
} else if (dig) break;
}
} catch (IOException e) {}
return ret;
}
@SuppressWarnings({"unchecked"})
public static <E> E[] CollectionToArray(Collection<E> c){
E[] a =(E[]) new Object[c.size()];
Iterator itr = c.iterator();
int i=0;
while(itr.hasNext()){
a[i] = (E) itr.next();
i++;
}
return a;
}
}
class sorttemplate implements Comparator<int[]>{
public int compare(int[] o1, int[] o2) {
if(o1[0]>o2[0]){
return 1;
}
if(o1[0]<o2[0]){
return -1;
}
return 0;
}
}
class sorttemplate2 implements Comparator<int[]>{
public int compare(int[] o1, int[] o2) {
for(int i=0;i<o1.length;i++){
if(o1[i]>o2[i]){
return 1;
}
if(o1[i]<o2[i]){
return -1;
}
}
return 0;
}
}
//untested
class UnionFind {
int[] s;
UnionFind(int n){
s = new int[n];
for(int i=0;i<n;i++){
s[i]=i;
}
}
public int find(int x){
if(s[x]==x){
return x;
}
s[x]=find(s[x]);
return s[x];
}
public void union(int x, int y){
s[find(x)] = find(y);
}
} | chaoxu/mgccl-oj | commons.java | 2,142 | //repeat the string n time, for example repeat("ab",3) = "ababab", O(|a|n^2) | line_comment | en | false |
148196_6 | /*
* Salwa Abdalla
* ICS3U Culminating Assignment: 1/21/2019
* Jeff Radulovic
*
* The search class is a collection of methods that take in an array list and
* some sort of string or integer and search through a specific aspect. For example
* the employee number or perhaps the username or password
*
*/
import java.util.ArrayList;
public class Search {
/**
* @param Employee_List
* @param EmployeeNum
* @return index of Employee according to filter
*/
public int searchIndexEmployees(ArrayList<Employees> Employee_List, String EmployeeNum) {
for (int i = 0; i < Employee_List.size(); i++) {
if (Employee_List.get(i).getEmployeeNum().equals(EmployeeNum))
return i;
}
return -1;
}
/**
* @param Employee_List
* @param username
* @param password
* @return
*/
public int searchIndexEmployees(ArrayList<Employees> Employee_List, String username, String password) {
for (int i = 0; i < Employee_List.size(); i++) {
if (Employee_List.get(i).getUsername().equals(username) && Employee_List.get(i).getPassword().equals(password))
return i;
}
return -1;
}
/**
* @param JobList_List
* @param JobTitle
* @return index of Job according to filter
*/
public int searchIndexJob(ArrayList<JobList> JobList_List, String JobTitle) {
for (int i = 0; i < JobList_List.size(); i++) {
if (JobList_List.get(i).getJobTitle().toLowerCase().equals(JobTitle.toLowerCase()))
return i;
}
return -1;
}
/**
* @param Location
* @param JobList_List
* @return all of the Job that fit the location
*/
public ArrayList<JobList> searchIndexJob(String Location, ArrayList<JobList> JobList_List) {
ArrayList<JobList> filtered = new ArrayList<JobList>();
for (int i = 0; i < JobList_List.size(); i++) {
if (JobList_List.get(i).getLocation().toLowerCase().equals(Location.toLowerCase()))
filtered.add(JobList_List.get(i));
}
return filtered;
}
/**
* @param JobList_List
* @param Availability
* @return index of Job according to filter
*/
public int searchIndexJob(ArrayList<JobList> JobList_List, boolean Availability) {
for (int i = 0; i < JobList_List.size(); i++) {
if (JobList_List.get(i).isAvailable() == Availability)
return i;
}
return -1;
}
/**
* @param JobList_List
* @param Wage
* @return index of Job according to filter
*/
public int searchIndexJob(ArrayList<JobList> JobList_List, double Wage) {
for (int i = 0; i < JobList_List.size(); i++) {
if (JobList_List.get(i).getWage() >= Wage)
return i;
}
return -1;
}
}
| sms-sudo/government-website-simulation | Search.java | 814 | /**
* @param JobList_List
* @param Wage
* @return index of Job according to filter
*/ | block_comment | en | true |
148558_1 | #ifdef J2ME
#define JAVAME
#endif /* J2ME */
/*
This is a port of the Swiss Ephemeris Free Edition, Version 2.00.00
of Astrodienst AG, Switzerland from the original C Code to Java. For
copyright see the original copyright notices below and additional
copyright notes in the file named LICENSE, or - if this file is not
available - the copyright notes at http://www.astro.ch/swisseph/ and
following.
For any questions or comments regarding this port to Java, you should
ONLY contact me and not Astrodienst, as the Astrodienst AG is not involved
in this port in any way.
Thomas Mack, [email protected], 23rd of April 2001
*/
/* Copyright (C) 1997 - 2008 Astrodienst AG, Switzerland. All rights reserved.
License conditions
------------------
This file is part of Swiss Ephemeris.
Swiss Ephemeris is distributed with NO WARRANTY OF ANY KIND. No author
or distributor accepts any responsibility for the consequences of using it,
or for whether it serves any particular purpose or works at all, unless he
or she says so in writing.
Swiss Ephemeris is made available by its authors under a dual licensing
system. The software developer, who uses any part of Swiss Ephemeris
in his or her software, must choose between one of the two license models,
which are
a) GNU public license version 2 or later
b) Swiss Ephemeris Professional License
The choice must be made before the software developer distributes software
containing parts of Swiss Ephemeris to others, and before any public
service using the developed software is activated.
If the developer choses the GNU GPL software license, he or she must fulfill
the conditions of that license, which includes the obligation to place his
or her whole software project under the GNU GPL or a compatible license.
See http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
If the developer choses the Swiss Ephemeris Professional license,
he must follow the instructions as found in http://www.astro.com/swisseph/
and purchase the Swiss Ephemeris Professional Edition from Astrodienst
and sign the corresponding license contract.
The License grants you the right to use, copy, modify and redistribute
Swiss Ephemeris, but only under certain conditions described in the License.
Among other things, the License requires that the copyright notices and
this notice be preserved on all copies.
Authors of the Swiss Ephemeris: Dieter Koch and Alois Treindl
The authors of Swiss Ephemeris have no control or influence over any of
the derived works, i.e. over software or services created by other
programmers which use Swiss Ephemeris functions.
The names of the authors or of the copyright holder (Astrodienst) must not
be used for promoting any software, product or service which uses or contains
the Swiss Ephemeris. This copyright notice is the ONLY place where the
names of the authors can legally appear, except in cases where they have
given special permission in writing.
The trademarks 'Swiss Ephemeris' and 'Swiss Ephemeris inside' may be used
for promoting such software, products or services.
*/
package swisseph;
/**
* A class to contain all the data that are relevant to houses in astrology.
* Does not seem to be relevant outside this package...
* <P><I><B>You will find the complete documentation for the original
* SwissEphemeris package at <A HREF="http://www.astro.ch/swisseph/sweph_g.htm">
* http://www.astro.ch/swisseph/sweph_g.htm</A>. By far most of the information
* there is directly valid for this port to Java as well.</B></I>
* @version 1.0.0a
*/
class Houses
#ifndef JAVAME
implements java.io.Serializable
#endif /* JAVAME */
{
/**
* The twelve house cusps from cusp[1] to cusp[12] plus many additional
* points.
*/
double cusp[]=new double[37];
/**
* The double value of the ascendant.
*/
double ac;
/**
* The double value of the MC (=Medium Coeli = the midpoint of the heaven).
*/
double mc;
/**
* The double value of the vertex.
*/
double vertex;
/**
* The double value of the "equatorial ascendant".
*/
double equasc;
/**
* The double value of the "co-ascendant" (Walter Koch).
*/
double coasc1;
/**
* The double value of the "co-ascendant" (Michael Munkasey).
*/
double coasc2;
/**
* The double value of the "polar ascendant" (Michael Munkasey).
*/
double polasc;
#ifdef TRACE0
Houses() {
Trace.log("Houses()");
}
#endif /* TRACE0 */
}
| arturania/swisseph | java/swesrc/Houses.pre | 1,209 | /*
This is a port of the Swiss Ephemeris Free Edition, Version 2.00.00
of Astrodienst AG, Switzerland from the original C Code to Java. For
copyright see the original copyright notices below and additional
copyright notes in the file named LICENSE, or - if this file is not
available - the copyright notes at http://www.astro.ch/swisseph/ and
following.
For any questions or comments regarding this port to Java, you should
ONLY contact me and not Astrodienst, as the Astrodienst AG is not involved
in this port in any way.
Thomas Mack, [email protected], 23rd of April 2001
*/ | block_comment | en | true |
148965_0 | // Intro- Seems like the JVM has gone mad, printing random integers.
// Details- https://blog.jooq.org/2013/10/17/add-some-entropy-to-your-jvm/ (modified)
import java.lang.reflect.Field;
import java.util.Random;
public class crazy_jvm {
public static void main(String[] args) throws Exception {
justKidding();
for(int i=0; i<10; i++){
System.out.println((Integer) i);
}
}
private static void justKidding() throws Exception{
// extract the IntegerCache through reflection
Field field = Class.forName("java.lang.Integer$IntegerCache").getDeclaredField("cache");
field.setAccessible(true);
Integer[] cache = (Integer[]) field.get("java.lang.Integer$IntegerCache");
// rewrite the Integer cache
for (int i=0; i<cache.length; i++){
cache[i] = new Integer(new Random().nextInt());
}
}
}
| pxcs/grizzly | crep/jvm.java | 241 | // Intro- Seems like the JVM has gone mad, printing random integers. | line_comment | en | true |
149016_4 | import java.io.File;
import java.io.PrintWriter;
import java.io.StringReader;
import java.security.CodeSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;
import com.sun.org.apache.xalan.internal.xslt.EnvironmentCheck;
/**
* A demo class to use the XSL resources in Xrem folder
* TODO : generic object process with piping steps
* @author Frédéric Glorieux
*
*/
public class Xrem {
/** The XSLT processor */
static TransformerFactory factory=TransformerFactory.newInstance();
/**
* Document RNG file as one HTML file.
* Transformation scenario
* 1) resolve includes (known limitation : overrides not greatly handled)
* 2) transform to html the entire schema
* @throws TransformerException
*/
public static void rng2html(String src, String dest) throws TransformerException {
Transformer transformer;
Source xslt;
// getResourceAsStream() seems enough to resolve relative links, wait and see
xslt = new StreamSource(Xrem.class.getResourceAsStream("rng4inc.xsl"));
transformer=factory.newTransformer(xslt);
DOMResult result= new DOMResult();
transformer.transform(new StreamSource(src), result);
xslt = new StreamSource(Xrem.class.getResourceAsStream("rng2html.xsl"));
transformer=factory.newTransformer(xslt);
// do not forget systemID, maybe useful to resolve links
transformer.transform(new DOMSource(result.getNode(), src), new StreamResult(dest));
}
/** Command line */
public static void main(String[] args) throws Exception {
if (args==null || args.length==0 || args[0].equals("-h") || args[0].equals("-help")) {
System.out.println(
"Xrem - cross remarks in XML file\n"
+ "Usage: java Xrem src.rng dest.html\n"
);
Class cl=TransformerFactory.newInstance().getClass();
CodeSource source =cl.getProtectionDomain().getCodeSource();
System.out.println("Tansformer "+cl+" from "+ (source == null ? "Java Runtime" : source.getLocation()));
System.exit(1);
}
rng2html(args[0], args[1]);
}
} | glorieux-f/rngdoc | RngDoc.java | 686 | // do not forget systemID, maybe useful to resolve links
| line_comment | en | true |
149892_0 | package pet.photography.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import javax.persistence.*;
/**
* Created by user chenzuoli on 2020/4/8 11:18
* description: 宠物类型、品种维表
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Entity
@Table(name = "dim_pet", schema = "photography")
public class DimPet {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private String id;
private String pet_type;
private String variety;
private String size;
private String country;
private String create_time;
private String update_time;
}
| chenzuoli/photography-backend | src/main/java/pet/photography/entity/DimPet.java | 181 | /**
* Created by user chenzuoli on 2020/4/8 11:18
* description: 宠物类型、品种维表
*/ | block_comment | en | true |
150697_0 | /**
* Class representing the TodoApp application.
* It is the main entry point for this program.
*/
import java.util.Scanner;
public class App{
public static void main(String[] args) {
boolean end = false;
TodoList todoList = new TodoList();
while (!end) {
System.out.println("Please specify a command [list, add, mark, archive], else the program will quit:");
String command = getInput();
if (command.toLowerCase().equals("list")) {
todoList.listAll();
}
else if (command.toLowerCase().equals("add")) {
System.out.println("Add an item:");
String name = getInput();
todoList.addItem(name);
}
else if (command.toLowerCase().equals("mark")) {
todoList.listAll();
System.out.println("Which one do you want to mark as completed: ");
try {
Integer idx = Integer.parseInt(getInput());
todoList.markItem(idx);
}
catch (NumberFormatException e) {
System.out.println("Please type only integers.");
}
}
else if (command.toLowerCase().equals("archive")) {
todoList.archiveItems();
}
else {
System.out.println("Goodbye!");
end = true;
}
}
}
public static String getInput() {
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
return input;
}
}
| CodecoolKRK20171/java-todo-app-wutismyname | App.java | 334 | /**
* Class representing the TodoApp application.
* It is the main entry point for this program.
*/ | block_comment | en | false |
150990_0 | /*
Indian Army setup some military-camps, sitauted at random places at LAC in Galwan.
There exist a main base camp connected with other base camps as follows:
Each military-camp is connected with atmost two other military-camps.
Each military-camp will be identified with an unique ID,(an integer).
To safeguard all the military-camps, Govt of India planned to setup protective
S.H.I.E.L.D. Govt of India ask your help to build the S.H.I.E.L.D that should
enclose all the militar-camps.
You are given the IDs of the military-camps as binary tree.
Your task is to find and return the military camp IDs, those are on the edge of
the S.H.I.E.L.D in anti-clockwise order.
Implement the class Solution:
1. public List<Integer> compoundWall(BinaryTreeNode root): returns a list.
NOTE:
'-1' in the input IDs indicates no military-camp (NULL).
Input Format:
-------------
space separated integers, military-camp IDs.
Output Format:
--------------
Print all the military-camp IDs, which are at the edge of S.H.I.E.L.D.
Sample Input-1:
---------------
5 2 4 7 9 8 1
Sample Output-1:
----------------
[5, 2, 7, 9, 8, 1, 4]
Sample Input-2:
---------------
11 2 13 4 25 6 -1 -1 -1 7 18 9 10
Sample Output-2:
----------------
[11, 2, 4, 7, 18, 9, 10, 6, 13]
import java.util.*;
//TreeNode Structure for Your Reference..
class Node{
public int data;
public Node left, right;
public Node(int data){
this.data = data;
left = null;
right = null;
}
}
*/
class Solution{
public void left(Node root,ArrayList<Integer> res){
if(root==null || root.data==-1) return;
if((root.left!=null && root.left.data!=-1) || (root.right!=null && root.right.data!=-1))res.add(root.data);
if((root.left!=null && root.left.data!=-1)) left(root.left,res);
else if((root.left==null || root.left.data==-1) && (root.right!=null && root.right.data!=-1)) left(root.right,res);
}
public void right(Node root,ArrayList<Integer> res){
if(root==null || root.data==-1) return;
if(root.right!=null && root.right.data!=-1) right(root.right,res);
else if((root.right==null || root.right.data==-1) &&(root.left!=null && root.left.data!=-1)) right(root.left,res);
if((root.left!=null && root.left.data!=-1) || (root.right!=null && root.right.data!=-1))res.add(root.data);
}
public void leaf(Node root,ArrayList<Integer> res){
if(root==null || root.data==-1) return;
if((root.left==null || root.left.data==-1) && (root.right==null || root.right.data==-1))res.add(root.data);
leaf(root.left,res);
leaf(root.right,res);
}
public List<Integer> compoundWall(Node root) {
ArrayList<Integer> res = new ArrayList<>();
if(root!=null && root.data!=-1) res.add(root.data);
left(root.left,res);
leaf(root,res);
right(root.right,res);
return res;
//implement your code here.
}
}
| adityachintala/Elite-Questions | CPP/D33/d33p1.java | 995 | /*
Indian Army setup some military-camps, sitauted at random places at LAC in Galwan.
There exist a main base camp connected with other base camps as follows:
Each military-camp is connected with atmost two other military-camps.
Each military-camp will be identified with an unique ID,(an integer).
To safeguard all the military-camps, Govt of India planned to setup protective
S.H.I.E.L.D. Govt of India ask your help to build the S.H.I.E.L.D that should
enclose all the militar-camps.
You are given the IDs of the military-camps as binary tree.
Your task is to find and return the military camp IDs, those are on the edge of
the S.H.I.E.L.D in anti-clockwise order.
Implement the class Solution:
1. public List<Integer> compoundWall(BinaryTreeNode root): returns a list.
NOTE:
'-1' in the input IDs indicates no military-camp (NULL).
Input Format:
-------------
space separated integers, military-camp IDs.
Output Format:
--------------
Print all the military-camp IDs, which are at the edge of S.H.I.E.L.D.
Sample Input-1:
---------------
5 2 4 7 9 8 1
Sample Output-1:
----------------
[5, 2, 7, 9, 8, 1, 4]
Sample Input-2:
---------------
11 2 13 4 25 6 -1 -1 -1 7 18 9 10
Sample Output-2:
----------------
[11, 2, 4, 7, 18, 9, 10, 6, 13]
import java.util.*;
//TreeNode Structure for Your Reference..
class Node{
public int data;
public Node left, right;
public Node(int data){
this.data = data;
left = null;
right = null;
}
}
*/ | block_comment | en | true |
151916_0 | package util;
import java.text.DecimalFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.apache.commons.lang.StringUtils;
import de.jollyday.HolidayCalendar;
import de.jollyday.HolidayManager;
public class CommonUtil {
private static final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
private static final DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm");
private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss Z");
private static final DecimalFormat priceFormatter = new DecimalFormat("#.00");
private static final HolidayManager holidayManager = HolidayManager.getInstance(HolidayCalendar.UNITED_STATES);
public static final ZoneId PACIFIC_ZONE_ID = ZoneId.of("America/Los_Angeles");
// private static final Logger log = LoggerFactory.getLogger(CommonUtil.class);
/**
* Get a DateTime object based on a date string
* @param dateString Date with format yyyyMMdd
*/
public static LocalDate parseDate(String dateString) {
return LocalDate.parse(dateString, dateFormatter);
}
public static String formatDate(LocalDate date) {
return date.format(dateFormatter);
}
public static String formatPrice(double price) {
return priceFormatter.format(price);
}
public static boolean isMarketClosedToday() {
LocalDate date = getPacificTimeNow().toLocalDate();
return date.getDayOfWeek() == DayOfWeek.SATURDAY ||
date.getDayOfWeek() == DayOfWeek.SUNDAY ||
holidayManager.isHoliday(date);
}
public static String removeHyphen(String dateString) {
return dateString == null ? null : dateString.replace("-", "");
}
/**
* Get a time string based on hour and minute.
* e.g. hour = 9, minute = 5 -> "09:05"
*/
public static String formatTime(LocalTime time) {
return time.format(timeFormatter);
}
public static String formatDateTime(ZonedDateTime dateTime) {
return dateTime.format(dateTimeFormatter);
}
public static ZonedDateTime parseDateTime(String dateTimeString) {
return ZonedDateTime.parse(dateTimeString, dateTimeFormatter);
}
public static LocalDateTime getDateTime(LocalDate date) {
return LocalDateTime.of(date, LocalTime.of(0, 0));
}
/**
* Split a CSV line.
* Remove the quote as well.
* @param line
* @return
*/
public static String[] splitCSVLine(String line) {
String[] data = line.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
for (int i = 0; i < data.length; i++) {
data[i] = data[i].trim().replaceAll("^\"|\"$", "").trim();
}
return data;
}
/**
* Return a delimited string from a list of strings.
*/
public static String getDelimitedString(List<String> list, String delimiter) {
return list.stream().collect(Collectors.joining(delimiter));
}
public static ZonedDateTime getPacificTimeNow() {
return ZonedDateTime.now(PACIFIC_ZONE_ID);
}
public static String getPacificDateNow() {
return formatDate(getPacificTimeNow().toLocalDate());
}
public static <T> void requireNonNull(T obj, String objName) {
Objects.requireNonNull(obj, objName + " cannot be null.");
}
public static <T> void requireEqual(T firstObj, T secondObj) {
if (firstObj == null || secondObj == null) {
throw new IllegalArgumentException("Cannot pass null objects to check equality.");
}
if (firstObj.equals(secondObj)) {
return;
}
String message = new StringBuilder()
.append("Objects are not equal.")
.append(System.lineSeparator())
.append("First object : ")
.append(firstObj.toString())
.append(System.lineSeparator())
.append("Second object: ")
.append(secondObj.toString())
.toString();
throw new IllegalArgumentException(message);
}
public static boolean isSymbolValid(String symbol) {
if (StringUtils.isEmpty(symbol)) return false;
return symbol.matches("[a-zA-Z]*");
}
} | jimmyzzxhlh/MinionStock | src/util/CommonUtil.java | 1,144 | // private static final Logger log = LoggerFactory.getLogger(CommonUtil.class);
| line_comment | en | true |
152049_0 | package application;
import java.util.ArrayList;
// TODO: change this class to function in a similar manner to Project.java, as there is now a CLINVersion class
public class CLIN
{
private String index;
private String projectType;
private String popStart;
private String popEnd;
private String clinContent;
private String version;
private String id;
private String versionID;
private ArrayList<OrganizationBOE> organizations;
private ArrayList<OrganizationBOE> deletedOrganizations;
public CLIN() {
index = null;
projectType = null;
popStart = null;
popEnd = null;
clinContent = null;
version = null;
versionID = null;
organizations = new ArrayList<OrganizationBOE>();
deletedOrganizations = new ArrayList<OrganizationBOE>();
}
public CLIN(String id, String versionID, String index, String version,
String projectType, String clinContent,
String popStart, String popEnd) {
this.id = id;
this.index = index;
this.version = version;
this.projectType = projectType;
this.clinContent = clinContent;
this.popStart = popStart;
this.popEnd = popEnd;
this.versionID = versionID;
organizations = new ArrayList<OrganizationBOE>();
deletedOrganizations = new ArrayList<OrganizationBOE>();
}
public void setID(String id) {
this.id = id;
}
public String getID() {
return id;
}
public void setIndex(String index) {
this.index = index;
}
public void setProjectType(String projectType) {
this.projectType = projectType;
}
public void setPopStart(String popStart) {
this.popStart = popStart;
}
public void setPopEnd(String popEnd) {
this.popEnd = popEnd;
}
public void setClinContent(String clinContent) {
this.clinContent = clinContent;
}
public void setVersion(String version) {
this.version = version;
}
public void setVersionID(String versionID) {
this.versionID = versionID;
}
public String getIndex() {
return index;
}
public String getProjectType() {
return projectType;
}
public String getPopStart() {
return popStart;
}
public String getPopEnd() {
return popEnd;
}
public String getClinContent() {
return clinContent;
}
public String getVersion() {
return version;
}
public String getVersionID() {
return versionID;
}
public ArrayList<OrganizationBOE> getOrganizations() {
return organizations;
}
public void setOrganizations(ArrayList<OrganizationBOE> list) {
this.organizations = list;
}
public void addOrganiztion(OrganizationBOE org) {
organizations.add(org);
}
public ArrayList<OrganizationBOE> getDeletedOrganizations() {
return deletedOrganizations;
}
public void setDeletedOrganizations(ArrayList<OrganizationBOE> orgs) {
this.deletedOrganizations = orgs;
}
public String toString() {
return "Index: " + index + " v" + version + "\n" + "Project Type: " + projectType + "\n"
+ "PoP: " + popStart + " to " + popEnd + "\n" + "Content:\n\t" + clinContent;
}
} | AFMS-Rowan-Software-Projects/Estimation-Tool-Fall-2019 | src/application/CLIN.java | 828 | // TODO: change this class to function in a similar manner to Project.java, as there is now a CLINVersion class | line_comment | en | true |
152352_0 | package Services;
import Tools.MyConnection;
//import static com.sun.org.glassfish.external.amx.AMXUtil.prop;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.PasswordAuthentication;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Mailing {
private Connection con;
private Statement ste;
public Mailing() {
con = MyConnection.getInstance().getCnx();
}
public static void mailing(String recipient) throws Exception {
Properties prop = new Properties();
final String moncompteEmail = "[email protected]";
final String psw = "chayma391chayma";
prop.put("mail.smtp.host", "smtp.gmail.com");
prop.put("mail.smtp.port", "587");
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.starttls.enable", "true");
Session ses = Session.getInstance(prop, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(moncompteEmail, psw);
}
});
try {
Message msg = new MimeMessage(ses);
msg.setFrom(new InternetAddress(moncompteEmail));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
msg.setSubject("information");
msg.setContent("Bonjour Mme/Mr je vais vous informe que l'administrateur a ajoute un nouveau article n'oublier pas de jetter un coup d'oeil ", "text/html");
Transport.send(msg);
} catch (MessagingException ex) {
Logger.getLogger(Mailing.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void mailingValider(String recipient, int nombre) throws Exception {
Properties prop = new Properties();
final String moncompteEmail = "[email protected]";
final String psw = "lion96montinho";
prop.put("mail.smtp.host", "smtp.gmail.com");
prop.put("mail.smtp.port", "587");
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.starttls.enable", "true");
Session ses = Session.getInstance(prop, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(moncompteEmail, psw);
}
});
try {
Message msg = new MimeMessage(ses);
msg.setFrom(new InternetAddress(moncompteEmail));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
msg.setSubject("Code de confirmation");
msg.setText("Merci pour votre Interet a TUNISIAN GOT TALENT , voici votre code de confirmation"+String.valueOf(nombre));
Transport.send(msg);
} catch (MessagingException ex) {
Logger.getLogger(Mailing.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| wiemjebari/PIDEV3A3 | src/Services/Mailing.java | 837 | //import static com.sun.org.glassfish.external.amx.AMXUtil.prop; | line_comment | en | true |
152590_0 | /*
Given two strings, append them together (known as "concatenation") and return the result. However,
if the strings are different lengths, omit chars from the longer string so it is the same length as
the shorter string. So "Hello" and "Hi" yield "loHi". The strings may be any length.
minCat("Hello", "Hi") → "loHi"
minCat("Hello", "java") → "ellojava"
minCat("java", "Hello") → "javaello" */
public class MinCat {
public static void main(String[] args) {
System.out.println(minCat("Hello", "Hi"));
System.out.println(minCat("Hello", "java"));
System.out.println(minCat("java", "Hello"));
}
public static String minCat(String a, String b) {
int min = Math.min(a.length(), b.length());
return a.substring(a.length() - min) + b.substring(b.length() - min);
}
} | anandboge/Programming | MinCat.java | 241 | /*
Given two strings, append them together (known as "concatenation") and return the result. However,
if the strings are different lengths, omit chars from the longer string so it is the same length as
the shorter string. So "Hello" and "Hi" yield "loHi". The strings may be any length.
minCat("Hello", "Hi") → "loHi"
minCat("Hello", "java") → "ellojava"
minCat("java", "Hello") → "javaello" */ | block_comment | en | true |
152714_0 | /*Problem Description
Find the minimum number of coins required to form any value between 1 to N,both inclusive.
Cumulative value of coins should not exceed N. Coin denominations are 1 Rupee, 2 Rupee and 5 Rupee.
Let’s Understand the problem using the following example. Consider the value of N is 13,
then the minimum number of coins required to formulate any value between 1 and 13, is 6. One 5 Rupee,
three 2 Rupee and two 1 Rupee coins are required to realize any value between 1 and 13. Hence this is the answer.However,
if one takes two 5 Rupee coins, one 2 rupee coin and two 1 rupee coin, then too all values between 1 and 13 are achieved.
But since the cumulative value of all coins equals 14, i.e., exceeds 13, this is not the answer.
Input Format:
A single integer value.
Output Format:
Four space separated integer values.
1st – Total number of coins.
2nd – number of 5 Rupee coins.
3rd – number of 2 Rupee coins.
4th – number of 1 Rupee coins.
Constraints:
0 < n < 1000
Refer the sample output for formatting
Sample Input
13
Sample Output
6 1 3 2
Explanation
The minimum number of coins required is 6 with in it:
minimum number of 5 Rupee coins = 1
minimum number of 2 Rupee coins = 3
minimum number of 1 Rupee coins = 2
Using these coins, we can form any value with in the given value and itself, like below:
Here the given value is 13
For 1 = one 1 Rupee coin
For 2 = one 2 Rupee coin
For 3 = one 1 Rupee coin and one 2 Rupee coins
For 4 = two 2 Rupee coins
For 5 = one 5 Rupee coin
For 6 = one 5 Rupee and one 1 Rupee coins
For 7 = one 5 Rupee and one 2 Rupee coins
For 8 = one 5 Rupee, one 2 Rupee and one 1 Rupee coins
For 9 = one 5 Rupee and two 2 Rupee coins
For 10 = one 5 Rupee, two 2 Rupee and one 1 Rupee coins
For 11 = one 5 Rupee, two 2 Rupee and two 1 Rupee coins
For 12 = one 5 Rupee, three 2 Rupee and one 1 Rupee coins
For 13 = one 5 Rupee, three 2 Rupee and two 1 Rupee coins
*/
import java.util.*;
class Coin {
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int one=0,two=0,five=0,num;
System.out.print("Enter The Coin Value: ");
num=sc.nextInt();
five=(num-4)/5;
if((num-five*5)%2==0)
{
one=2;
}
else
{
one=1;
}
two=(num-5*five-one)/2;
System.out.print("Total Coins Are Used: ");
System.out.println(one+two+five);
System.out.print("Five Rupee Coins Are Used: ");
System.out.println(five);
System.out.print("Two Rupee Coins Are Used: ");
System.out.println(two);
System.out.print("One Rupee Coins Are Used: ");
System.out.println(one);
}
}
| ruban117/PROBLEM-SOLVING-USING-JAVA | Coin.java | 943 | /*Problem Description
Find the minimum number of coins required to form any value between 1 to N,both inclusive.
Cumulative value of coins should not exceed N. Coin denominations are 1 Rupee, 2 Rupee and 5 Rupee.
Let’s Understand the problem using the following example. Consider the value of N is 13,
then the minimum number of coins required to formulate any value between 1 and 13, is 6. One 5 Rupee,
three 2 Rupee and two 1 Rupee coins are required to realize any value between 1 and 13. Hence this is the answer.However,
if one takes two 5 Rupee coins, one 2 rupee coin and two 1 rupee coin, then too all values between 1 and 13 are achieved.
But since the cumulative value of all coins equals 14, i.e., exceeds 13, this is not the answer.
Input Format:
A single integer value.
Output Format:
Four space separated integer values.
1st – Total number of coins.
2nd – number of 5 Rupee coins.
3rd – number of 2 Rupee coins.
4th – number of 1 Rupee coins.
Constraints:
0 < n < 1000
Refer the sample output for formatting
Sample Input
13
Sample Output
6 1 3 2
Explanation
The minimum number of coins required is 6 with in it:
minimum number of 5 Rupee coins = 1
minimum number of 2 Rupee coins = 3
minimum number of 1 Rupee coins = 2
Using these coins, we can form any value with in the given value and itself, like below:
Here the given value is 13
For 1 = one 1 Rupee coin
For 2 = one 2 Rupee coin
For 3 = one 1 Rupee coin and one 2 Rupee coins
For 4 = two 2 Rupee coins
For 5 = one 5 Rupee coin
For 6 = one 5 Rupee and one 1 Rupee coins
For 7 = one 5 Rupee and one 2 Rupee coins
For 8 = one 5 Rupee, one 2 Rupee and one 1 Rupee coins
For 9 = one 5 Rupee and two 2 Rupee coins
For 10 = one 5 Rupee, two 2 Rupee and one 1 Rupee coins
For 11 = one 5 Rupee, two 2 Rupee and two 1 Rupee coins
For 12 = one 5 Rupee, three 2 Rupee and one 1 Rupee coins
For 13 = one 5 Rupee, three 2 Rupee and two 1 Rupee coins
*/ | block_comment | en | true |
152822_0 | /*
* Decompiled with CFR 0.150.
*/
package delta;
public interface Class137 {
public static final boolean still$;
public boolean _plymouth(Class137 var1);
public boolean _fixtures();
public Class137 _actress();
public boolean _elements();
public String _settle();
public boolean _computer();
public boolean _northern();
}
| Wirest/Minecraft-Hacked-Client-Sources | Delta b3.7/delta/Class137.java | 98 | /*
* Decompiled with CFR 0.150.
*/ | block_comment | en | true |
152912_14 |
// This file is part of TOOL, a robotics interaction and development
// package created by the Northern Bites RoboCup team of Bowdoin College
// in Brunswick, Maine.
//
// TOOL 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.
//
// TOOL 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 TOOL. If not, see <http://www.gnu.org/licenses/>.
package TOOL.SQL;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.Vector;
import TOOL.TOOLException;
import TOOL.Data.DataSet;
import TOOL.Data.DataSource;
import TOOL.Data.SourceHandler;
public class SQLSource implements DataSource {
private SourceHandler handler;
private String db_path;
private Vector<SQLSet> datasets;
public SQLSource(SourceHandler hdlr, String path) {
handler = hdlr;
db_path = path;
datasets = new Vector<SQLSet>();
}
//
// DataSource contract
//
public SourceHandler getHandler() {
return handler;
}
/**
* This createNew() methods varies slightly from those of other
* DataSources, as the String argument here is NOT an URL representation of
* the location of the DataSet, but a SQL statement that performs the
* initial SELECT operation for the DataSet. This statement should be in
* the form emitted by a FrameIDRequest (the toString() method, in the
* SQLRequest base-class).
*/
public DataSet createNew(String statement) {
try {
SQLSet set = new SQLSet(this, datasets.size(), db_path,
statement);
datasets.add(set);
return set;
}catch (TOOLException e) {
SQLModule.logError("Unable to initialize SQL DataSet", e);
return null;
}
}
public int numDataSets() {
return datasets.size();
}
public DataSet getDataSet(int i) {
return datasets.get(i);
}
public List<DataSet> getDataSets() {
return new Vector<DataSet>(datasets);
}
public String getPath() {
String[] sections = db_path.split("/");
String path = "";
for (int i = 0; i < 3 && i < sections.length; i++)
path += sections[i] + '/';
return path;
}
public String getType() {
return SQL_SOURCE_TYPE;
}
}
| northern-bites/tool | TOOL/SQL/SQLSource.java | 675 | // You should have received a copy of the GNU General Public License | line_comment | en | true |
153185_5 | /******************************************************************************
* Compilation: javac BST.java
* Execution: java BST
* Dependencies: StdIn.java StdOut.java Queue.java
* Data files: https://algs4.cs.princeton.edu/32bst/tinyST.txt
*
* A symbol table implemented with a binary search tree.
*
* % more tinyST.txt
* S E A R C H E X A M P L E
*
* % java BST < tinyST.txt
* A 8
* C 4
* E 12
* H 5
* L 11
* M 9
* P 10
* R 3
* S 0
* X 7
*
******************************************************************************/
import java.util.NoSuchElementException;
import edu.princeton.cs.algs4.Queue;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
public class BST <Key extends Comparable<Key>, Value> {
private Node root;
private class Node {
private Key key;
private Value val;
private Node left, right;
private int count;
public Node(Key key, Value val) {
this.key = key;
this.val = val;
}
}
public void put(Key key, Value val) {
root = put(root, key, val);
}
private Node put(Node x, Key key, Value val) {
//concise but tricky, read carefully
if (x == null) return new Node(key, val);
int cmp = key.compareTo(x.key);
if (cmp > 0) x.right = put(x.right, key, val);
else if (cmp < 0) x.left = put(x.left, key, val);
else x.val = val;
x.count = 1 + size(x.left) + size(x.right);
return x;
}
public int size() {
return size(root);
}
private int size(Node x) {
if (x == null) return 0;
return x.count;
}
public Value get(Key key) {
Node x = root;
while (x != null) {
int cmp = key.compareTo(x.key);
if (cmp > 0) x = x.right;
else if (cmp < 0) x = x.left;
else return x.val;
}
return null;
}
public Key floor(Key key) {
Node x = floor(root, key);
if (x == null) return null;
return x.key;
}
private Node floor(Node x, Key key) {
if (x == null) return null;
int cmp = key.compareTo(x.key);
if (cmp == 0) return x;
if (cmp < 0) return floor(x.right, key);
Node t = floor(x.right, key);
if (t != null) return t;
else return x;
}
public int rank(Key key) {
return rank(key, root);
}
private int rank(Key key, Node x) {
if (x == null) return 0;
int cmp = key.compareTo(x.key);
if (cmp == 0) return size(x.left);
else if (cmp > 0) return 1 + size(x.left) + rank(key, x.right); //tricky
else return rank(key, x.left);
}
public void delete(Key key) {
root = delete(root, key);
}
private Node delete(Node x, Key key) {
if (x == null) return null;
int cmp = key.compareTo(x.key);
if (cmp < 0) x.left = delete(x.left, key);
else if (cmp > 0) x.right = delete(x.right, key);
//if cmp == 0, find the smallest at the right Node, exch that with deleted key
else {
if (x.right == null) return x.left;
if (x.left == null) return x.right;
Node t = x;
x = min(x.right);
x.right = deleteMin(x.right); //TODO: delete and return the min key in right side
x.left = t.left;
}
x.count = 1 + size(x.right) + size(x.left);
return x;
}
private Node min(Node x) {
if (x.left == null) return x;
return min(x.left);
}
public void deleteMin() {
// if(isEmpty()) throw new NoSuchElementException("Symbol table underflow");
root = deleteMin(root);
}
private Node deleteMin(Node x) {
if (x.left == null) return x.right;
x.left = deleteMin(x.left);
x.count = size(x.left) + size(x.right) + 1;
return x;
}
public Iterable<Key> keys () {
Queue<Key> q = new Queue<Key>();
inorder(root, q);
return q;
}
private void inorder(Node x, Queue<Key> q) {
if (x == null) return;
inorder(x.left, q);
q.enqueue(x.key);
inorder(x.right, q);
}
public static void main(String[] args) {
BST<String, Integer> st = new BST<String, Integer>();
for (int i = 0; !StdIn.isEmpty(); i++) {
String key = StdIn.readString();
if ((st.size() > 1) && (st.floor(key) != st.floor2(key)))
throw new RuntimeException("floor() function inconsistent");
st.put(key, i);
}
for (String s : st.levelOrder())
StdOut.println(s + " " + st.get(s));
StdOut.println();
for (String s : st.keys())
StdOut.println(s + " " + st.get(s));
}
} | nmd2k/data-structure-n-algorithm | BST.java | 1,476 | // if(isEmpty()) throw new NoSuchElementException("Symbol table underflow"); | line_comment | en | true |
153578_10 | /*
* Copyright (C) 2012-2023 by LA7ECA, Øyvind Hanssen ([email protected])
*
* 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.
*/
package no.polaric.aprsd;
import java.util.*;
import java.io.Serializable;
/**
* APRS object.
*/
public class AprsObject extends AprsPoint implements Serializable
{
private static long _expiretime = 1000 * 60 * 60 * 12; // Default: 3 hour
public static class JsInfo extends AprsPoint.JsInfo {
public String owner;
public JsInfo(AprsObject p) {
super(p);
type = "AprsObject";
owner = p.getOwner().getIdent();
}
}
public JsInfo getJsInfo() {
return new JsInfo(this);
}
/*
* Attributes of object/item record (APRS data)
*/
private String _ident;
private Station _owner; // FIXME: use ident instead
private boolean _killed = false;
private boolean _timeless = false;
/* If an object is timeless it also permanent, i.e. it allows other permanent objects
* to exist with the same name (in another area and with another owner id)
* Permanence is a proposed APRS 1.2 feature
*/
public AprsObject(Station owner, String id)
{
super(null);
_owner = owner;
_ident = id;
_updated = new Date();
}
public synchronized void reset()
{
_killed = true;
super.reset();
}
public String getIdent()
{ return _ident+'@'+
(_owner!= null ? _owner.getIdent() : "UNKNOWN"); }
public void setOwner(Station o)
{ _owner = o; }
public Station getOwner()
{ return _owner; }
@Override
public Source getSource() {
return (_owner==null ? null : _owner.getSource());
}
/**
* Set the object to be timeless/permanent. If true it allows other
* permanent objects o exist with the same name...
*
* @param p Set to true if we want the object to be timeless/permanent.
*/
public void setTimeless(boolean p)
{ _timeless = p; }
/**
* Return true if object is timeless/permanent.
*/
public boolean isTimeless()
{ return _timeless; }
/**
* Set object to updated (with new timestamp).
*/
public synchronized void update()
{
if (!_killed)
setChanging();
_killed = false;
_owner.setUpdated(new Date());
}
/**
* Update position of the object.
*
* @param ts Timestamp (time of update). If null, the object will be timeless/permanent.
* @param pd Position data (position, symbol, ambiguity, etc..)
* @param descr Comment field.
* @param path Digipeater path of containing packet.
*/
public synchronized void update(Date ts, ReportHandler.PosData pd, String descr, String path)
{
/* Should try to share code with Station class ?*/
if (_symbol != pd.symbol || _altsym != pd.symtab ||
(_position == null && pd.pos != null))
setChanging();
if (_position != null && _updated != null) {
long distance = Math.round(_position.distance(pd.pos) * 1000);
if (distance > 10)
setChanging();
}
if (ts==null) {
setTimeless(true);
ts = new Date();
}
LatLng prevpos = (getPosition()==null ? null : getPosition());
saveToTrail(ts, pd.pos, 0, 0, "(obj)");
updatePosition(ts, pd.pos, pd.ambiguity);
setDescr(descr);
_symbol = pd.symbol;
_altsym = pd.symtab;
_killed = false;
_owner.setUpdated(new Date());
_api.getDB().updateItem(this, prevpos);
}
/**
* Return true if object has expired.
*/
protected boolean _expired()
{ Date now = new Date();
return (_owner != _api.getOwnPos() && // Do not expire own objects
(_owner.expired() || now.getTime() > (_updated.getTime() + _expiretime))) ;
}
/**
* Return false if object should not be visible on maps. If it has expired
* or if it has been killed.
*/
@Override
public synchronized boolean visible()
{ return !_killed && !expired(); }
/**
* Kill the object. Mark it for removal.
*/
public void kill()
{
_killed = true;
setChanging();
}
}
| PolaricServer/aprsd | src/AprsObject.java | 1,239 | /* Should try to share code with Station class ?*/ | block_comment | en | true |
153960_0 | /**
* Что здесь не так? Объясните почему? Как можно поправить?
*/
public class BoxingPuzzle {
public void puzzleMe() {
Integer n = 6;
Integer half = n / 2;
Integer None = null;
if (n == 6)
System.out.println("Six little nigger boys playing with a hive;\n" +
"A bumble-bee stung one, and then there were five.");
decrement(n);
if (n == 5)
System.out.println("Five little nigger boys going in for law;\n" +
"One got in chancery, and then there were four.");
decrement(n);
if (n == 4)
System.out.println("Four little nigger boys going out to sea;\n" +
"A red herring swallowed one, and then there were three.");
decrement(n);
if (n == half)
System.out.println("debug: Only half is left");
if (n == 3)
System.out.println("Three little nigger boys walking in the Zoo;\n" +
"A big bear hugged one, and then there were two.\n");
decrement(n);
if (n == 2)
System.out.println("Two little nigger boys sitting in the sun; \n" +
"One got frizzled up, and then there was one.");
decrement(n);
if (n == 1)
System.out.println("One little nigger boy left all alone;\n" +
"He went out and hanged himself and then there were None.");
decrement(n);
if (n == 0)
n = None;
if (n == null)
System.out.println("debug: Nothing left");
}
private Integer decrement(Integer i) {
i--;
return i;
}
}
| java-park-mail-ru/rk1_cases | BoxingPuzzle.java | 458 | /**
* Что здесь не так? Объясните почему? Как можно поправить?
*/ | block_comment | en | true |
154238_1 | interface message
{
void morning ();
}
interface message1 extends message
{
void evening ();
}
interface message2 extends message
{
void goodnight();
}
public class implement implements message2
{
//public void morning () { System.out.println(" morning");}
//public void evening () { System.out.println(" evening");}
public void goodnight () { System.out.println(" goodnight");}
public static void main ( String [] args)
{
implement e = new implement();
e.goodnight ();
}
}
| oldoldoldoldoldDarshan/javaPrograms | implement.java | 147 | //public void evening () { System.out.println(" evening");} | line_comment | en | true |
154677_6 | import java.util.*;
public class FoodItem {
private String name = " "; //Inputted by the user
private double fat = 0; //Inputted by the user
private double carbs = 0; //Inputted by the user
private double protein = 0; //Inputted by the user
//Calorie calculation constants
private static final double CALORIES_PER_GRAM_FAT = 9.0;
private static final double CALORIES_PER_GRAM_CARBS = 4.0;
private static final double CALORIES_PER_GRAM_PROTEIN = 4.0;
//The amount of calories per each macronutrient. Variables are assigned when getCalories() is run.
private double fatCalories = 0;
private double carbsCalories = 0;
private double proteinCalories = 0;
public FoodItem(String name, double fat, double carbs, double protein){
this.name = name;
this.fat = fat;
this.carbs = carbs;
this.protein = protein;
}
//The following methods return the amount of calories per fat, carbs, and protein.
//Calories from fat
private double getCaloriesFat(double fatGrams) {
return (fatGrams*CALORIES_PER_GRAM_FAT);
}
//Calories from carbs
private double getCaloriesCarbs(double carbsGrams) {
return (carbsGrams*CALORIES_PER_GRAM_CARBS);
}
//Calories from protein
private double getCaloriesProtein(double proteinGrams) {
return (proteinGrams*CALORIES_PER_GRAM_PROTEIN);
}
//Calculates the total amount of calories from all the macronutrients
public double getCalories(double numServings) {
//Uses the calories per macronutrient constants to calculate the calories per each macronutrient
this.fatCalories = getCaloriesFat(fat);
this.carbsCalories = getCaloriesCarbs(carbs);
this.proteinCalories = getCaloriesProtein(protein);
//Adds up all the individual calories, multiplies the sum by the number of servings, then returns the value
return numServings*(this.fatCalories+this.carbsCalories+this.proteinCalories);
}
public void printInfo(double numServings) {
System.out.printf("\nNutritional information per serving of %s:\n", this.name);
System.out.printf("Fat: %.2f g\nCarbohydrates: %.2f g\nProtein: %.2f g\n", this.fat, this.carbs, this.protein);
System.out.printf("Total Calories for %.2f servings of %s: %.2f\n",numServings, this.name, getCalories(numServings));
System.out.println("Dominant Macronutrient: " + getDominantMacronutrient());
}
private String getDominantMacronutrient() {
String DominantMacronutrient = " ";
//getCalories() assigns private variables for the amount of calories in fat, carbs, and protein
this.getCalories(0);
//First checks if fat is greater than carbs, then goes through the remaining possibilities
if (this.fatCalories > this.carbsCalories)
//Checks fat's relationship to protein and returns the larger one, or both of them if they're equal
if (this.fatCalories > this.proteinCalories)
DominantMacronutrient = "Fat";
else if (this.fatCalories < this.proteinCalories)
DominantMacronutrient = "Protein";
else
DominantMacronutrient = "Fat & Protein";
//Checks if carbs is greater than fat
else if (this.fatCalories < this.carbsCalories)
//Then compares carbs to protein and returns the larger one, or both if they're equal
if (this.carbsCalories > this.proteinCalories)
DominantMacronutrient = "Carbohydrates";
else if (this.carbsCalories < this.proteinCalories)
DominantMacronutrient = "Protein";
else
DominantMacronutrient = "Carbohydrates & Protein";
//If the last two branches aren't checked, carbs must be equal to fat
else
//Checks if protein is also equal to carbs and fat
if ((this.fatCalories == this.carbsCalories) && (this.carbsCalories == this.proteinCalories))
DominantMacronutrient = "Fat & Protein & Carbohydrates";
else
DominantMacronutrient = "Fat & Protein";
return DominantMacronutrient;
}
}
| cafox2003/CSC-222-Caleb-Fox-Assignment-5 | FoodItem.java | 1,107 | //The following methods return the amount of calories per fat, carbs, and protein. | line_comment | en | true |
155474_8 | package building;
import java.util.ArrayList;
import java.util.List;
import human.Subscriber;
//신문사(Newspaper) 클래스를 정의한다.
public class BillysNewspaper implements Newspaper {
// 구독자 목록
private List<Subscriber> subscribers;
// 정치 뉴스
private String politics;
// 연예 뉴스
private String entertainment;
// 프로그래밍 뉴스
private String programming;
// 빌리네 신문회사가 생성될 때 구독자 목록을 초기화
public BillysNewspaper() {
subscribers = new ArrayList<Subscriber>();
}
// 빌리네 신문회사를 마을사람이 구독할 때
@Override
public void subscribe(Subscriber subscriber) {
// 목록에 새로운 구독자를 추가한다.
subscribers.add(subscriber);
}
// 빌리네 신문회사를 구독 취소할 때
@Override
public void quit(Subscriber subscriber) {
// 구독자 목록에서 구독 취소자를 삭제한다.
subscribers.remove(subscriber);
}
// 빌리네 신문회사가 뉴스를 배부할 때
public void deliverNews() {
// 신문을 배달하는 메소드 실행
deliver();
}
// 신문을 배달하는 메소드
public void deliver() {
for (Subscriber subscriber : subscribers)
// 구독자 목록에 있는 구독자들에게 정치, 연예, 프로그래밍 뉴스를 배부함
subscriber.receive(politics, entertainment, programming);
}
// 새로운 소식을 취재하는 메소드(setter에 해당)
public void coverning(String politics, String entertainment, String programming) {
this.politics = politics;
this.entertainment = entertainment;
this.programming = programming;
// 취재가 끝나고 새로운 소식을 바로 배부함
deliverNews();
}
public String getPolitics() {
return politics;
}
public String getEntertainment() {
return entertainment;
}
public String getProgramming() {
return programming;
}
} | drow724/design_pattern | src/building/BillysNewspaper.java | 621 | // 빌리네 신문회사를 구독 취소할 때 | line_comment | en | true |
155605_6 | import java.util.Date;
import java.util.List;
/**
* The Partner class for storing partner information.
* The class stores firstName, lastName, email, country, and availableDates.
* Has getters and setters methods for each variable.
*/
public class Partner {
private String firstName;
private String lastName;
private String email;
private String country;
private List<Date> availableDates;
/**
* firstName variable setter.
* @param firstName
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* lastName variable setter
* @param lastName
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* email variable setter
* @param email
*/
public void setEmail(String email) {
this.email = email;
}
/**
* country variable setter
* @param country
*/
public void setCountry(String country) {
this.country = country;
}
/**
* availableDates variable setter
* @param availableDates
*/
public void setAvailableDates(List<Date> availableDates) {
this.availableDates = availableDates;
}
/**
* firstname variable getter
* @return
*/
public String getFirstName() {
return firstName;
}
/**
* lastName variable getter
* @return
*/
public String getLastName() {
return lastName;
}
/**
* email variable getter
* @return
*/
public String getEmail() {
return email;
}
/**
* country variable getter
* @return
*/
public String getCountry() {
return country;
}
/**
* availableDates variable getter
* @return
*/
public List<Date> getAvailableDates() {
return availableDates;
}
} | timzhangRepo/Meeting-Scheduling-App | Partner.java | 408 | /**
* firstname variable getter
* @return
*/ | block_comment | en | true |
155700_3 | /*
Type.java
Copyright (c) 2009-2012, Morgan McGuire
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
Types of Entitys that can be in a location.
*/
public enum Type {
/** A square that is empty and can be entered (note that it may no
* longer be empty by the time you actually get around to entering
* it, though!. */
EMPTY,
/** A square that cannot be entered because it is blocked by an
immovable and indestructible wall.*/
WALL,
/** A square that cannot be entered because it is blocked by an immovable
and indestructible hazard. Attempting to move into the hazard
converts a creature into an Apple. */
HAZARD,
CREATURE;
/** @deprecated Old name for HAZARD */
@Deprecated
static final public Type THORN = HAZARD;
}
| brodermar/darwin | src/Type.java | 479 | /** A square that cannot be entered because it is blocked by an
immovable and indestructible wall.*/ | block_comment | en | false |
156140_0 | /*Create an abstract class called Animal with an abstract method called move().
Implement three concrete classes, Fish, Bird, and Dog, that extend Animal and
implement each animal's move() method. The Fish class should print out a message
saying it is swimming; the Bird class should print out a message saying it is flying, and
the Dog class should print out a message saying it is running.*/
abstract class animal{
abstract void move();
}
class fish extends animal{
void move(){
System.out.println("Fish is swimming.");
}
}
class bird extends animal{
void move(){
System.out.println("Bird is flying.");
}
}
class dog extends animal{
void move(){
System.out.println("Dog is running.");
}
}
public class ps3q6 {
public static void main(String[] args) {
fish f = new fish();
f.move();
bird b = new bird();
b.move();
dog d = new dog();
d.move();
}
}
| sailochan03/Practice-Set_DSA | ps3q6.java | 253 | /*Create an abstract class called Animal with an abstract method called move().
Implement three concrete classes, Fish, Bird, and Dog, that extend Animal and
implement each animal's move() method. The Fish class should print out a message
saying it is swimming; the Bird class should print out a message saying it is flying, and
the Dog class should print out a message saying it is running.*/ | block_comment | en | true |
156644_7 | /**
File: TimBot.java
Author: Alex Brodsky
Date: September 21, 2015
Purpose: CSCI 1110, Assignment 4 Solution
Description: This class specifies the solution for the TimBot base class.
*/
/**
This is the TimBot base class for representing TimBots and their
behaviours on the planet DohNat.
*/
public class TimBot {
private int myId; // TimBot's ID
protected int energyLevel; // TimBot's energy level
protected char personality = 'N'; // TimBot's personality
protected int [] spressoSensed = new int[5]; // last spresso sensor read
protected boolean [] botsSensed = new boolean[5]; // last adj bot sensor read
/**
This is the only constructor for this class. This constructor
initializes the Tibot and sets its ID and the initial amount of
energy that it has. The ID is between 0 and 99.
parameter: id : ID of the TimBotA
jolts : Initial amount of energy
*/
public TimBot( int id, int jolts ) {
myId = id;
energyLevel = jolts;
}
/**
This method returns the ID of this TimBot, which should be 1 or
greater.
returns: id of TimBot
*/
public int getID() {
return myId;
}
/**
This method is called at the start of the round. The TimBot
uses up one jolt of energy at the start or each round. This
method decrements the energy level and returns true if and
only if the TimBot is still functional.
returns true if energyLevel >= 0
*/
public boolean startRound() {
return useJolt();
}
/**
This method is called during the Sense phase of each round and
informs the TimBot of the districts around it. An integer
array and a boolean array of 5 elements each is passed. The
elements represent the state of the District.CURRENT district
and the districts District.NORTH, District.EAST, District.SOUTH,
and District.WEST of the current district. Each element of
the spresso array stores the number of rounds before the spresso
plants in the corresponding district will be ready for harvest.
I.e., a 0 means that the spresso can be harvested this round.
Each element of the bots array indicates whether a TimBot is
present in the district. E.g., if bots[District.SOUTH] is true,
then there is a TimBot in the district to the south.
It is recommended that this method store the information locally,
in its own boolean variables or arrays to be used in later phases
of the the round.
Params: spresso: a 5 element array of integers indicating when
the ospresso plants will be ready for harvest in
corresponding districts.
bots : a 5 element array of booleans indicating whether
TimBots are present in corresponding districts.
*/
public void senseDistricts( int [] spresso, boolean [] bots ) {
System.arraycopy( spresso, 0, spressoSensed, 0, spresso.length );
System.arraycopy( bots, 0, botsSensed, 0, bots.length );
}
/**
This method is called during the Move phase of each round and
requires the TimBot to decide whether or not to move to another
district. If the TimBot wishes to move, it returns, District.NORTH,
District.EAST, District.SOUTH, or District.WEST, indicating which
direction it wishes to move. If it does not wish to move, it
returns District.CURRENT.
returns: the one of District.NORTH, District.EAST, District.SOUTH,
District.WEST, or District.CURRENT
*/
public int getNextMove() {
// Never move
return District.CURRENT;
}
/**
This method returns true if the TmBot is functional. I.e., it's
energy level is not negative.
returns: energy level >= 0
*/
public boolean isFunctional() {
return energyLevel >= 0;
}
/**
This method is called whenever a TimBot uses a jolt of energy.
It decrements the energy level and returns true if and only
if the TimBot is still functional.
returns true if energyLevel >= 0
*/
private boolean useJolt() {
if( energyLevel >= 0 ) {
energyLevel--;
}
return isFunctional();
}
/**
This method is called when the TimBot has to use its shield.
This costs the TimBot 1 Jolt of energy. If the TimBot has
positive enery, it must use its shield (and use 1 Jolt of
energy). Otherwise, its energy level becomes -1 and it
becomes nonfunctional.
returns: true if the shield was raised.
*/
public boolean useShield() {
return useJolt();
}
/**
This method is called during the Harvest phase if there are
spresso plants to harvest. This allows the TimBot to increase
it's energy reserves by jolts Jolts. The energy level cannot
exceed 99 Jolts.
*/
public void harvestSpresso( int jolts ) {
// add harvest jolts to energy level and ensure it does not exceed 99
energyLevel += jolts;
if( energyLevel > 99 ) {
energyLevel = 99;
}
}
/**
This method is called during the Fire Cannon phase. The TimBot
creates an array of integers, each representing where it wishes
to fire the ion cannon, and decreases its energy reserves by
1 Jolt for each shot. The integers can be one NORTH, EAST,
SOUTH, or WEST. If the TimBot does not wish to fire its cannon,
it returns null;
returns: array of integers representing shots from the cannon
*/
public int [] fireCannon() {
// Never shoots
return null;
}
/**
This method is called at the end of each round to display the state
of the TimBot. The format of the String shoud be:
(P I E)
where
P: is a single Capital letter representing the personality of the TimBot
The default personality is N for do Nothing.
I: is the ID of the TimBot.
E: is the TimBot's energy level in Jolts.
Both the ID and the Energy should have width 2. E.g., if the TimBot's
Personality is A, its ID is 42, and its energy level is 7, then the
string to be returned is:
(A 42 7)
returns: a String representing the state of the TimBot
*/
public String toString() {
return String.format( "(%c %2d %2d)", personality, myId, energyLevel );
}
protected void useMoveEnergy(int move){
if(move != District.CURRENT){
energyLevel--;
}
}
}
| kylecumming/2134A4 | src/TimBot.java | 1,637 | /**
This is the only constructor for this class. This constructor
initializes the Tibot and sets its ID and the initial amount of
energy that it has. The ID is between 0 and 99.
parameter: id : ID of the TimBotA
jolts : Initial amount of energy
*/ | block_comment | en | false |
157597_1 | // this code will not run unless you change the classname to file name.
import java.util.Hashtable;
class Solution {
public int firstUniqChar(String s) {
Hashtable <Character, Integer> map = new Hashtable<>();
for(int i = 0; i < s.length(); i++){
if(!map.containsKey(s.charAt(i))){
map.put(s.charAt(i), 1);
}
else {
map.put(s.charAt(i), map.get(s.charAt(i)) + 1);
}
}
for(int i = 0; i < s.length(); i++){
if(map.get(s.charAt(i)) == 1){
return i;
}
}
return -1;
}
}
/*
* Problem Name: 387. First Unique Character in a String
* Problem Link: https://leetcode.com/problems/first-unique-character-in-a-string/description/
*
* INPUT: s = "loveleetcode"
* OUTPUT: 2
*
* Time Complexity: O(2n) == O(n)
* Space Complexity: O(n)
*
*/ | ashfaqfardin/leetcodestreak2024 | Day14a.java | 279 | /*
* Problem Name: 387. First Unique Character in a String
* Problem Link: https://leetcode.com/problems/first-unique-character-in-a-string/description/
*
* INPUT: s = "loveleetcode"
* OUTPUT: 2
*
* Time Complexity: O(2n) == O(n)
* Space Complexity: O(n)
*
*/ | block_comment | en | true |
157662_0 | /* Written by Yu-Fang Chen, Richard Mayr, and Chih-Duo Hong */
/* Copyright (c) 2010 */
/* */
/* 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*/
package mainfiles;
import java.lang.management.*;
import java.util.Random;
import java.util.TreeMap;
import java.util.TreeSet;
import automata.FAState;
import automata.FiniteAutomaton;
/**
*
* @author Yu-Fang Chen
*
*/
public class TV {
public static void main(String[] args) {
Random r = new Random();
if(args.length<4){
System.out.println("A generator of Tabakov-Vardi random automata.");
System.out.println("Usage: java -jar TV.jar size td ad filename");
System.out.println("Size: number of states.");
System.out.println("td=transition density, typically between 1.1 and 4.5");
System.out.println("ad=acceptance density, must be between 0 and 1.0, e.g., 0.5");
System.out.println("filename=The filename (without extension) where the automaton is stored.");
System.out.println("Output: filename.ba");
System.out.println("Example: java -jar TV.jar 100 1.9 0.8 test");
}else{
int size=Integer.parseInt(args[0]);
float td=Float.parseFloat(args[1]);
float fd=Float.parseFloat(args[2]);
String name=args[3];
FiniteAutomaton ba=genRandomTV(size, td, fd,2);
//System.out.println(ba);
ba.saveAutomaton(name+".ba");
}
}
/**
* Generate automata using Tabakov and Vardi's approach
*
* @param num
*
* @return a random finite automaton
* @author Yu-Fang Chen
*/
public static FiniteAutomaton genRandomTV(int size, float td, float fd, int alphabetSize){
FiniteAutomaton result = new FiniteAutomaton();
TreeMap<Integer,FAState> st=new TreeMap<Integer,FAState>();
Random r = new Random();
TreeSet<Integer> added=new TreeSet<Integer>();
for(int i=0;i<size;i++){
st.put(i, result.createState());
}
for(int n=0;n<Math.round(size*fd)-1;n++){
int i=r.nextInt(size-1);
if(!added.contains(i+1)){
result.F.add(st.get(i+1));
added.add(i+1);
}else
n--;
}
result.setInitialState(st.get(0));
result.F.add(st.get(0));
int transNum=Math.round(td*size);
for(int k=0;k<alphabetSize;k++){
added.clear();
for(int n=0;n<transNum;n++){
int i=r.nextInt(size);
int j=r.nextInt(size);
if(!added.contains(i*size+j)){
result.addTransition(st.get(i),st.get(j),("a"+k));
added.add(i*size+j);
}
else
n--;
}
}
return result;
}
}
| iscas-tis/RABIT | mainfiles/TV.java | 1,061 | /* Written by Yu-Fang Chen, Richard Mayr, and Chih-Duo Hong */ | block_comment | en | true |
157665_0 | /**
* Shapez.java program
* @author Matthew Soulanille
* @author Richard White
* @version 2015-02-04
*/
import javax.swing.JFrame;
import java.awt.FlowLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.Rectangle;
import java.awt.geom.Rectangle2D;
import javax.swing.JComponent;
import java.awt.Shape;
import java.lang.Math;
public class Shapez
{
public static void main(String[] args)
{
JFrame frame = new JFrame(); // constructing a Frame
// frame.setLayout(new FlowLayout());
final int x = 800;
final int y = 600;
frame.setSize(x,y); // (pixels across, pixels down)
frame.setTitle("My Frame, Eh?");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
class randomShapesComponent extends JComponent
{
public void paintComponent(Graphics g)
{
Color[] colors = new Color[] {Color.red, Color.orange, Color.yellow, Color.green, Color.blue, Color.pink, Color.white, Color.gray, Color.black}; // They don't have purple!!!
int count = 1000;
// Recover Graphics 2D
Graphics2D g2 = (Graphics2D) g;
Shape[] shapes = new Shape[count];
for (int n = 0; n < count; n++) {
if (Math.random() < 0.5) {
Ellipse2D.Float ellipse = new Ellipse2D.Float();
ellipse.setFrame(Math.random() *x, Math.random()*y, Math.random() *x, Math.random()*y);
shapes[n] = ellipse;
} else {
Rectangle2D.Float rectangle = new Rectangle2D.Float();
rectangle.setFrame(Math.random() *x, Math.random()*y, Math.random() *x, Math.random()*y);
shapes[n] = rectangle;
}
}
// shapes[0].setFrame(100, 100, 50, 40);
// shapes[1].setFrame(300, 200, 40, 60);
for(Shape s : shapes) {
g2.setColor(colors[(int)Math.floor(Math.random() * 9)]);
g2.draw(s);
}
}
}
// We'll construct something to be viewed here in a minute
// RectangleComponent myBox = new RectangleComponent();
// EllipseComponent myEllipse = new EllipseComponent();
randomShapesComponent shapes = new randomShapesComponent();
// TextComponent text = new TextComponent();
// We'll add the thing that we've constructed to the frame here
// frame.add(text);
frame.add(shapes);
// frame.add(myBox);
//frame.add(myEllipse);
// Now we need to show the frame
frame.setVisible(true);
}
}
| mattsoulanille/compSci | Shapez/Shapez.java | 787 | /**
* Shapez.java program
* @author Matthew Soulanille
* @author Richard White
* @version 2015-02-04
*/ | block_comment | en | true |
158270_0 | /*You are given a 0-indexed integer array nums and a target element target.
A target index is an index i such that nums[i] == target.
Return a list of the target indices of nums after sorting nums in non-decreasing order. If there are no target indices, return an empty list. The returned list must be sorted in increasing order.
Example 1:
Input: nums = [1,2,5,2,3], target = 2
Output: [1,2]
Explanation: After sorting, nums is [1,2,2,3,5].
The indices where nums[i] == 2 are 1 and 2.
Example 2:
Input: nums = [1,2,5,2,3], target = 3
Output: [3]
Explanation: After sorting, nums is [1,2,2,3,5].
The index where nums[i] == 3 is 3.
Example 3:
Input: nums = [1,2,5,2,3], target = 5
Output: [4]
Explanation: After sorting, nums is [1,2,2,3,5].
The index where nums[i] == 5 is 4.
Constraints:
1 <= nums.length <= 100
1 <= nums[i], target <= 100*/
class Solution {
public List<Integer> targetIndices(int[] nums, int target) {
List<Integer> ls=new ArrayList<>();
int s=0;
int l=0;
for(int i=0;i<nums.length;i++){
if(nums[i]<target){
s++;
}else if(nums[i]>target){
l++;
}
}
for(int i=s;i<nums.length-l;i++){
ls.add(i);
}
return ls;
}
} | Shaik-Sohail-72/DSA | p81.java | 436 | /*You are given a 0-indexed integer array nums and a target element target.
A target index is an index i such that nums[i] == target.
Return a list of the target indices of nums after sorting nums in non-decreasing order. If there are no target indices, return an empty list. The returned list must be sorted in increasing order.
Example 1:
Input: nums = [1,2,5,2,3], target = 2
Output: [1,2]
Explanation: After sorting, nums is [1,2,2,3,5].
The indices where nums[i] == 2 are 1 and 2.
Example 2:
Input: nums = [1,2,5,2,3], target = 3
Output: [3]
Explanation: After sorting, nums is [1,2,2,3,5].
The index where nums[i] == 3 is 3.
Example 3:
Input: nums = [1,2,5,2,3], target = 5
Output: [4]
Explanation: After sorting, nums is [1,2,2,3,5].
The index where nums[i] == 5 is 4.
Constraints:
1 <= nums.length <= 100
1 <= nums[i], target <= 100*/ | block_comment | en | true |
158608_1 | /*----------------------------------------------------------------------------*/
/* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package frc.robot;
/**
* The RobotMap is a mapping from the ports sensors and actuators are wired into
* to a variable name. This provides flexibility changing wiring, makes checking
* the wiring easier and significantly reduces the number of magic numbers
* floating around.
*/
public class RobotMap{
//used to map out the pins aka ports used by different parts of the robot
//PWM
public static final int[] leftMotors = {5, 6, 7};
public static final int[] rightMotors = {2, 3, 4};
public static final int armPotentiometer = 0;
//DIO
public static final int[] leftEncoders = {0, 1};
public static final int[] rightEncoders = {2, 3};
//USB
public static final int controllerPort = 0;
}
| b3fr4nk/4814_DeepSpace | RobotMap.java | 276 | /* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */ | block_comment | en | true |
159874_0 | /*
GemIdent v1.1b
Interactive Image Segmentation Software via Supervised Statistical Learning
http://gemident.com
Copyright (C) 2009 Professor Susan Holmes & Adam Kapelner, Stanford University
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:
http://www.gnu.org/licenses/gpl-2.0.txt
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.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package GemIdentView;
import java.awt.*;
import javax.swing.*;
/**
* The super class of all panels where the central display is
* an image in an {@link KImagePanel image panel}, the east side
* is the image's {@link KMagnify magnifier} and the south may or
* may not display thumbnail views. The class is abstract because
* it provides common functionality; but it, itself is never instantiated
*
* @author Adam Kapelner
*
*/
@SuppressWarnings("serial")
public abstract class KPanel extends JPanel {
/** the image panel in the center of the panel */
protected KImagePanel imagePanel;
/** the Eastern region of the panel (to be populated by a {@link KMagnify magnifier} */
protected Box eastBox;
/** the Central region of the panel (to be populated by a {@link KImagePanel image panel} */
protected Box centerBox;
/** the Southern region of the panel (may be populated by a {@link KThumbnailPane thumbnail view} */
protected Box southBox;
/** default constructor */
public KPanel(){
super();
setLayout(new BorderLayout());
}
/** resets the image panel in the Central region with a new component (to be overridden) */
protected void setImagePanel(KImagePanel imagePanel){
this.imagePanel=imagePanel;
centerBox=Box.createVerticalBox();
centerBox.add(imagePanel.getScrollPane());
add(centerBox,BorderLayout.CENTER);
AppendEast();
add(eastBox,BorderLayout.EAST);
}
/** sets the image panel's magnifier in the Eastern region (to be overridden) */
protected void AppendEast(){
eastBox=Box.createVerticalBox();
eastBox.add(imagePanel.getMagnifier());
}
/** resets the Southern region (to be overridden) */
protected void EditSouth(){
southBox=Box.createVerticalBox();
add(southBox,BorderLayout.SOUTH);
}
public KImagePanel getImagePanel() {
return imagePanel;
}
/** resets the Eastern region with a new component (to be overridden) */
public void appendToEast(Component comp){
remove(eastBox);
eastBox.add(comp);
add(eastBox,BorderLayout.EAST);
repaint();
}
} | kapelner/GemIdent | GemIdentView/KPanel.java | 799 | /*
GemIdent v1.1b
Interactive Image Segmentation Software via Supervised Statistical Learning
http://gemident.com
Copyright (C) 2009 Professor Susan Holmes & Adam Kapelner, Stanford University
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:
http://www.gnu.org/licenses/gpl-2.0.txt
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.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/ | block_comment | en | true |
160185_3 | import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
/*****************************************************************
* MyComboBoxModel creates and manages a ComboBox to be used by other parts of
* our program. In its current form relies on UseCase.java; as it's contents are
* generated therein. Extends the DefaultComboBox class. authors Wesley Krug,
* Gabriel Steponovich, Michael Brecker, Halston Raddatz
* @version Winter 2015
*****************************************************************/
public class ActorBox extends DefaultComboBoxModel<String> {
/**
* version id.
*/
private static final long serialVersionUID = 1L;
/**
* @param aName a name
*/
public ActorBox(final Vector<String> aName) {
super(aName);
}
/*****************************************************************
* Returns the currently selected UseCase.
*
* @return selectedUSeCase
*****************************************************************/
@Override
public final String getSelectedItem() {
String selectedName = (String) super.getSelectedItem();
return selectedName;
}
}
| Krugw/Term-Project | ActorBox.Java | 251 | /*****************************************************************
* Returns the currently selected UseCase.
*
* @return selectedUSeCase
*****************************************************************/ | block_comment | en | false |