file_id
stringlengths 4
9
| content
stringlengths 146
15.9k
| repo
stringlengths 9
113
| path
stringlengths 6
76
| token_length
int64 34
3.46k
| original_comment
stringlengths 14
2.81k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | excluded
bool 1
class | file-tokens-Qwen/Qwen2-7B
int64 30
3.35k
| comment-tokens-Qwen/Qwen2-7B
int64 3
624
| file-tokens-bigcode/starcoder2-7b
int64 34
3.46k
| comment-tokens-bigcode/starcoder2-7b
int64 3
696
| file-tokens-google/codegemma-7b
int64 36
3.76k
| comment-tokens-google/codegemma-7b
int64 3
684
| file-tokens-ibm-granite/granite-8b-code-base
int64 34
3.46k
| comment-tokens-ibm-granite/granite-8b-code-base
int64 3
696
| file-tokens-meta-llama/CodeLlama-7b-hf
int64 36
4.12k
| comment-tokens-meta-llama/CodeLlama-7b-hf
int64 3
749
| excluded-based-on-tokenizer-Qwen/Qwen2-7B
bool 2
classes | excluded-based-on-tokenizer-bigcode/starcoder2-7b
bool 2
classes | excluded-based-on-tokenizer-google/codegemma-7b
bool 2
classes | excluded-based-on-tokenizer-ibm-granite/granite-8b-code-base
bool 2
classes | excluded-based-on-tokenizer-meta-llama/CodeLlama-7b-hf
bool 2
classes | include-for-inference
bool 2
classes |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
101898_1 | package model;
/**
* A state enumeration storing the states of Australian territory. Used in
* conjunction with the weather model to access weather stations among other
* things.
*
* @author Liam
*/
public enum State {
Antarctica("Antarctica"), Canberra("Canberra"), NewSouthWales("New South Wales"), NorthernTerritory(
"Northern Territory"), Queensland("Queensland"), SouthAustralia("South Australia"), Tasmania(
"Tasmania"), Victoria("Victoria"), WesternAustralia("Western Australia");
private String str;
State(String str) {
this.str = str;
}
/**
* Returns the string representation of this state as it appears in the BOM
* json API.
*
* @return A string representation of the state.
*/
public String getString() {
return str;
}
/**
* Returns The state enum of a given string
*
* @param str
* The string to convert
* @return The state or null if it doesn't exist
*/
public static State fromString(String str) {
switch (str) {
case "Antarctica":
return State.Antarctica;
case "Canberra":
return State.Canberra;
case "New South Wales":
return State.NewSouthWales;
case "Northern Territory":
return State.NorthernTerritory;
case "Queensland":
return State.Queensland;
case "South Australia":
return State.SouthAustralia;
case "Tasmania":
return State.Tasmania;
case "Victoria":
return State.Victoria;
case "Western Australia":
return State.WesternAustralia;
default:
return null;
}
}
}
| rmit-s3372913-Liam-Parker/SEPTAssignment | src/model/State.java | 466 | /**
* Returns the string representation of this state as it appears in the BOM
* json API.
*
* @return A string representation of the state.
*/ | block_comment | en | false | 376 | 39 | 466 | 37 | 413 | 42 | 466 | 37 | 517 | 43 | false | false | false | false | false | true |
103435_3 | import java.util.List;
import java.util.ArrayList;
import java.io.File;
/**
* An album is a collection of images. It reads images from a folder on disk,
* and it can be used to retrieve single images.
*
* @author mik
* @version 1.0
*/
public class Album
{
private List<Image> images;
/**
* Create an Album from a folder in disk.
*/
public Album(String directoryName)
{
images = loadImages(directoryName);
}
/**
* Return a image from this album.
*/
public Image getImage(int imageNumber)
{
return images.get(imageNumber);
}
/**
* Return the number of images in this album.
*/
public int numberOfImages()
{
return images.size();
}
/**
* Load the file names of all files in the given directory.
*/
private List<Image> loadImages(String dirName)
{
File dir = new File(dirName);
if(dir.isDirectory()) {
File[] allFiles = dir.listFiles();
List<Image> foundImages = new ArrayList<Image>();
for(File file : allFiles) {
//System.out.println("found: " + file);
Image image = Image.getImage(file.getPath());
if(image != null) {
foundImages.add(image);
}
}
return foundImages;
}
else {
System.err.println("Error: " + dirName + " must be a directory");
return null;
}
}
}
| MichaelJacob21012/Slideshow | Album.java | 363 | /**
* Return the number of images in this album.
*/ | block_comment | en | false | 321 | 14 | 363 | 14 | 409 | 16 | 363 | 14 | 422 | 16 | false | false | false | false | false | true |
105555_1 | package cp;
import java.nio.file.Path;
import java.util.List;
/**
*
* @author Fabrizio Montesi <[email protected]>
*/
public interface Stats
{
/**
* Returns the number of times that a number was found (across all files).
*/
public int occurrences( int number );
/**
* Returns the number that was found the most times (across all files).
*/
public int mostFrequent();
/**
* Returns the number that was found the least times (of course, you should have found it at least once).
*/
public int leastFrequent();
/**
* Returns a list of all the files found in the directory, ordered from the
* one that contains numbers whose sum across all lines is the smallest
* (first of the list),
* to the one that contains numbers whose sum is the greatest (last of the list).
*/
public List< Path > byTotals();
}
| fmontesi/cp2018 | exam/exam_project/src/cp/Stats.java | 235 | /**
* Returns the number of times that a number was found (across all files).
*/ | block_comment | en | false | 208 | 21 | 235 | 21 | 241 | 22 | 235 | 21 | 255 | 23 | false | false | false | false | false | true |
106445_1 | import java.awt.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.util.ArrayList;
/* This file contains instructions for printing and connecting to input and output devices while the simulator is operating. */
public class Devices extends JFrame{
private ArrayList<JPanel> panel;
private JTextArea ConsoleOut,ConsoleIn;
public int printerStatus=0; // check for console printer : 0 if unused, 1 if used
public Devices(){
super("Console");
this.setSize(960,480);
this.setLayout(null);
panel = new ArrayList<JPanel>();
panel.add(new JPanel());
panel.add(new JPanel());
panel.add(new JPanel());
TitledBorder ConsoleOutBorder = new TitledBorder("Console Printer");
ConsoleOutBorder.setTitleJustification(TitledBorder.CENTER);
ConsoleOutBorder.setTitlePosition(TitledBorder.TOP);
TitledBorder ConsoleInBorder = new TitledBorder("Console Keyboard");
ConsoleInBorder.setTitleJustification(TitledBorder.CENTER);
ConsoleInBorder.setTitlePosition(TitledBorder.TOP);
ConsoleIn = new JTextArea("", 1, 20);
ConsoleOut = new JTextArea(16,38);
ConsoleOut.setFont(new Font("Courrier New",Font.BOLD,14));
//ConsoleOut.setBounds(0,0,350,300);
ConsoleOut.setEditable(false);
ConsoleOut.setBackground(Color.BLACK);
ConsoleOut.setForeground(Color.green);
panel.get(0).setBorder(ConsoleOutBorder);
panel.get(0).add(ConsoleOut);
panel.get(1).setBorder(ConsoleInBorder);
panel.get(1).add(ConsoleIn);
panel.get(0).setBounds(10, 10, 480, 340);
panel.get(1).setBounds((480-250)/2+10, 360, 250, 60);
panel.get(2).setBounds(500,10,440,420);
for(int i=0;i<3;i++)
this.add(panel.get(i));
}
public void emptyConsole(){
ConsoleOut.setText(null);
ConsoleIn.setText(null);
}
public void LoadDevices(short devid, String input){
switch (devid) {
case 1:
//keyboard();
break;
case 2:
//printer(input);
break;
}
}
public int boardstatus=0;
public int keyboardStatus(){
if(ConsoleIn.getText().length()>0) boardstatus=1; //Text in Keyboard
else boardstatus=0; // Empty to Use.
return boardstatus;
}
public void keyboard(char []Reg){
Converter conv = new Converter();
try{
short c = (short)ConsoleIn.getText().charAt(0);
conv.DecimalToBinary(c, Reg, 16);
if(ConsoleIn.getText().length()>1){
ConsoleIn.setText(ConsoleIn.getText().substring(1));
}else if(ConsoleIn.getText().length()==1)
ConsoleIn.setText(null);
}catch(Exception e){
conv.DecimalToBinary((short)0, Reg, 16);
System.out.println("No Input Found");
}
}
public void printer(char[] Reg){
printerStatus=1;
Converter conv = new Converter();
Character dec = (char)conv.BinaryToDecimal(Reg, 16);
StringBuilder build = new StringBuilder();
build.append(dec);
String s = new String(build.toString());
try{
ConsoleOut.append(s);
}catch(Exception e){
return;
}
}
public void Run(){
this.setVisible(true);
}
} | vaibhav-vemula/CSA_Simulator | Devices.java | 887 | // check for console printer : 0 if unused, 1 if used | line_comment | en | false | 784 | 15 | 887 | 15 | 958 | 15 | 887 | 15 | 1,036 | 16 | false | false | false | false | false | true |
107040_2 |
//This is an abstract class rather than an interface because all of the methods are optional
public abstract class View {
//the parent ViewManager... used because Views may be asked to repaint and now need to ask ViewManager to do this.
//note: this starts null but is never set back to null, even when the view becomes inactive... this is to avoid an issue where a repaint is requested just as the view is being removed (a NullPointerException could result).
private ViewManager viewManager = null;
//called by the ViewManager if the view is on the view stack.
//If the view is the topmost one that the user intends to interact with, it is considered active.
//There is a special exception to this relationship for for GameView, PausedView, and GameOverView: PausedView/GameOverView call the GameView's draw directly when the GameView is not on the stack at all so that the presence of blocks, etc. can be controlled more finely.
public void draw(GraphicsWrapper g2, boolean active) {}
//called when the view becomes active, either:
// - by being added to the view stack for the first time, or
// - by another view being removed from the view stack
public void onActive() {}
//called to update the position of the pointer, if this view uses one, when the view is active.
//coordinates are in the 16x10 standard coordinate space
public void pointerUpdate(float cursorX, float cursorY) {}
//called when a key event is received, when this view is active.
public void onKey(int keyCode) {}
//called by ViewManager to notify this View of who its parent is, so it knows who to ask to repaint.
public final void setViewManager(ViewManager vm) {
viewManager = vm;
}
//this exists only so Views can use JOptionPane and similar
public final ViewManager getViewManager() {
return viewManager;
}
//called by the View or anyone who interacts with it that wants a repaint
public final void repaint() {
if (viewManager != null)
viewManager.repaint();
}
//if draw(GraphicsWrapper) is called without indication of being active, assume it's not.
public final void draw(GraphicsWrapper g2) {
draw(g2, false);
}
} | mattbroussard/polydrop-game | src/View.java | 549 | //note: this starts null but is never set back to null, even when the view becomes inactive... this is to avoid an issue where a repaint is requested just as the view is being removed (a NullPointerException could result). | line_comment | en | false | 492 | 45 | 549 | 46 | 540 | 46 | 549 | 46 | 578 | 49 | false | false | false | false | false | true |
109115_5 | package netflix;
import java.io.*;
public class User {
// Instance variables
private String strNickname;
private int intAge;
private boolean blnMaturity;
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
/**
* set constructor
* @param nickname: the user's nickname
* @param age: the user's age
* @param mature: the user's maturity
*/
public User(String strNickname, int intAge, boolean blnMaturity) {
this.strNickname = strNickname;
this.intAge = intAge;
this.blnMaturity = blnMaturity;
}
/**
*
* @return the nickname of the user
*/
public String getNickname() {
return strNickname;
}
/**
*
* @return the age of the user
*/
public int getAge() {
return intAge;
}
/**
*
* @throws IOException read line for user nickname
*/
public void setNickname() throws IOException {
strNickname = input.readLine();
}
/**
*
* @throws IOException read line for user age
*/
public void setAge() throws IOException {
intAge = Integer.parseInt(input.readLine());
}
/**
*
* @return the maturity of the user
*/
public boolean getMaturity() {
return blnMaturity;
}
}
| SACHSTech/oop-assignment-oscarlin05 | src/netflix/User.java | 323 | /**
*
* @throws IOException read line for user age
*/ | block_comment | en | false | 312 | 17 | 323 | 15 | 378 | 19 | 323 | 15 | 430 | 20 | false | false | false | false | false | true |
109892_0 | import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.NoSuchElementException;
import java.util.Scanner;
/**
* Class representing an alarm which is set to go off at a certain
* time every day that it is enabled.
* @author Joshua Evans
* @version Sprint 3, V1.2
* @release 19/04/2016
*/
public class Alarm {
private int alarmHour;
private int alarmMinute;
private boolean isEnabled;
private File alarmFile;
public static String fileDirectory = System.getProperty("user.home") + System.getProperty("file.separator") + "DynOSor" + System.getProperty("file.separator") + "Alarms";
/**
* Constructor given a file, from which it reads all of the data
* necessary for its initialisation.
*
* @param alarmFile The file containing the alarm data.
*/
public Alarm(File alarmFile){
this.alarmFile = alarmFile;
Scanner alarmReader = null;
try {
alarmReader = new Scanner(this.alarmFile);
//Reads alarm hour from file
alarmHour = Integer.parseInt(alarmReader.nextLine());
//Validates alarm hour
if (alarmHour > 23){
alarmHour = 23;
}
else if (alarmHour < 0){
alarmHour = 0;
}
//Reads alarm minute from file
alarmMinute = Integer.parseInt(alarmReader.nextLine());
//Validates alarm minute
if (alarmMinute > 59){
alarmMinute = 59;
}
else if (alarmMinute < 0){
alarmMinute = 0;
}
//Reads alarm isEnabled from file
String isisEnabledString = alarmReader.nextLine();
//Converts string to boolean
if (isisEnabledString.equals("true")){
isEnabled = true;
}
else {
isEnabled = false;
}
}
catch (FileNotFoundException ex){
System.err.println("Could not read from the specified note file because the file could not be found.");
}
catch (NumberFormatException ex){
}
catch (NoSuchElementException ex){
System.err.println("Invalid Appointment File");
}
finally {
assert alarmReader != null;
alarmReader.close();
}
}
/**
* Constructor given a an alarm hour, alarm minute and whether the
* alarm should be enabled or not. Creates an file for storing
* alarm data too.
* @param alarmHour The hour at which the alarm should go off.
* @param alarmMinute The minute at which the alarm should go off.
* @param isEnabled Whether or not the alarm should be enabled.
*/
public Alarm(int alarmHour, int alarmMinute, boolean isEnabled){
this.alarmHour = alarmHour;
this.alarmMinute = alarmMinute;
this.isEnabled = isEnabled;
//Finds an unused filename, then creates the new file.
File newAlarmFile;
int i = 0;
do{
i++;
newAlarmFile = new File(fileDirectory + System.getProperty("file.separator") + "Alarm" + i + ".txt");
} while (newAlarmFile.exists() == true);
alarmFile = newAlarmFile;
updateAlarmFile();
}
/**
* Sets the alarm time.
* @param alarmHour The hour at which the alarm should go off.
* @param alarmMinute The minute at which the alarm should go off.
* @return Whether or not updating the time was successful.
*/
public boolean setAlarmTime(int alarmHour, int alarmMinute){
this.alarmHour = alarmHour;
this.alarmMinute = alarmMinute;
boolean wasSuccessful = updateAlarmFile();
return wasSuccessful;
}
/**
* Sets whether or not the alarm is enabled.
* @param isEnabled Boolean value of whether or not the alarm is enabled.
* @return Whether or not the isEnabled value has been successfully updated.
*/
public boolean setIsEnabled(boolean isEnabled){
this.isEnabled = isEnabled;
boolean wasSuccessful = updateAlarmFile();
return wasSuccessful;
}
public int getAlarmHour(){
return alarmHour;
}
public int getAlarmMinute(){
return alarmMinute;
}
public String getAlarmTimeString(){
return alarmHour + ":" + alarmMinute;
}
public boolean getIsEnabled(){
return isEnabled;
}
public String getIsEnabledString(){
if (isEnabled == true){
return "Alarm Enabled";
}
else {
return "Alarm Disabled";
}
}
/**
* Sets whether or not the alarm is enabled.
* @param isEnabled String value of whether or not the alarm is enabled.
* @return Whether or not the isEnabled value has been successfully updated.
*/
public boolean setIsEnabled(String isEnabledString){
boolean wasSuccessful = false;
if (isEnabledString.toLowerCase().equals("true")){
this.isEnabled = true;
}
else {
this.isEnabled = false;
}
wasSuccessful = updateAlarmFile();
return wasSuccessful;
}
/**
* Updates the alarm file with the current alarm data.
* @return whether or not the file was updated successfully.
*/
public synchronized boolean updateAlarmFile(){
boolean wasSuccessful = false;
PrintWriter alarmWriter = null;
try {
//Writes the alarm's data to a file.
alarmWriter = new PrintWriter(alarmFile);
alarmWriter.println(alarmHour);
alarmWriter.println(alarmMinute);
alarmWriter.println(new Boolean(isEnabled));
//If the method reaches this point, it has successfully completed the writing operation.
wasSuccessful = true;
}
catch (FileNotFoundException ex){
System.err.println("Could not write to specified appointment file because the file could not be found.");
}
finally {
//Closes the file writer
assert alarmWriter != null;
alarmWriter.close();
}
return wasSuccessful;
}
public boolean deleteAlarm(){
boolean wasSuccessful = false;
wasSuccessful = alarmFile.delete();
return wasSuccessful;
}
/**
* Returns the alarm's file.
*
* @return The alarm's file.
*/
public File getFile(){
return alarmFile;
}
}
| QingVer/C-SED-PIM | Alarm.java | 1,542 | /**
* Class representing an alarm which is set to go off at a certain
* time every day that it is enabled.
* @author Joshua Evans
* @version Sprint 3, V1.2
* @release 19/04/2016
*/ | block_comment | en | false | 1,400 | 59 | 1,542 | 65 | 1,634 | 61 | 1,542 | 65 | 2,013 | 63 | false | false | false | false | false | true |
109920_5 | package cp317;
public class Card implements Comparable<Card>{
//Declare types of cards available in a deck
public static final String SUIT[] = {"Clubs", "Diamonds", "Hearts", "Spades"};
public static final String FACE[] = {"2", "3", "4", "5", "6", "7", "8",
"9", "10", "Jack", "Queen", "King", "Ace"};
//*** ADD ENUMERATION TO SIMPLIFY VALUES WITH CARDS ***
/*public enum Face {
TWO(2), THREE(3), FOUR(4), FIVE(5), SIX(6), SEVEN(7), EIGHT(8), NINE(9), TEN(10), JACK(10), QUEEN(10), KING(10), ACE(11);
private int value;
Face(final int value) {
this.value = value;
}
}*/
//Declare variables to instantiate a card
private int suit = 0;
private int face = 0;
private int value = 0;
private int num = 0;
//Instantiate a card object
protected Card(final int suit, final int face, final int value, final int num) {
this.suit = suit;
this.face = face;
this.value = value;
this.num = num;
}
//Allow a card to be formatted and printed (*** Value is here for testing purposes. Remove Later! ***)
@Override
public String toString() {
String card = FACE[this.face] + " of " + SUIT[this.suit] + " --- Value: " + this.value + " Index: " + this.num;
return card;
}
//Get the value of a certain card
public int getValue() {
return this.value;
}
//Get the index of the card
public int getNum() {
return this.num;
}
//Set the value of an ace
public void setAceValue() {
this.value = 1;
}
//Allow cards to be compared to one another (Might need to be tweaked based on the game)
@Override
public int compareTo(Card that) {
// TODO Auto-generated method stub
if (this.value > that.value) {
return 1;
}
else if (this.value < that.value) {
return -1;
}
else {
return 0;
}
}
public static void main(String args[]) {
Card two = new Card(3, 12, 2, 0);
System.out.print(two.toString());
}
}
| G-Iarrusso/casino-night | Card.java | 670 | //Allow a card to be formatted and printed (*** Value is here for testing purposes. Remove Later! ***)
| line_comment | en | false | 585 | 24 | 670 | 25 | 703 | 23 | 670 | 25 | 779 | 23 | false | false | false | false | false | true |
113194_4 | package logic;
import java.util.Collection;
public class Lamp {
private static final Integer[] PRISMATIC_LAMP_EXP_VALUES = {-1, 62, 69, 77, 85, 93, 104, 123, 127, 194, 153, 170, 188,
205, 229, 252, 261, 274, 285, 298, 310, 324, 337, 352, 367, 384, 399, 405, 414, 453, 473, 493, 514, 536, 559,
583, 608, 635, 662, 691, 720, 752, 784, 818, 853, 889, 929, 970, 1012, 1055, 1101, 1148, 1200, 1249, 1304, 1362,
1422, 1485, 1546, 1616, 1684, 1757, 1835, 1911, 2004, 2108, 2171, 2269, 2379, 2470, 2592, 2693, 2809, 2946, 3082,
3213, 3339, 3495, 3646, 3792, 3980, 4166, 4347, 4521, 4762, 4918, 5033, 5375, 5592, 5922, 6121, 6451, 6614, 6928,
7236, 7532, 8064, 8347, 8602, 0};
private static final Integer[] GUTHIXIAN_CACHE_EXP_VALUES = {-1, 1650, 1700, 1750, 1800, 1800, 1850, 1900, 1950, 2000, 2500,
2550, 2600, 2650, 2700, 2750, 2800, 2850, 2900, 2900, 3350, 3400, 3450, 3500, 3550, 3650, 3700, 3750, 3800, 3850, 4050,
4200, 4300, 4500, 4600, 4750, 4850, 5000, 5150, 5250, 7100, 7200, 7350, 7500, 7650, 15600, 15800, 16100, 16300, 16600, 20800,
21300, 21900, 22500, 23000, 23600, 24100, 24600, 25100, 25600, 27800, 28500, 29100, 29800, 30500, 31100, 31700, 32300, 32900,
33400, 35800, 36800, 37700, 38600, 39500, 40400, 41200, 42000, 42800, 43500, 46100, 47000, 47700, 48200, 48400, 50900, 51900,
52700, 53300, 53600, 56600, 57900, 58900, 59500, 59900, 67900, 70000, 71600, 72800, 0};
private Collection<String> choices;
private int xp;
private int minLevel;
public Lamp(Collection<String> choices, int xp, int minLevel) {
this.choices = choices;
this.xp = xp;
this.minLevel = minLevel;
}
public Reward getBestReward(Player player) {
double maxGain = 0;
//Placeholder so null reward doesn't get returned and cause a mess if can't use lamp yet. This should be overwritten
Reward maxReward = new Reward("Attack", 1);
boolean cantUse = true;
for (String choice : choices) {
if (LevelHelper.getLevel(choice, player.getXp().get(choice)) >= minLevel && !choice.equals("Archaeology")) {
cantUse = false;
if (LevelHelper.getLevel(choice, player.getXp().get(choice)) < 99) {
int xpReward = xp;
//-5: Shattered Heart (gold)
if (xp == -5) {
xpReward = (int)(Math.floor(LevelHelper.getLevel(choice, player.getXp().get(choice))*LevelHelper.getLevel(choice, player.getXp().get(choice))*1.2 - LevelHelper.getLevel(choice, player.getXp().get(choice))*2.4 + 120));
}
//-6: Shattered Heart
else if (xp == -6) {
xpReward = LevelHelper.getLevel(choice, player.getXp().get(choice))*LevelHelper.getLevel(choice, player.getXp().get(choice)) - LevelHelper.getLevel(choice, player.getXp().get(choice))*2 + 100;
}
//-7: Troll Invasion
else if (xp == -7) {
xpReward = 8*(LevelHelper.getLevel(choice, player.getXp().get(choice))*LevelHelper.getLevel(choice, player.getXp().get(choice)) - LevelHelper.getLevel(choice, player.getXp().get(choice))*2 + 100);
}
//-1: small pris, -2: med pris, -4: large pris, -8: huge pris, -3: other rewards that use pris formula
else if (xp < 0 && xp > -9) {
xpReward = PRISMATIC_LAMP_EXP_VALUES[LevelHelper.getLevel(choice, player.getXp().get(choice))] * -1 * xp;
}
//-9: dragonkin lamp
else if (xp == -9) {
xpReward = (int) Math.floor((Math.pow(LevelHelper.getLevel(choice, player.getXp().get(choice)), 3) - 2 * Math.pow(LevelHelper.getLevel(choice, player.getXp().get(choice)), 2) + 100 * LevelHelper.getLevel(choice, player.getXp().get(choice))) / 20);
}
//-11: Guthixian Caches
else if (xp == -11) {
xpReward = GUTHIXIAN_CACHE_EXP_VALUES[LevelHelper.getLevel(choice, player.getXp().get(choice))];
}
//-10/-12+: flat level multiplier (ex. goulash, peng points)
else if (xp == -10) {
xpReward = LevelHelper.getLevel(choice, player.getXp().get(choice)) * -1 * xp;
}
else if (xp <= -12) {
xpReward = LevelHelper.getLevel(choice, player.getXp().get(choice)) * -1 * xp;
}
Reward choiceReward = new Reward(choice, xpReward);
double gain = choiceReward.getGainFromReward(player);
if (gain > maxGain) {
maxGain = gain;
maxReward = choiceReward;
}
}
}
}
if (maxReward.getQuantifier() == 1 && maxReward.getQualifier().equals("Attack") && !cantUse) {
maxReward = new Reward("Attack", 2);
}
return maxReward;
}
}
| RenegadeLucien/project-tenacity | src/logic/Lamp.java | 2,211 | //-1: small pris, -2: med pris, -4: large pris, -8: huge pris, -3: other rewards that use pris formula | line_comment | en | false | 2,083 | 33 | 2,211 | 39 | 2,232 | 33 | 2,211 | 39 | 2,448 | 35 | false | false | false | false | false | true |
113591_8 | package com.bridgeLabs.Master;
import java.util.Objects;
/*
* @Class Variables: firstName, lastName, address, city, state, zip, phoneNumber, email
*
* @Class Methods: Setter and Getter methods for variables
*
* @description: UC-1 Ability to create a Contacts in Address Book with first and last names, address,city, state, zip, phone number and email
*/
public class Contact implements Comparable<Contact> {
private String firstName;
private String lastName;
private String address;
private String city;
private String state;
private int zip;
private long phoneNumber;
private String email;
/*
* @Description: Parameterized constructor to initialize the variables
*
* @Param: firstName, lastName, address, city, state, zip, phoneNumber, email
*
* @Return: No return value
*/
public Contact(String firstName, String lastName, String address, String city, String state, int zip,
long phoneNumber, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.city = city;
this.state = state;
this.zip = zip;
this.phoneNumber = phoneNumber;
this.email = email;
}
/*
* @Description: Getter method to get the first name
*
* @Param: No parameters
*
* @Return: String
*/
public String getFirstName() {
return firstName;
}
/*
* @Description: Getter method to get the last name
*
* @Param: No parameters
*
* @Return: String
*/
public String getLastName() {
return lastName;
}
/*
* @Description: Getter method to get the address
*
* @Param: No parameters
*
* @Return: String
*/
public String getAddress() {
return address;
}
/*
* @Description: Getter method to get the city
*
* @Param: No parameters
*
* @Return: String
*/
public String getCity() {
return city;
}
/*
* @Description: Getter method to get the state
*
* @Param: No parameters
*
* @Return: String
*/
public String getState() {
return state;
}
/*
* @Description: Getter method to get the zip
*
* @Param: No parameters
*
* @Return: int
*/
public int getZip() {
return zip;
}
/*
* @Description: Getter method to get the phone number
*
* @Param: No parameters
*
* @Return: long
*/
public long getPhoneNumber() {
return phoneNumber;
}
/*
* @Description: Getter method to get the email
*
* @Param: No parameters
*
* @Return: String
*/
public String getEmail() {
return email;
}
/*
* @Description: Setter method to set the first name
*
* @Param: String
*
* @Return: No return value
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/*
* @Description: Setter method to set the last name
*
* @Param: String
*
* @Return: No return value
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/*
* @Description: Setter method to set the address
*
* @Param: String
*
* @Return: No return value
*/
public void setAddress(String address) {
this.address = address;
}
/*
* @Description: Setter method to set the city
*
* @Param: String
*
* @Return: No return value
*/
public void setCity(String city) {
this.city = city;
}
/*
* @Description: Setter method to set the state
*
* @Param: String
*
* @Return: No return value
*/
public void setState(String state) {
this.state = state;
}
/*
* @Description: Setter method to set the zip
*
* @Param: int
*
* @Return: No return value
*/
public void setZip(int zip) {
this.zip = zip;
}
/*
* @Description: Setter method to set the phone number
*
* @Param: long
*
* @Return: No return value
*/
public void setPhoneNumber(long phoneNumber) {
this.phoneNumber = phoneNumber;
}
/*
* @Description: Setter method to set the email
*
* @Param: String
*
* @Return: No return value
*/
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Name: " + getFirstName() + " " + getLastName() + "\nAddress: " + getAddress() + "\nCity: " + getCity()
+ "\nState: " + getState() + "\nZip: " + getZip() + "\nPhone Number: " + getPhoneNumber() + "\nEmail: "
+ getEmail() + "\n";
}
/*
* @Description: Overriding the toString method to print the contact details
*
* @Param: No parameters
*
* @Return: String
*/
@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
if (!(obj instanceof Contact))
return false;
if (obj == this)
return true;
return this.getFirstName().equalsIgnoreCase(((Contact) obj).getFirstName())
&& this.getLastName().equalsIgnoreCase(((Contact) obj).getLastName());
}
@Override
public int hashCode() {
return Objects.hash(firstName, lastName);
}
@Override
public int compareTo(Contact o) {
String fullName = this.getFirstName() + " " + this.getLastName();
String otherFullName = o.getFirstName() + " " + o.getLastName();
return fullName.compareTo(otherFullName);
}
}
| shro-2002/Address-Book-System | Contact.java | 1,469 | /*
* @Description: Getter method to get the phone number
*
* @Param: No parameters
*
* @Return: long
*/ | block_comment | en | false | 1,361 | 37 | 1,469 | 32 | 1,592 | 40 | 1,469 | 32 | 1,775 | 41 | false | false | false | false | false | true |
114399_2 | import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class Login extends JFrame implements ActionListener{
JButton login,clear,register;
JTextField cardTextField;
JPasswordField pinTextField;
Login(){
setTitle("A.T.M");
setLayout(null);
//image in the login screen
ImageIcon i1 = new ImageIcon(ClassLoader.getSystemResource("image/logo.png"));
Image i2 = i1.getImage().getScaledInstance (100, 100, Image.SCALE_DEFAULT);
ImageIcon i3 = new ImageIcon(i2); //converting image i2 into imageIcon
JLabel label = new JLabel(i3) ;
label.setBounds(70,30,100,100);
add(label);
//for adding text WELCOME TO ATM on atm login screen
JLabel text = new JLabel("WELCOME TO ATM ");
text.setBounds(250,70,400,40);
text.setFont(new Font("Osward",Font.BOLD,33) );
add(text);
//for taking Card number as input from user for login .
JLabel cardno = new JLabel("card no : ");
cardno.setBounds(100,170,200,40);
cardno.setFont(new Font("Osward",Font.BOLD,33) );
add(cardno);
//text field to take input .
cardTextField = new JTextField();
cardTextField.setBounds(270,175,350,40);
cardTextField.setFont(new Font("OSWARD",Font.BOLD,16));
add(cardTextField);
//for taking password as input from user for login .
JLabel pin = new JLabel("Pin : ");
pin.setBounds(100,250,400,40);
pin.setFont(new Font("Osward",Font.BOLD,33) );
add(pin);
//text field to take input .
pinTextField = new JPasswordField();
pinTextField.setBounds(270,250,350,40);
pinTextField.setFont(new Font("OSWARD",Font.BOLD,16));
add(pinTextField);
// LOGIN button after clicking on it user get into his/her account if card number and password is correct .
login = new JButton("LOGIN");
login.setBounds(300,325,100,60);
login.setForeground(Color.BLACK);
login.setFont(new Font("Osward",Font.BOLD,15) );
login.addActionListener(this);
add(login);
//CLEAR button which is used to clear both text field
clear = new JButton("CLEAR");
clear.setBounds(460,325,100,60);
clear.setForeground(Color.BLACK);
clear.setFont(new Font("Osward",Font.BOLD,15) );
clear.addActionListener(this);
add(clear);
//NEW REGISTERATION button for new registration.
register = new JButton("NEW REGISTERATION ");
register.setBounds(300,399,260,60);
register.setForeground(Color.BLACK);
register.setFont(new Font("Osward",Font.BOLD,15) );
register.addActionListener(this);
add(register);
getContentPane().setBackground(Color.lightGray);
setSize(800,550);
setVisible(true);
setLocation(400,200);
}
public void actionPerformed(ActionEvent ae){
//if any action happned in login page like clocking on button
if (ae.getSource() == clear){
//if you clibk on clear button
cardTextField.setText("");
pinTextField.setText("");
}
else if (ae.getSource() == login){
//if you click on login button
Conne conne = new Conne();
String cardnumber = cardTextField.getText();
String pinnumber = pinTextField.getText();
String query = "SELECT * FROM login WHERE CARD_NUMBER = '"+cardnumber+"' and PASSWORD = '"+pinnumber+"'";
try{
ResultSet rs = conne.s.executeQuery(query);
if(rs.next()){
setVisible(false);
new Atm(pinnumber).setVisible(true);
}else{
JOptionPane.showMessageDialog(null,"INCORRECT CARD NUMBER OR PIN ");
}
}
catch (Exception e){
System.out.println(e);
}
}
else if (ae.getSource() == register){
//if you click on new registration button
setVisible(false);
new Signup("").setVisible(true);
}
}
public static void main(String args[]){
new Login();
}
} | PrakashDhami/BankManagementSystem-ATM-_Mini_project | Login.java | 1,106 | //for adding text WELCOME TO ATM on atm login screen | line_comment | en | false | 982 | 13 | 1,106 | 17 | 1,172 | 12 | 1,106 | 17 | 1,333 | 17 | false | false | false | false | false | true |
114661_6 | import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class Doctor {
private int doctorID;
private String doctorName;
private String expertise;
public Doctor(String doctorName, String expertise) {
this.doctorName = doctorName;
this.expertise = expertise;
}
public void registerDoctor() {
Connection connection = null;
try {
connection = connectToDatabase();
addUser(); // Use the common addUser method from the User class
String doctorQuery = "INSERT INTO Doctor (DoctorName, Expertise) VALUES (?, ?)";
PreparedStatement statement = connection.prepareStatement(doctorQuery);
statement.setString(1, doctorName);
statement.setString(2, expertise);
statement.executeUpdate();
System.out.println("Doctor registered successfully");
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeConnection(connection);
}
}
// Add other doctor-related methods as needed...
private void addUser() {
// Implement addUser method from the User class as needed
}
public boolean isAvailableOnDayAndTime(String day, String time) {
// Check if the doctor is available on a specific day and time
// Implement your logic here
return true; // Replace with actual logic
}
public List<Appointment> viewUpcomingAppointments(int days) {
// Implement SQL query to get upcoming appointments for the doctor in the next
// 'days' days
// Return a list of Appointment objects
List<Appointment> appointments = new ArrayList<>();
try (Connection connection = connectToDatabase()) {
// Example query (modify as per your database schema)
String query = "SELECT * FROM Appointment WHERE PatientID = ? AND StartTime <= NOW() + INTERVAL ? DAY";
try (PreparedStatement statement = connection.prepareStatement(query)) {
statement.setInt(1, this.doctorID); // Assuming doctorID is a field in the Doctor class
statement.setInt(2, days);
try (ResultSet resultSet = statement.executeQuery()) {
while (resultSet.next()) {
Appointment appointment = new Appointment(
resultSet.getDate("StartTime"),
resultSet.getDate("EndTime"),
resultSet.getString("Status_"),
resultSet.getInt("PatientID"),
resultSet.getInt("NurseID"),
resultSet.getInt("DoctorID"),
resultSet.getInt("RoomID"));
// Set other appointment details as needed
appointments.add(appointment);
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return appointments;
}
public List<Appointment> filterAppointmentsByPatientName(String patientName) {
// Implement SQL query to get appointments based on patient's name
// Return a list of Appointment objects
List<Appointment> appointments = new ArrayList<>();
try (Connection connection = connectToDatabase()) {
// Example query (modify as per your database schema)
String query = "SELECT * FROM appointments WHERE patient_name = ?";
try (PreparedStatement statement = connection.prepareStatement(query)) {
statement.setString(1, patientName);
try (ResultSet resultSet = statement.executeQuery()) {
while (resultSet.next()) {
Appointment appointment = new Appointment(
resultSet.getDate("StartTime"),
resultSet.getDate("EndTime"),
resultSet.getString("Status_"),
resultSet.getInt("PatientID"),
resultSet.getInt("NurseID"),
resultSet.getInt("DoctorID"),
resultSet.getInt("RoomID"));
// Set other appointment details as needed
appointments.add(appointment);
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return appointments;
}
private Connection connectToDatabase() throws SQLException {
String url = "jdbc:mysql://localhost:3306/cs202_project";
String user = "root";
String password = "Thed4rkside"; // Change this to your database password
return DriverManager.getConnection(url, user, password);
}
protected void closeConnection(Connection connection) {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
protected void closeStatement(PreparedStatement statement) {
try {
if (statement != null) {
statement.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
protected void closeResultSet(ResultSet resultSet) {
try {
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public int getDoctorID() {
return doctorID;
}
public void setDoctorID(int doctorID) {
this.doctorID = doctorID;
}
public String getDoctorName() {
return doctorName;
}
public void setDoctorName(String doctorName) {
this.doctorName = doctorName;
}
public String getExpertise() {
return expertise;
}
public void setExpertise(String expertise) {
this.expertise = expertise;
}
}
| DurthVadr/MedicalAppointmentSystem | Doctor.java | 1,172 | // Implement SQL query to get upcoming appointments for the doctor in the next | line_comment | en | false | 1,074 | 14 | 1,172 | 15 | 1,281 | 14 | 1,172 | 15 | 1,505 | 17 | false | false | false | false | false | true |
118308_3 | /*****************************
Query the University Database
*****************************/
import java.io.*;
import java.sql.*;
import java.util.*;
import java.lang.String;
public class MyQuery {
private Connection conn = null;
private Statement statement = null;
private ResultSet resultSet = null;
public MyQuery(Connection c)throws SQLException
{
conn = c;
// Statements allow to issue SQL queries to the database
statement = conn.createStatement();
}
public void findFall2009Students() throws SQLException
{
String query = "select distinct name from student natural join takes where semester = \'Fall\' and year = 2009;";
resultSet = statement.executeQuery(query);
}
public void printFall2009Students() throws IOException, SQLException
{
System.out.println("******** Query 0 ********");
System.out.println("name");
while (resultSet.next()) {
// It is possible to get the columns via name
// also possible to get the columns via the column number which starts at 1
String name = resultSet.getString(1);
System.out.println(name);
}
}
public void findGPAInfo() throws SQLException
{
String query = "SELECT student.ID, name, ROUND(sum((CASE " +
"WHEN grade = 'F' THEN 0.0 " +
"WHEN grade = 'D-' THEN 0.7 " +
"WHEN grade = 'D' THEN 1.0 " +
"WHEN grade = 'D+' THEN 1.3 " +
"WHEN grade = 'C-' THEN 1.7 " +
"WHEN grade = 'C' THEN 2.0 " +
"WHEN grade = 'C+' THEN 2.3 " +
"WHEN grade = 'B-' THEN 2.7 " +
"WHEN grade = 'B' THEN 3.0 " +
"WHEN grade = 'B+' THEN 3.3 " +
"WHEN grade = 'A-' THEN 3.7 " +
"WHEN grade = 'A' THEN 4.0 " +
"END) * credits) / sum(credits), 2) AS GPA " +
"FROM student JOIN takes USING(ID) JOIN course USING(course_id) " +
"WHERE grade is not null " +
"GROUP BY student.ID;";
resultSet = statement.executeQuery(query);
}
public void printGPAInfo() throws IOException, SQLException
{
System.out.println("******** Query 1 ********");
System.out.printf("| %5s | %-10s | %-4s |%n", "ID", "Name", "GPA");
System.out.printf("-------------------------------%n");
while (resultSet.next()) {
// It is possible to get the columns via name
// also possible to get the columns via the column number which starts at 1
int ID = resultSet.getInt(1);
String Name = resultSet.getString(2);
double GPA = resultSet.getDouble(3);
System.out.printf("| %05d | %-10s | %,.2f |%n", ID, Name, GPA);
}
System.out.printf("-------------------------------%n");
resultSet.close();
}
public void findMorningCourses() throws SQLException
{
String query ="SELECT course_id, sec_id, title, semester, year, name, count(DISTINCT takes.id) enrollment " +
"from course NATURAL JOIN section NATURAL JOIN time_slot NATURAL JOIN teaches NATURAL JOIN instructor " +
"JOIN takes USING (course_id, sec_id, semester, year) " +
"WHERE start_hr <= 12 " +
"GROUP BY course_id, sec_id, semester, year, name " +
"HAVING count(DISTINCT takes.id) > 0;";
this.resultSet = this.statement.executeQuery(query);
}
public void printMorningCourses() throws IOException, SQLException
{
System.out.println("******** Query 2 ********");
System.out.printf("| %-9s | %1s | %-26s | %-8s | %4s | %-10s | %1s |%n", "course_id", "sec_id", "title", "semester", "year",
"name", "enrollment");
System.out.printf("-----------------------------------------------------------------------------------------------%n");
while (resultSet.next()) {
// It is possible to get the columns via name
// also possible to get the columns via the column number which starts at 1
String course_id = resultSet.getString(1);
int sec_id = resultSet.getInt(2);
String title = resultSet.getString(3);
String semester = resultSet.getString(4);
int year = resultSet.getInt(5);
String name = resultSet.getString(6);
int enrollment = resultSet.getInt(7);
System.out.printf("| %-9s | %01d | %-26s | %-8s | %04d | %-10s | %01d |%n", course_id, sec_id, title, semester, year, name, enrollment);
}
}
public void findBusyClassroom() throws SQLException
{
String query = "select building, room_number, count(course_id) as frequency " +
"from section " +
"group by room_number, building " +
"having count(course_id) >= all (select count(course_id) " +
"from section " +
"group by room_number);";
resultSet = statement.executeQuery(query);
}
public void printBusyClassroom() throws IOException, SQLException
{
System.out.println("******** Query 3 ********");
System.out.printf("| %-10s | %-11s | %4s |%n", "Building", "Room_Number", "Frequency");
System.out.printf("----------------------------------------%n");
while (resultSet.next()) {
// It is possible to get the columns via name
// also possible to get the columns via the column number which starts at 1
String building = resultSet.getString(1);
int room_number = resultSet.getInt(2);
int frequency = resultSet.getInt(3);
System.out.printf("| %-10s | %-11s | %01d |%n", building, room_number, frequency);
}
System.out.printf("----------------------------------------%n");
resultSet.close();
}
public void findPrereq() throws SQLException
{
String query = "SELECT c.title as course, " +
"CASE " +
" WHEN c.course_id IN (SELECT course_id FROM prereq) " +
" THEN (SELECT c1.title " +
" FROM course AS c1, prereq AS p " +
" WHERE c.course_id = p.course_id " +
" AND c1.course_id = p.prereq_id) " +
" ELSE 'N/A' " +
"END AS prereq " +
"FROM course AS c;";
resultSet = statement.executeQuery(query);
}
public void printPrereq() throws IOException, SQLException
{
System.out.println("******** Query 4 ********");
System.out.printf("| %-26s | %-26s |%n", "Course", "Prereq");
System.out.printf("-----------------------------------------------------------%n");
while (resultSet.next()) {
// It is possible to get the columns via name
// also possible to get the columns via the column number which starts at 1
String course = resultSet.getString(1);
String prereq = resultSet.getString(2);
System.out.printf("| %-26s | %-26s |%n", course, prereq);
}
System.out.printf("-----------------------------------------------------------%n");
resultSet.close();
}
public void updateTable() throws SQLException
{
statement.executeUpdate("drop table if exists studentCopy");
statement.executeUpdate("CREATE TABLE studentCopy LIKE student");
statement.executeUpdate("INSERT INTO studentCopy SELECT * FROM student");
statement.executeUpdate("UPDATE studentCopy SET tot_cred = "
+ "(SELECT COALESCE(SUM(credits), 0) FROM takes NATURAL JOIN course "
+ "WHERE studentCopy.id = takes.id AND takes.grade != 'F' AND takes.grade IS NOT NULL)");
String query1 = "SELECT studentCopy.*, COUNT(DISTINCT takes.course_id) AS num_of_courses "
+ "FROM studentCopy LEFT JOIN takes ON studentCopy.id = takes.id "
+ "GROUP BY studentCopy.id";
resultSet = statement.executeQuery(query1);
}
public void printUpdatedTable() throws IOException, SQLException
{
System.out.println("******** Query 5 ********");
System.out.printf("| %5s | %-8s | %-10s | %-8s | %17s |%n", "id", "name", "dept_name", "tot_cred", "number_of_courses");
System.out.printf("----------------------------------------------------------------%n");
while (resultSet.next()) {
// It is possible to get the columns via name
// also possible to get the columns via the column number which starts at 1
int id = resultSet.getInt(1);
String name = resultSet.getString(2);
String dept_name = resultSet.getString(3);
int tot_cred = resultSet.getInt(4);
int number_of_courses = resultSet.getInt(5);
System.out.printf("| %05d | %-8s | %-10s | %-8s | %17s |%n", id, name, dept_name, tot_cred, number_of_courses);
}
System.out.printf("----------------------------------------------------------------%n");
resultSet.close();
}
public void findDeptInfo() throws SQLException
{
System.out.println("******** Query 6 ********");
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the department name: ");
String input = scan.nextLine();
CallableStatement cStmt = conn.prepareCall("{call deptInfo(?, ?, ?, ?) }");
cStmt.setString(1, input);
cStmt.registerOutParameter(2, Types.INTEGER);
cStmt.registerOutParameter(3, Types.FLOAT);
cStmt.registerOutParameter(4, Types.FLOAT);
cStmt.execute();
int num_of_instructor = cStmt.getInt(2);
float total_salary = cStmt.getFloat(3);
float budget = cStmt.getFloat(4);
System.out.println(input + " Department has " + num_of_instructor + " instructors.");
System.out.println(input + " Department has a total salary of $" + total_salary);
System.out.println(input + " Department has a budget of $" + budget);
cStmt.close();
}
public void findFirstLastSemester() throws SQLException
{
statement.executeUpdate("CREATE TEMPORARY TABLE tempFirst AS "
+ "SELECT ID, name, CONCAT(CASE MIN(CASE semester "
+ " WHEN 'Fall' THEN 3 "
+ " WHEN 'Spring' THEN 1 "
+ " WHEN 'Summer' THEN 2 "
+ " END) "
+ " WHEN 3 THEN 'Fall' "
+ " WHEN 1 THEN 'Spring' "
+ " WHEN 2 THEN 'Summer' "
+ " END, ' ', year) AS first_semester "
+ "FROM takes NATURAL JOIN student AS T "
+ "WHERE year <= (SELECT MIN(year) "
+ " FROM takes NATURAL JOIN student AS S "
+ " WHERE S.ID = T.ID) "
+ "GROUP BY ID, year");
statement.executeUpdate("CREATE TEMPORARY TABLE tempLast AS "
+ "SELECT ID, name, CONCAT(CASE MAX(CASE semester "
+ " WHEN 'Fall' THEN 3 "
+ " WHEN 'Spring' THEN 1 "
+ " WHEN 'Summer' THEN 2 "
+ " END) "
+ " WHEN 3 THEN 'Fall' "
+ " WHEN 1 THEN 'Spring' "
+ " WHEN 2 THEN 'Summer' "
+ " END, ' ', year) AS last_semester "
+ "FROM takes NATURAL JOIN student AS T "
+ "WHERE year >= (SELECT MAX(year) "
+ " FROM takes NATURAL JOIN student AS S "
+ " WHERE S.ID = T.ID) "
+ "GROUP BY ID, year");
String query = ("SELECT ID, name, first_semester, last_semester "
+ "FROM tempFirst NATURAL JOIN tempLast");
resultSet = statement.executeQuery(query);
}
public void printFirstLastSemester() throws IOException, SQLException
{
System.out.println("******** Query 7 ********");
System.out.printf("| %5s | %-8s | %-15s | %-15s |%n", "id", "name", "First_Semester", "Last_semester");
System.out.printf("--------------------------------------------------------%n");
while (resultSet.next()) {
// It is possible to get the columns via name
// also possible to get the columns via the column number which starts at 1
int id = resultSet.getInt(1);
String name = resultSet.getString(2);
String First_Semester = resultSet.getString(3);
String Last_Semester = resultSet.getString(4);
System.out.printf("| %05d | %-8s | %-15s | %-15s |%n", id, name, First_Semester, Last_Semester);
}
System.out.printf("--------------------------------------------------------%n");
resultSet.close();
}
}
| Evebarr20/CSCD327Project | MyQuery.java | 3,172 | // also possible to get the columns via the column number which starts at 1 | line_comment | en | false | 2,924 | 16 | 3,172 | 16 | 3,382 | 16 | 3,172 | 16 | 3,783 | 16 | false | false | false | false | false | true |
121373_0 |
package cycling;
import java.time.LocalTime;
public class Result {
private int riderId;
private int points;
private int mountainPoints;
private int rank;
private int pointClassificationRank;
private int mountainPointClassificationRank;
private LocalTime[] time;
private Rider rider;
private LocalTime adjustedTime;
private LocalTime stageTime; //I think this is the time it took to complete the stage
public Result(int riderId, int points, int mountainPoints, int rank, int pointClassificationRank, int mountainPointClassificationRank) {
this.riderId = riderId;
this.points = points;
this.mountainPoints = mountainPoints;
this.rank = rank;
this.pointClassificationRank = pointClassificationRank;
this.mountainPointClassificationRank = mountainPointClassificationRank;
}
public int getRiderId() {
return riderId;
}
public int getPoints() {
return points;
}
public int getMountainPoints() {
return mountainPoints;
}
public int getRank() {
return rank;
}
public int getPointClassificationRank() {
return pointClassificationRank;
}
public int getMountainPointClassificationRank() {
return mountainPointClassificationRank;
}
public void setRiderId(int riderId) {
this.riderId = riderId;
}
public void setPoints(int points) {
this.points = points;
}
public void setMountainPoints(int mountainPoints) {
this.mountainPoints = mountainPoints;
}
public void setRank(int rank) {
this.rank = rank;
}
public void setPointClassificationRank(int pointClassificationRank) {
this.pointClassificationRank = pointClassificationRank;
}
public void setMountainPointClassificationRank(int mountainPointClassificationRank) {
this.mountainPointClassificationRank = mountainPointClassificationRank;
}
public LocalTime[] getRiderTimes() {
return time;
}
public Rider getRider() {
return rider;
}
//Dunno if im calculating this or not so leaving it like this for now
public LocalTime getAdjustedTime() {
return adjustedTime;
}
public LocalTime getStageTime() {
return stageTime;
}
}
| Dightful/Cycle-Racing | Result.java | 542 | //I think this is the time it took to complete the stage | line_comment | en | false | 486 | 13 | 542 | 13 | 563 | 13 | 542 | 13 | 656 | 13 | false | false | false | false | false | true |
124015_2 | package kwic;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
/**
* Represent a phrase.
*
*/
public class Phrase implements Comparable{
final protected String phrase;
public Phrase(String s){
phrase = s;
}
/**
* Provide the words of a phrase.
* Each word may have to be cleaned up:
* punctuation removed, put into lower case
*/
public Set<Word> getWords() {
Set<Word> words = new HashSet<Word>();
StringTokenizer st = new StringTokenizer(phrase);
while (st.hasMoreTokens()) {
Word next = new Word(cleanUp(st.nextToken()));
words.add(next);
}
return words;
}
/**
Compares whether two Phrase objects are equal by comparing their strings
*/
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Phrase other = (Phrase) obj;
if (phrase == null) {
if (other.phrase != null)
return false;
} else if (!phrase.equals(other.phrase))
return false;
return true;
}
/**
Returns the hashcode associated with a given phrase.
*/
public int hashCode() {
final int PRIME = 31;
int result = 1;
result = PRIME * result + ((phrase == null) ? 0 : phrase.hashCode());
return result;
}
/** Filter the supplied {@link String} (which is the String of
a {@link Phrase} presumably) into a canonical form
for subsequent matching.
The actual filtering depends on what you consider to be
insignificant in terms of matching.
<UL> <LI> If punctuation is
irrelevant, remove punctuation.
<LI> If case does not matter, than convert to lower (or upper)
case.
</UL>
*/
protected static String cleanUp(String s){
String newString = s.replace("[^\\w]",""); //Regular expression to remove extra characters
return newString.toLowerCase();
}
/**
Used to sort phrases.
*/
@Override
public int compareTo(Object obj) {
if (!(obj instanceof Phrase)){
return 0;
}
Phrase comparePhrase = (Phrase) obj;
return phrase.compareTo(comparePhrase.phrase);
}
/**
Returns the Phrase as a string.
*/
public String toString(){
return phrase;
}
}
| julianozen/kwic_lookup | Phrase.java | 645 | /**
Compares whether two Phrase objects are equal by comparing their strings
*/ | block_comment | en | false | 552 | 18 | 645 | 18 | 654 | 19 | 645 | 18 | 782 | 21 | false | false | false | false | false | true |
124511_9 | /************************************************************/
/* Author: Aidan Donohoe, Eric Chen, Chris O'Brien */
/* Major: Computer Science */
/* Creation Date: 4/24/2024 */
/* Due Date: 4/29/2024 */
/* Course: CS211-02 */
/* Professor Name: Prof. Shimkanon */
/* Assignment: Final Project */
/* Filename: Event.java */
/* Purpose: This program will create the event class */
/************************************************************/
package application;
public class Event
{
public String startTime; //the time the event will begin
public String endTime; //the time the event will end
public String group; //what teams are involved in the event
public String eventName; //the name of the event
public String description; //what is going on at the event or what the reason for it is
public String repeatAmount; //the amount of times the event will repeat, 0 is none
public Event(String s, String e, String g, String n, String d, String r)
{
startTime = s;
endTime = e;
group = g;
eventName = n;
description = d;
repeatAmount = r;
}
public Event()
{
startTime = "";
endTime = "";
group = "";
eventName = "";
description = "";
repeatAmount = "";
}
//getting and setting all of the variables
public String getStartTime()
{
return startTime;
}
public String getEndTime()
{
return endTime;
}
public String getGroup()
{
return group;
}
public String getEventName()
{
return eventName;
}
public String getDescription()
{
return description;
}
public String getRepeatAmount()
{
return repeatAmount;
}
public void setStartTime(String s)
{
startTime = s;
}
public void setEndTime(String e)
{
endTime = e;
}
public void setGroup(String g)
{
group = g;
}
public void setEventName(String e)
{
eventName = e;
}
public void setDescription(String d)
{
description = d;
}
public void setRepeatAmount(String r)
{
repeatAmount = r;
}
public String toString()
{
return eventName;
}
}
| co4008/CS211---Final_Project | Event.java | 622 | /* Purpose: This program will create the event class */ | block_comment | en | false | 504 | 11 | 622 | 11 | 633 | 11 | 622 | 11 | 704 | 12 | false | false | false | false | false | true |
124683_1 | package imogenart.cp;
/**
*
* Contact:
* [email protected]
*
* CoulsonPlotGenerator was created by Helen Imogen Field Copyright. 2010-
*
* Please note all software is released under the Artistic Licence 2.0 until further notice.
* It may be freely distributed and copied providing our notes remain as part of the code.
* Note that under the terms of this licence, versions of classes that you use have to
* continue to work (with the GOtool) and must be made available to us.
* If you would like modifications made please contact me first
* to see if the functions you require are already part of this package.
*
*/
import java.awt.Color;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
/* Class to export a link which opens up a hyperlink in your web browser (as a new window) */
public class Link {
boolean printok = false;
private void p(String s){ if (printok) System.out.println("Link:: "+s); }
public JButton GoLink (String url, String embeddingtext, String linktext, String followtext) throws URISyntaxException {
final URI uri = new URI(url);
// JButton
JButton button = new JButton();
button.setText("<HTML>"+embeddingtext+" <FONT color=\"#000099\"><U>"+linktext+"</U></FONT>"+followtext+"</HTML>");
button.setHorizontalAlignment(SwingConstants.LEFT);
button.setBorderPainted(false);
button.setOpaque(false);
button.setBackground(Color.WHITE);
button.setToolTipText(uri.toString());
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
open(uri);
}
});
return button;//looks like a hyperlink with blue underlined text
}
public JButton buttonLink (String url, String embeddingtext, String linktext, String followtext, Font smallerfont) throws URISyntaxException {
final URI uri = new URI(url);
// JButton
JButton button = new JButton();
button.setName(url);
button.setText("<HTML>"+embeddingtext+" <FONT color=\"#000099\"><U>"+linktext+"</U></FONT>"+followtext+"</HTML>");
button.setHorizontalAlignment(SwingConstants.LEFT);
button.setFont(smallerfont);
button.setForeground(Color.red);
// button.setBorderPainted(false);
//button.setOpaque(false);
// button.setBackground(Color.WHITE);
button.setToolTipText(uri.toString());
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
open(uri);
}
});
return button;
}
private void open(URI uri) {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(uri);
} catch (IOException e) {
p("IOException ") ;e.printStackTrace();
}
} else {
System.out.println("Desktop.isDesktopSupported() - NOT") ;
}
}
public void openBrowser(String url) {
URI uri=null;
try{
uri = new URI(url);
}catch(URISyntaxException us){
System.out.println("URI syntax exception in "+url);
us.printStackTrace();
}
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
try {
if(uri!=null)
desktop.browse(uri);
} catch (IOException e) {
p("IOException ") ;e.printStackTrace();
}
} else {
System.out.println("Desktop.isDesktopSupported() - NOT") ;
}
}
/* Return the complete link item. It is a button lying in a panel
* - you have already initialized a link
* - used by GOontology
*/
public JPanel getLinkbutton(String url, String embeddingtext, String linktext, String followtext, Font font){
JPanel J = new JPanel();
J.setBackground(Color.white);
try{
JButton B = GoLink(url, embeddingtext, linktext, followtext);
B.setFont(font);
B.setBackground(Color.white);
J.add(B);
p("Added button for "+url+" ie "+B);
}catch(Exception e){
p("Could not make link beacuse: "+e);
e.printStackTrace();
}
p("panel with link is "+J);
//J.setSize(new Dimension(10,100));
return J;
}
public Font smallerfont(){
Font smallerfont;
Font oldfont = new JButton().getFont();
String fontstring = new JButton("hello").toString();
if(fontstring.contains("apple")){
smallerfont = new Font(oldfont.getFamily(),oldfont.getStyle(), (oldfont.getSize()-2));//oldfont.deriveFont(new AffineTransform());
} /* end getting smaller font for apple */
else {smallerfont = oldfont;} // dont change font for other OS
return smallerfont;
}
}
| mfield34/CPG | cp/Link.java | 1,278 | /* Class to export a link which opens up a hyperlink in your web browser (as a new window) */ | block_comment | en | false | 1,085 | 22 | 1,278 | 23 | 1,367 | 22 | 1,278 | 23 | 1,535 | 23 | false | false | false | false | false | true |
131077_1 | /* Title: Lesson 1
Description: This program demonstrates a simple hello world
Goal: Run this program to understand how to output to the console
Try this: Try changing the output to say "Goodnight World!" instead
*/
//This is a comment. Note how it starts with 2 / characters
//The name of this class 'Lesson1' needs to be the same as the name of the file
public class Lesson1{
//The following magic line denotes the START of our program
public static void main(String[] args) {
//Notice how the words that print out is "Hello World"
//Also note that the words use " quotes and are within the ()
System.out.println("Hello World!");
//This won't work because we dont have the full command
//println("Hello World!");
//This won't work becuase we are missing the semicolon ; at the end
//System.out.println("Hello World")
}
} | GiantRobato/Java101 | Lesson1.java | 228 | //This is a comment. Note how it starts with 2 / characters | line_comment | en | false | 214 | 15 | 228 | 15 | 225 | 15 | 228 | 15 | 255 | 15 | false | false | false | false | false | true |
131519_3 | // Kirsten Schumy
// Sept. 2, 2017
// Program is based on an assignment for Ada Developers Academy Jump Start, although it's Java
// instead of Ruby, these is more than one possible output, and the user can play again.
//
// This program produces text, partly completed by user input.
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
public class MadLibs {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
Random rand = new Random();
Map<String, String> words = new HashMap<String, String>();
do {
System.out.println("Welcome to MadLibs! Please enter in some information below:");
words = getWords(console, words);
System.out.println("Here's your MadLib...");
if (rand.nextInt(2) == 0) {
outputOne(words); // "Welcome to the University of ___ ..."
} else {
outputTwo(words); // "Welcome to ___ State University..."
}
words.clear();
System.out.print("Play again (y/n)?" );
} while (console.next().toLowerCase().startsWith("y"));
}
// Uses the provided console to store user's responses to the provided words.
// Returns words.
public static Map<String, String> getWords(Scanner console, Map<String, String> words) {
System.out.println();
System.out.print("noun: ");
words.put("noun", console.next());
System.out.print("adjective: ");
words.put("adjOne", console.next());
System.out.print("animal (plural): ");
words.put("animalsOne", console.next());
System.out.print("verb ending in \"-ing\": ");
words.put("verbWithIng", console.next());
System.out.print("number: ");
words.put("number", console.next());
System.out.print("subject in school: ");
words.put("department", console.next());
System.out.print("adjective: ");
words.put("adjTwo", console.next());
System.out.print("sport: ");
words.put("sportsTeam", console.next());
System.out.print("superlative: ");
words.put("superlative", console.next());
System.out.print("animal (plural): ");
words.put("animalsTwo", console.next());
System.out.println();
return words;
}
// Produces text using the provided words.
public static void outputOne(Map <String, String> words) {
System.out.println();
System.out.println("Welcome to the University of " + firstUpper(words.get("noun")) +"!");
System.out.println("As you know, we have many " + words.get("adjTwo") + " programs, "
+ "especially our Department of " + firstUpper(words.get("department")) +".");
System.out.println(firstUpper(words.get("department")) + " professor Dr. " +
firstUpper(words.get("adjOne")) + " just published a groundbreaking study on " +
words.get("number") + " " + words.get("verbWithIng") + " " +
words.get("animalsOne") + ".");
System.out.println("And our " + words.get("sportsTeam") + " team recently won the "
+ "championship for being the " + words.get("superlative") + " in the country!");
System.out.println("Go " + firstUpper(words.get("animalsTwo")) + "!");
System.out.println();
}
// Produces text using the provided words.
public static void outputTwo(Map <String, String> words) {
System.out.println();
System.out.println("Welcome to " + firstUpper(words.get("adjOne")) + " State University!");
System.out.println("As you may have heard, we've had some bad press recently.");
System.out.println(words.get("number") + " students on our " + words.get("sportsTeam") +
" team were recently found guilty of " + words.get("verbWithIng") + " in " +
words.get("department") + " class.");
System.out.println("And there were " + words.get("adjTwo") + " " + words.get("animalsTwo")+
" loose in the dorms.");
System.out.println("And students said we have the " + words.get("superlative") + " " +
words.get("noun") + " they've ever seen.");
System.out.println("But we're sure to bounce back. Go " +
firstUpper(words.get("animalsOne")) + "!");
System.out.println();
}
// Returns the provided word with the first letter capitalized.
public static String firstUpper(String word){
return Character.toUpperCase(word.charAt(0)) + word.substring(1);
}
}
| kschumy/Ada-Jump-Start-Java-Edition | MadLibs.java | 1,276 | // instead of Ruby, these is more than one possible output, and the user can play again. | line_comment | en | false | 1,049 | 20 | 1,276 | 20 | 1,265 | 20 | 1,276 | 20 | 1,449 | 20 | false | false | false | false | false | true |
131974_1 | public class Code {
// Returns "Hello World!"
public static String helloWorld() {
throw new RuntimeException("Not Implemented");
}
// Take a single-spaced <sentence>, and capitalize every <n> word starting with <offset>.
public static String capitalizeEveryNthWord(String sentence, Integer offset, Integer n) {
throw new RuntimeException("Not Implemented");
}
// Determine if a number is prime
public static Boolean isPrime(Integer n) {
throw new RuntimeException("Not Implemented");
}
// Calculate the golden ratio.
// Given two numbers a and b with a > b > 0, the ratio is b / a.
// Let c = a + b, then the ratio c / b is closer to the golden ratio.
// Let d = b + c, then the ratio d / c is closer to the golden ratio.
// Let e = c + d, then the ratio e / d is closer to the golden ratio.
// If you continue this process, the result will trend towards the golden ratio.
public static Double goldenRatio(Double a, Double b) {
throw new RuntimeException("Not Implemented");
}
// Give the nth Fibionacci number
// Starting with 1 and 1, a Fibionacci number is the sum of the previous two.
public static Integer fibionacci(Integer n) {
throw new RuntimeException("Not Implemented");
}
// Give the square root of a number
// Using a binary search algorithm, search for the square root of a given number.
// Do not use the built-in square root function.
public static Double squareRoot(Double n) {
throw new RuntimeException("Not Implemented");
}
}
| athlinks/codetest-1 | Code.java | 375 | // Take a single-spaced <sentence>, and capitalize every <n> word starting with <offset>. | line_comment | en | false | 360 | 21 | 375 | 22 | 402 | 21 | 375 | 22 | 435 | 25 | false | false | false | false | false | true |
134083_0 | /**
* generates the scripts to make nucleotide blast databases from the files containing all genes
*/
package rbh;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class MakeBlastDB {
public static String DIR = "/nobackup/afodor_research/kwinglee/cre/rbh/";
public static void main(String[] args) throws IOException {
BufferedWriter runAll = new BufferedWriter(new FileWriter(new File(
DIR + "makedbScripts/runAll.sh")));//script to run all files
String[] folders = {"carolina", "susceptible", "resistant"};
/*for(String f : folders) {
File folder = new File(DIR + f);
File[] genomes = folder.listFiles();
for(File g : genomes) {
String gen = g.getName();
//set up individual script
BufferedWriter script = new BufferedWriter(new FileWriter(new File(
DIR + "makedbScripts/run" + gen)));
script.write("module load blast\n");
script.write("makeblastdb -in " + g.getAbsolutePath() + "/" + f + "_" + gen + "_allGenes.fasta -dbtype 'nucl'\n");
script.close();
//add to runAll
runAll.write("qsub -q \"viper_batch\" run" + gen + "\n");
}
}*/
for(String f : folders) {
File folder = new File(DIR + f);
File[] genomes = folder.listFiles();
for(File g : genomes) {
String gen = g.getName();
if(gen.endsWith("allGenes.fasta")) {
//set up individual script
BufferedWriter script = new BufferedWriter(new FileWriter(new File(
DIR + "makedbScripts/run" + gen)));
script.write("module load blast\n");
/*script.write("makeblastdb -in " + g.getAbsolutePath() + "/" + f + "_" + gen + "_allGenes.fasta -dbtype 'nucl'\n");*/
script.write("makeblastdb -in " + g.getAbsolutePath() + " -dbtype 'nucl'\n");
script.close();
//add to runAll
runAll.write("qsub -q \"viper_batch\" run" + gen + "\n");
}
}
}
runAll.close();
}
}
| afodor/kPhyloInfer | src/rbh/MakeBlastDB.java | 614 | /**
* generates the scripts to make nucleotide blast databases from the files containing all genes
*/ | block_comment | en | false | 519 | 19 | 614 | 21 | 604 | 20 | 614 | 21 | 795 | 25 | false | false | false | false | false | true |
134749_3 | package api;
import javax.xml.crypto.Data;
import java.io.Serializable;
import java.util.ArrayList;
/**
* Child class of User with the functionalities of a simple type user.
*/
public class Customer extends User implements Serializable{
private ArrayList<Rating>myRatings;
private ArrayList<Accommodation> myRatedAccommodations;
public Customer(String name, String surname, String username, String password) {
super(name, surname, username, password, 1);
myRatings = new ArrayList<>();
}
/**
* This method fetches all ratings from the database and keeps in an ArrayList the ratings that the specific user has submitted.
* @return the ArrayList of user's ratings.
*/
public ArrayList<Rating> getMyRatings(){
for (Rating rating : Database.getRatings()) {
if (rating.getCustomer().equals(this)){
myRatings.add(rating);
}
}
return myRatings;
}
/**
* This method fetches all accommodations from the database and keeps in an ArrayList the accommodation that the specific user has rated.
* @return the ArrayList of user's rated accommodations.
*/
@Override
public ArrayList<Accommodation> getMyAccommodations(){
myRatedAccommodations = new ArrayList<>();
for (Rating rating : Database.getRatings()) {
if (rating.getCustomer().equals(this)){
myRatedAccommodations.add(rating.getAccommodation());
}
}
return myRatedAccommodations;
}
/**
* This method returns the rating that the current customer has submitted for a specific accommodation.
* @param a the accommodation we want to get the rating.
* @return the user's rating.
*/
public Rating getMyRating(Accommodation a) {
for (Rating rating : Database.getRatings()) {
if (rating.getCustomer().equals(this)){
if (rating.getAccommodation().equals(a)) return rating;}
}
return null;
}
/**
* This method returns the average rating score that the current customer has submitted for accommodations.
* @return that score or zero if the customer hasn't rated accommodations yet..
*/
@Override
public float getMyScore(){
float sum = 0;
int count = 0;
for (Rating rating : Database.getRatings()) {
if (rating.getCustomer().equals(this)){
sum += rating.getStars();
count++;
}
}
if (count != 0) return sum/count;
return 0;
}
}
| ThodorisAnninos/appartments-management-system-java | src/api/Customer.java | 594 | /**
* This method returns the rating that the current customer has submitted for a specific accommodation.
* @param a the accommodation we want to get the rating.
* @return the user's rating.
*/ | block_comment | en | false | 546 | 44 | 594 | 48 | 613 | 49 | 594 | 48 | 694 | 51 | false | false | false | false | false | true |
136487_0 |
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.List;
import java.util.ListIterator;
import uk.ac.ucl.comp2010.bestgroup.AST.Node;
import uk.ac.ucl.comp2010.bestgroup.AST.ProgramNode;
import java_cup.runtime.Symbol;
import uk.ac.ucl.comp2010.bestgroup.*;
public class QC {
private static QLex lex;
private static QCup pccParser;
private static String input;
/**
* Prints the int value of tokens created by the lexer object and values
* within the token object (if any)
*
* @throws IOException
*/
private static void lexicalAnalysisOnly() throws IOException {
Symbol token;
while ((token = lex.next_token()).sym != 0) {
System.out.print(token.toString());
System.out.println(token.value != null ? "(" + token.value.toString() + ")" : "");
}
}
public static void main(String[] args) {
try {
boolean lexOnly = false;
boolean repeatCode = false;
boolean checkSemantics = false;
boolean ast = false;
for (String arg : args) {
if (arg.equalsIgnoreCase("--lex")) {
lexOnly = true;
} else if (arg.equalsIgnoreCase("--repeat")) {
repeatCode = true;
}else if (arg.equalsIgnoreCase("--semantics")) {
checkSemantics= true;
}else if (arg.equalsIgnoreCase("--ast")) {
ast = true;
} else {
input = arg;
}
}
lex = new QLex(new FileReader(input));
pccParser = new QCup(lex);
if (lexOnly) {
lexicalAnalysisOnly();
} else {
System.out.println("Parsing\n-------");
Symbol parse_tree = pccParser.parse();
if(repeatCode) {
System.out.println("\n\nRepeating code\n--------------");
new CodeOutputVisitor().visit((ProgramNode)parse_tree.value);
}
if(checkSemantics) {
System.out.println("\n\nRunning Semantics Visitor\n---------------------");
new SemanticsVisitor().visit((ProgramNode)parse_tree.value);
}
if(ast) {
System.out.println("\nAST\n---");
displayTree(parse_tree.value, 0);
}
}
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
}
public static void displayTree(Object node, int i) {
if(node == null) {
System.out.println("null");
return;
}
System.out.println(node.getClass().getSimpleName());
Field[] nodeFields = node.getClass().getFields();
for(Field field: nodeFields) {
if(java.lang.reflect.Modifier.isStatic(field.getModifiers()) || field.getName() == "lineNumber" || field.getName() == "charNumber") {
continue;
}
try {
if(Node.class.isInstance(field.get(node))) {
System.out.print(indent(i+2) + field.getName() + " = ");
displayTree(field.get(node), i+2 + field.getName().length() + 3);
} else if(List.class.isInstance(field.get(node)) && field.get(node) != null){
System.out.print(indent(i+2) + field.getName() + " = ");
ListIterator<Object> li = ((List) field.get(node)).listIterator();
if(! li.hasNext()) {
System.out.println("[empty list]");
} else {
while(li.hasNext()) {
if(li.hasPrevious()) {System.out.print(indent(i+2 + field.getName().length() + 3));}
System.out.print("*");
Object o = li.next();
if(Node.class.isInstance(o)) {
displayTree(o, i+2 + field.getName().length() + 4);
} else {
System.out.println(o);
}
}
}
//} else if(ExprOperationNode.class.isInstance(node) && field.getName() == "op") {
} else if(! (field.getName()=="type" && field.get(node) == null)){
System.out.println(indent(i+2) + field.getName() + " = " + field.get(node));
}
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
public static String indent(int level) {
String s = "";
for(int i=0; i<level; i++) {
s = s + " ";
}
return s;
}
}
| Globegitter/QLanguageAnalyser | src/QC.java | 1,250 | /**
* Prints the int value of tokens created by the lexer object and values
* within the token object (if any)
*
* @throws IOException
*/ | block_comment | en | false | 1,007 | 38 | 1,250 | 35 | 1,328 | 41 | 1,250 | 35 | 1,603 | 44 | false | false | false | false | false | true |
137461_0 | import java.util.Date;
public class Accident {
private Date date;
private Breakable[] involvedCars;
private Street location;
public Accident(Date date, Breakable[] involvedCars, Street location) {
setDate(date);
setInvovledCars(involvedCars);
this.location = location;
}
private void setDate(Date date){
this.date = date;
}
private void setInvovledCars(Breakable[] cars){
if (cars.length > 1) this.involvedCars = cars;
else throw new IllegalArgumentException("Can not make an accident with one car");
}
public Date getDate() {
return date;
}
public Breakable[] getInvolvedCars() {
return involvedCars;
}
public Street getLocation(){
return this.location;
}
public int getTimeToFix(){
int max = 0;
for (Breakable car : involvedCars){
if (car.getTimeToFix() > max) max = car.getTimeToFix();
}
return max;
}
public boolean isDone(){
for (Breakable car : this.involvedCars){
/*
if broken flag is set and currAcc is ref to this instance
then the accident is not done.
The ref to accident should be null if fix() of car is invoked
*/
if (car.isBroken() &&
((CivilVehicle)car).getCurrentAccident() == this) {
return false;
}
}
return true;
}
}
| EngOsamah/Hajj-simulation | src/Accident.java | 352 | /*
if broken flag is set and currAcc is ref to this instance
then the accident is not done.
The ref to accident should be null if fix() of car is invoked
*/ | block_comment | en | false | 318 | 42 | 352 | 40 | 376 | 44 | 352 | 40 | 428 | 44 | false | false | false | false | false | true |
138539_5 | /**
* An object of the RNG class generates a random number from a minimum value to a maximum
* value.
*
* @author (Sugandh Singhal)
* @version (26-10-2019)
*/
public class RNG
{
private int maximumValue;
private int minimumValue;
/**
* Default Constructor for objects of class RNG
*/
public RNG()
{
maximumValue = 0;
minimumValue = 0;
}
/**
* Non Default Constructor for objects of class RNG
*
* @param newMax integer to define the new maximum value for the random number
* @param newMin integer to define the new minimum value for the random number
*/
public RNG(int newMax, int newMin)
{
maximumValue = newMax;
minimumValue = newMin;
}
/**
* Method to display value of fields
*
* @return A single string which contains the maximum and minimum value for random number seperated by spaces
*/
public String displayRNG()
{
return maximumValue + " " + minimumValue;
}
/**
* Accessor Method to get the maximum value for random number generation
*
* @return A integer which contains the maximum value
*/
public int getMaximumValue()
{
return maximumValue;
}
/**
* Accessor Method to get the minimum value for random number generation
*
* @return A integer which contains the minimum value
*/
public int getMinimumValue()
{
return minimumValue;
}
/**
* Mutator Method to set the maximum value for random number generation
*
* @param newMaximumValue integer to define the the maximum value
*/
public void setMaximumValue(int newMaximumValue)
{
maximumValue = newMaximumValue;
}
/**
* Mutator Method to set the minimum value for random number generation
*
* @param newMinimumValue integer to define the the minimum value
*/
public void setMinimumValue(int newMinimumValue)
{
minimumValue = newMinimumValue;
}
}
| SugandhSinghal/256-with-Arraylists-Java-Application | RNG.java | 472 | /**
* Accessor Method to get the minimum value for random number generation
*
* @return A integer which contains the minimum value
*/ | block_comment | en | false | 495 | 33 | 472 | 30 | 592 | 36 | 472 | 30 | 616 | 36 | false | false | false | false | false | true |
138543_7 | import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.regex.Pattern;
public class Main {
// Define constants for the minimum / maximum age required to be a client
private static final int MINIMUM_AGE = 18;
private static final int MAXIMUM_AGE = 100;
/**
* Check if a given client name is valid
*
* @param clientName the name of the client to check
* @return true if the name is valid, false otherwise
*/
private static boolean isValidClientName(String clientName) {
// Validate that the client name does not contain numbers
return !Pattern.compile("[0-9]").matcher(clientName).find();
}
/**
* Check if a given client age is valid
*
* @param clientAge the age of the client to check
* @return true if the age is valid, false otherwise
*/
private static boolean isValidClientAge(String clientAge) {
// Validate that the client age is a valid integer
try {
int age = Integer.parseInt(clientAge);
return age >= MINIMUM_AGE && age <= MAXIMUM_AGE; // Age should be a positive integer, higher than 18 (majority)
} catch (NumberFormatException e) {
System.err.println("Client Age must be an integer: " + e.getMessage());
} catch (Exception e) {
System.err.println("Exception error occurred in the code: " + e.getMessage());
}
return false;
}
public static void main(String[] args) {
// Create a new Store object
Store store = new Store();
// Create a new Scanner object to read input from the console
Scanner scanner = new Scanner(System.in);
// Load library data from file
store.setClients(Database.loadFromFile());
int choice = 0;
do {
// Print the main menu to the console
System.out.println("\nLibrary Management System");
String choices[] = { "Add Client", "Buy Vehicles", "Display Clients",
"Display All Vehicles", "Display Client's Vehicles", "Exit" };
// Print the menu options to the console
try {
for (int i = 1; i <= choices.length; i++) {
System.out.println(i + ". " + choices[i - 1]);
}
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Array index out of bounds when looping through choices array: " + e.getMessage());
} catch (Exception e) {
System.err.println("Exception error occurred in the code: " + e.getMessage());
}
// Prompt the user to enter their choice
System.out.print("Enter your choice: ");
try {
choice = scanner.nextInt();
} catch (InputMismatchException e) {
System.err.println("Choice must be a number between 1 and 6: " + e.getMessage());
} catch (Exception e) {
System.err.println("Exception error occurred in the code: " + e.getMessage());
} finally {
scanner.nextLine(); // Consume the newline character
}
// Handle the user's choice
switch (choice) {
case 1:
// Add a new client
System.out.print("Enter Client Name: ");
String clientName = scanner.nextLine();
if (isValidClientName(clientName) == false) {
System.out.println("Invalid client name. Please enter a valid name without numbers.");
continue;
}
System.out.print("Enter Client Age: ");
String clientAge = scanner.nextLine();
if (isValidClientAge(clientAge) == false) {
System.out.println("Invalid client age. Age should be a positive integer, older than 18 years old (majority) and younger than 100 years old.");
continue;
}
System.out.print("Enter Client Nationality: ");
String clientNationality = scanner.nextLine();
store.addClient(new Client(clientName, Integer.parseInt(clientAge), clientNationality));
break;
case 2:
// Buy a vehicle for a client
store.displayClients();
System.out.print("Enter Client ID: ");
String clientId = scanner.nextLine();
if (store.findClientById(clientId) == null) {
System.out.println("Invalid client ID. Please enter an existing client ID.");
continue;
}
store.displayVehicles();
System.out.print("Enter Vehicle ID: ");
String vehicleId = scanner.nextLine();
if (store.findVehicleById(vehicleId) == null) {
System.out.println("Invalid vehicle ID. Please enter an existing vehicle ID.");
continue;
}
store.purchaseVehicle(vehicleId, clientId);
break;
case 3:
// Display all clients
store.displayClients();
break;
case 4:
// Display all vehicles
store.displayVehicles();
break;
case 5:
// Display a client's vehicles
store.displayClients();
System.out.print("Enter Client ID: ");
clientId = scanner.nextLine();
store.displayClientByID(store.findClientById(clientId));
break;
case 6:
// Exit the program
System.out.println("Exiting the Library Management System. Goodbye!");
break;
default:
// Handle invalid choices
System.out.println("Invalid choice. Please enter a number between 1 and 6.");
break;
}
} while (choice != 6);
// Save library data to file before exiting
Database.saveToFile(store.getClients());
// Close the Scanner object
scanner.close();
}
} | twillsonepitech/oop-java-project | Main.java | 1,278 | // Create a new Scanner object to read input from the console | line_comment | en | false | 1,189 | 12 | 1,278 | 12 | 1,393 | 12 | 1,278 | 12 | 1,557 | 12 | false | false | false | false | false | true |
138951_1 | //: pony/Flam.java
package pokepon.pony;
import pokepon.enums.*;
/** Flam
* Quite balanced stats, with higher defs than atks,
* and good hp.
*
* @author silverweed
*/
public class Flam extends Pony {
public Flam(int _level) {
super(_level);
name = "Flam";
type[0] = Type.CHAOS;
type[1] = Type.LAUGHTER;
race = Race.UNICORN;
sex = Sex.MALE;
baseHp = 98;
baseAtk = 60;
baseDef = 75;
baseSpatk = 65;
baseSpdef = 92;
baseSpeed = 75;
/* learnableMoves ... */
learnableMoves.put("Hidden Talent",1);
learnableMoves.put("Sonic Barrier",1);
learnableMoves.put("Mirror Pond",1);
learnableMoves.put("Taunt",1);
learnableMoves.put("Dodge",1);
learnableMoves.put("Chatter",18);
learnableMoves.put("Magic Blast",20);
learnableMoves.put("Applebuck",35);
learnableMoves.put("Horn Beam",44);
learnableMoves.put("Freeze Spell",56);
}
}
| silverweed/pokepon | pony/Flam.java | 357 | /** Flam
* Quite balanced stats, with higher defs than atks,
* and good hp.
*
* @author silverweed
*/ | block_comment | en | false | 306 | 28 | 357 | 35 | 335 | 32 | 357 | 35 | 429 | 37 | false | false | false | false | false | true |
140564_1 | 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例 1:
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
示例 2:
输入:l1 = [], l2 = []
输出:[]
示例 3:
输入:l1 = [], l2 = [0]
输出:[0]
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/merge-two-sorted-lists
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode dummy=new ListNode(0);
ListNode current=dummy;
while(list1!=null&&list2!=null){
if(list1.val<list2.val){
current.next=list1;
list1=list1.next;
}else{
current.next=list2;
list2=list2.next;
}
current=current.next;
}
if(list1!=null){
current.next=list1;
}
if(list2!=null){
current.next=list2;
}
return dummy.next;
}
}
思路:定义新的链表头部为dummy,并用指针指向头部,依次遍历两个链表,判断,将其加入新的链表里,最后判断是否有剩余
| aaaaaaliang/LeetCode1 | L46.java | 466 | /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/ | block_comment | en | false | 397 | 65 | 466 | 81 | 462 | 80 | 466 | 81 | 608 | 88 | false | false | false | false | false | true |
141228_6 | import java.util.Collection;
import java.util.ArrayList;
/**
A directed graph implementation optimized for sparse graphs.
Incidence lists are used to keep track of adjacencies.
@param <V> Type of vertex element
@param <E> Type of edge element
*/
public final class SparseGraph<V, E> implements Graph<V, E> {
private final class IncidenceVertex implements Vertex<V> {
public Collection<DirectedEdge> outgoing;
public Collection<DirectedEdge> incoming;
public V data;
public Object label;
public boolean removed;
public IncidenceVertex(V d) {
this.outgoing = new ArrayList<DirectedEdge>();
this.incoming = new ArrayList<DirectedEdge>();
this.data = d;
this.label = null;
this.removed = false;
}
@Override
public V get() { return this.data; }
@Override
public void put(V v) { this.data = v; }
public SparseGraph<V, E> manufacturer() {
return this.removed ? null : SparseGraph.this;
}
}
private final class DirectedEdge implements Edge<E> {
public IncidenceVertex from;
public IncidenceVertex to;
public E data;
public Object label;
public boolean removed;
private DirectedEdge(IncidenceVertex f, IncidenceVertex t, E d) {
this.from = f;
this.to = t;
this.data = d;
this.label = null;
this.removed = false;
}
@Override
public E get() { return this.data; }
@Override
public void put(E e) { this.data = e; }
public SparseGraph<V, E> manufacturer() {
return this.removed ? null : SparseGraph.this;
}
}
private Collection<IncidenceVertex> vertices;
private Collection<DirectedEdge> edges;
/** New SparseGraph instance. */
public SparseGraph() {
this.vertices = new ArrayList<IncidenceVertex>();
this.edges = new ArrayList<DirectedEdge>();
}
@SuppressWarnings("unchecked") // We're typesafe because we use instanceof.
private IncidenceVertex validateVertex(Vertex<V> v)
throws IllegalArgumentException {
if (v == null) {
throw new IllegalArgumentException("Inputted Vertex is null.");
} else if (!(v instanceof SparseGraph.IncidenceVertex)) {
throw new IllegalArgumentException("Inputted Vertex unusable"
+ "by SparseGraph.");
}
IncidenceVertex validee = (IncidenceVertex) v;
if (!(validee.manufacturer() == this)) {
throw new IllegalArgumentException("Inputted Vertex does not "
+ "belong to this SparseGraph.");
}
return validee;
}
@SuppressWarnings("unchecked") // We're typesafe because we use instanceof.
private DirectedEdge validateEdge(Edge<E> e)
throws IllegalArgumentException {
if (e == null) {
throw new IllegalArgumentException("Inputted Edge is null.");
} else if (!(e instanceof SparseGraph.DirectedEdge)) {
throw new IllegalArgumentException("Inputted Edge unusable "
+ "by SparseGraph.");
}
DirectedEdge validee = (DirectedEdge) e;
if (!(validee.manufacturer() == this)) {
throw new IllegalArgumentException("Inputted Edge does not"
+ "belong to this SparseGraph.");
}
return validee;
}
@Override
public Vertex<V> insert(V v) {
IncidenceVertex newVertex = new IncidenceVertex(v);
this.vertices.add(newVertex);
return newVertex;
}
private boolean isDuplicateEdge(Collection<DirectedEdge> c,
IncidenceVertex from, IncidenceVertex to) {
for (DirectedEdge e : c) {
if (e.from == from && e.to == to) {
return true;
}
}
return false;
}
@Override
public Edge<E> insert(Vertex<V> from, Vertex<V> to, E e) {
DirectedEdge insert;
IncidenceVertex f;
IncidenceVertex t;
// validation
Collection<DirectedEdge> search;
if (from == to) {
throw new IllegalArgumentException("Can't create self-loops.");
}
f = this.validateVertex(from);
t = this.validateVertex(to);
search = f.outgoing.size() <= t.incoming.size()
? f.outgoing : t.incoming;
if (this.isDuplicateEdge(search, f, t)) {
throw new IllegalArgumentException("Can't insert duplicate edges.");
}
insert = new DirectedEdge(f, t, e);
f.outgoing.add(insert);
t.incoming.add(insert);
this.edges.add(insert);
return insert;
}
@Override
public V remove(Vertex<V> vertex) {
// validation
IncidenceVertex v = this.validateVertex(vertex);
if (!(v.outgoing.isEmpty() && v.incoming.isEmpty())) {
throw new IllegalArgumentException("Can't remove Vertex with"
+ "incoming or outgoing edges");
}
v.removed = true;
this.vertices.remove(v);
return v.data;
}
@Override
public E remove(Edge<E> edge) {
DirectedEdge e = this.validateEdge(edge);
e.removed = true;
e.from.outgoing.remove(e);
e.to.incoming.remove(e);
this.edges.remove(e);
return e.data;
}
@Override
public Iterable<Vertex<V>> vertices() {
Collection<Vertex<V>> verts = new ArrayList<Vertex<V>>();
verts.addAll(this.vertices);
return verts;
}
@Override
public Iterable<Edge<E>> edges() {
Collection<Edge<E>> edgs = new ArrayList<Edge<E>>();
edgs.addAll(this.edges);
return edgs;
}
@Override
public Iterable<Edge<E>> outgoing(Vertex<V> vertex) {
IncidenceVertex v = this.validateVertex(vertex);
Collection<Edge<E>> outs = new ArrayList<Edge<E>>();
outs.addAll(v.outgoing);
return outs;
}
@Override
public Iterable<Edge<E>> incoming(Vertex<V> vertex) {
IncidenceVertex v = this.validateVertex(vertex);
Collection<Edge<E>> ins = new ArrayList<Edge<E>>();
ins.addAll(v.incoming);
return ins;
}
@Override
public Vertex<V> from(Edge<E> edge) {
DirectedEdge e = this.validateEdge(edge);
return e.from;
}
@Override
public Vertex<V> to(Edge<E> edge) {
DirectedEdge e = this.validateEdge(edge);
return e.to;
}
@Override
public void label(Vertex<V> vertex, Object l) {
IncidenceVertex v = this.validateVertex(vertex);
if (l == null) {
throw new IllegalArgumentException("Can't label null.");
}
v.label = l;
return;
}
@Override
public void label(Edge<E> edge, Object l) {
DirectedEdge e = this.validateEdge(edge);
if (l == null) {
throw new IllegalArgumentException("Can't label null.");
}
e.label = l;
return;
}
@Override
public Object label(Vertex<V> vertex) {
IncidenceVertex v = this.validateVertex(vertex);
return v.label;
}
@Override
public Object label(Edge<E> edge) {
DirectedEdge e = this.validateEdge(edge);
return e.label;
}
@Override
public void clearLabels() {
for (IncidenceVertex v : this.vertices) {
v.label = null;
}
for (DirectedEdge e : this.edges) {
e.label = null;
}
return;
}
/**
Converts to GraphViz-compatible string format.
@return The string.
*/
public String toString() {
String result = "digraph {\n";
for (IncidenceVertex v : this.vertices) {
result += " \"" + v.data.toString() + "\";\n";
}
for (DirectedEdge e : this.edges) {
result += " \"" + e.from.data.toString() + "\""
+ " -> "
+ "\"" + e.to.data.toString() + "\""
+ " [label=\"" + e.data.toString() + "\"];\n";
}
result += "}";
return result;
}
}
| matthew-richard/finding-kevin-bacon | SparseGraph.java | 1,972 | /**
Converts to GraphViz-compatible string format.
@return The string.
*/ | block_comment | en | false | 1,779 | 19 | 1,969 | 19 | 2,154 | 23 | 1,972 | 19 | 2,418 | 26 | false | false | false | false | false | true |
144573_1 | package irvine.oeis.a111;
// Generated by gen_seq4.pl deriv at 2021-06-28 18:44
import irvine.math.z.Z;
import irvine.oeis.Sequence;
import irvine.oeis.Sequence1;
import irvine.oeis.a023.A023201;
import irvine.oeis.a046.A046117;
/**
* A111192 Product of the n-th sexy prime pair.
* @author Georg Fischer
*/
public class A111192 extends Sequence1 {
final Sequence mA023201 = new A023201();
final Sequence mA046117 = new A046117();
@Override
public Z next() {
return mA023201.next().multiply(mA046117.next());
}
}
| archmageirvine/joeis | src/irvine/oeis/a111/A111192.java | 252 | /**
* A111192 Product of the n-th sexy prime pair.
* @author Georg Fischer
*/ | block_comment | en | false | 211 | 25 | 252 | 32 | 242 | 28 | 252 | 32 | 262 | 29 | false | false | false | false | false | true |
144597_4 | package geneticAlgorithm;
/**
* creates a population of individuals
*
* @author Leo
*/
public class Population {
Individual[] individuals;
int populationSize;
Individual fittestEnd;
static final boolean DEBUG = false;
static final boolean sexySon = false;
/**
* initialize a population with random individuals
* @param populationSize
* @param init
*/
public Population(int populationSize, boolean init){
this.populationSize = populationSize;
this.individuals = new Individual[populationSize];
for(int i = 0; i < populationSize; i++){
Individual individual = new Individual();
if(!Evolution.GENEPOOL){
individuals[i] = individual.generateIndividualRandom();
}
else{
individuals[i] = individual.generateIndividualFromGenePool();
}
if(sexySon && i == populationSize-1){
individuals[i] = individual.generateSexySon();
}
}
}
/**
* creates new empty population
* @param populationSize
*/
public Population(int populationSize){
this.individuals = new Individual[populationSize];
this.populationSize = populationSize;
}
/**
* adding individual to population at position i
* @param i
* @param individual
*/
public void addIndividual(int i, Individual individual){
individuals[i] = individual;
}
/**
* overwrite individuals of a population to next generation
* @param nextGeneration
*/
public void takeOver(Population nextGeneration){
for(int i = 0; i < populationSize; i++){
this.individuals[i] = nextGeneration.individuals[i];
}
}
/**
* resets population
*/
public void resetEmpty(){
for(int i = 0; i < populationSize; i++){
this.individuals[i] = null;
}
}
public Individual getFittest(){
Individual fittest = individuals[0];
if (fittestEnd == null)
{
fittestEnd = individuals[0];
}
for(int i = 0; i < populationSize; i++){
if(individuals[i].getFitness() < fittest.getFitness()){
fittest = individuals[i];
if (fittest.getFitness() < fittestEnd.getFitness())
{
fittestEnd = fittest;
}
}
}
return fittest;
}
public Individual getIndividual(int i){
return individuals[i];
}
public void print(){
if (fittestEnd == null)
{
fittestEnd = individuals[0];
}
System.out.println("============");
//System.out.println("Fittest Up until now All INDIVIDUAL: " + fittestEnd.velVector + ", initVel: " + fittestEnd.initVel + ", fitness " + fittestEnd.fitness + ", distance: " + fittestEnd.distanceVector + ", position: " + fittestEnd.position);
System.out.println("Fittest until now INDIVIDUAL " + fittestEnd.getFitness() + ", Velocity: " + fittestEnd.velVector + "; position: " + fittestEnd.posVector + "; initVel: " + fittestEnd.initVel + ", distance: " + fittestEnd.distanceVector + ", position: " + fittestEnd.position);
System.out.println("============");
// for(int i = 0; i < populationSize; i++){
// System.out.println("INDIVIDUAL: " + individuals[i].velVector + ", initVel: " + individuals[i].initVel + ", fitness " + individuals[i].fitness + ", distance: " + individuals[i].distanceVector + ", position: " + individuals[i].position);
// }
}
}
| chiarapaglioni/SpacetravelToTitan | src/geneticAlgorithm/Population.java | 865 | /**
* overwrite individuals of a population to next generation
* @param nextGeneration
*/ | block_comment | en | false | 803 | 21 | 865 | 19 | 909 | 22 | 865 | 19 | 1,028 | 23 | false | false | false | false | false | true |
145119_8 | /*
*take a game object and calc the highest piece
* determine if the highest piece is in a corner
* a trial is when the ai executes one move
* and then random moves until a win or loss
* keeps track of the highest score and which
* ever inital direction has the highest score
* tells the ai to make that direction
*
*
* try to upgrade trial so it can look at x moves infront
* instead of just one move ahead
*/
import java.util.Random;
public class Trial {
public gameObject myGameObject;//keep track of initial board
public gameObject trialGame;
public int [] originalBoard = {0,1,2,3,4,5,6,7,8,9,1,1,1,1,1,1};
Trial(gameObject myGameObject){
this.myGameObject = myGameObject;
this.trialGame = new gameObject();
this.originalBoard = getOriginalBoard(myGameObject.getCurrentBoard());
setTrialGame();
}
public int[] getOriginalBoard(int [] board){
for(int i = 0; i < board.length; i++){
originalBoard[i] = board[i] ;
}
return originalBoard;
}
public void setTrialGame(){
trialGame.setBoard(originalBoard);
}
/*
* try all four moves possible on the current board
* keep track of the score
* which ever move gives the highest score,
* return that move
*
*/
public String executeTrial(int numMoves){
String [] firstMoves = {"LEFT", "RIGHT", "UP", "DOWN", };
int maxScore = 0;
String bestMove = "";
String randomMove = "";
int counter = 0;
for(int i = 0; i < firstMoves.length; i++){//need to keep track of original board position
//make first move
counter = 0;
getOriginalBoard(originalBoard);
trialGame.setBoard(originalBoard);
trialGame.turn(firstMoves[i]);
while(trialGame.getCanStillPlay() && counter < numMoves){//execute random moves till loss
Random random = new Random();
String [] moves = {"LEFT", "RIGHT", "UP", "DOWN", };
randomMove = moves[random.nextInt(moves.length)];
try{
trialGame.turn(randomMove);
}
catch(Exception e){
}
if(trialGame.getScore(trialGame.board) > maxScore){//if the left turn has highest score, return left as move
maxScore = trialGame.getScore(trialGame.board);//keep track of highest score
bestMove = firstMoves[i];
}
if(i == 6){ //when the first move makes no diff, it keeps the getCanStillPlay variable as false
System.out.println(randomMove);//while loop doesn't execute
trialGame.printBoard();
}
counter++;
}
// System.out.println("move is " + firstMoves[i] + " this moves score is " + myGameObject.getScore(myGameObject.board));
}
// System.out.println("max score was: " + maxScore);
return bestMove;
}
/*
* make an advanced trial that calculates the score
* based if the highest value piece is in the top left corner
* additionally only takes the highest piece value as the score
* score = biggest value + 20 if topLeft
*/
public String advancedTrial(int numMoves){
String [] firstMoves = {"LEFT", "RIGHT", "UP", "DOWN", };
int maxScore = 0;
String bestMove = "";
String randomMove = "";
int counter = 0;
int fitnessScore = 0;
for(int i = 0; i < firstMoves.length; i++){//need to keep track of original board position
//make first move
counter = 0;
fitnessScore = 0;
getOriginalBoard(originalBoard);
trialGame.setBoard(originalBoard);
trialGame.turn(firstMoves[i]);
while(trialGame.getCanStillPlay() && counter < numMoves){//execute random moves till loss
Random random = new Random();
String [] moves = {"LEFT", "RIGHT", "UP", "DOWN", };
randomMove = moves[random.nextInt(moves.length)];
try{
trialGame.turn(randomMove);
}
catch(Exception e){
}
fitnessScore = trialGame.getBiggestValue(trialGame.getCurrentBoard());
if(trialGame.getTopLeft(trialGame.getCurrentBoard())){
fitnessScore += 20;
}
if(fitnessScore > maxScore){//if the left turn has highest score, return left as move
maxScore = fitnessScore;//keep track of highest score
bestMove = firstMoves[i];
}
counter++;
}
// System.out.println("move is " + firstMoves[i]);
// trialGame.printBoard();
}
// System.out.println("best move" + bestMove);
return bestMove;
}
}
| danielkachelmyer/2048_Game | Trial.java | 1,153 | //when the first move makes no diff, it keeps the getCanStillPlay variable as false | line_comment | en | false | 1,075 | 19 | 1,153 | 19 | 1,239 | 19 | 1,153 | 19 | 1,361 | 20 | false | false | false | false | false | true |
145812_3 | /**
Small class representing a Java program.
This is used in the sample main as a
way to abstract out information so
that the autograder does not have to be
updated every time from scratch for a new
project and can just be updated in the
run_autograder file.
@author Brandon Lax
@see AutograderMain
*/
public class Program {
/**The name of the program.*/
private String name;
/**The number of cooresponding diff tests.*/
private int testCount;
/**The number of cooresponding unit tests.*/
private int unitCount;
/**Whether the file exists in the submission.*/
private boolean exists;
/**Whether the file was written by the student*/
private boolean userWritten;
/**Whether there are junits for the file*/
private boolean junits;
/**
Public constructor of the class.
@param newName the name of the program
@param diffCount the number of diff tests
@param unitCount the number of comparison tests
@param written stores low bit is user written and 2's bit is junits or not
*/
Program(String newName, String diffCount, String unitCount, String written) {
this.name = newName;
this.testCount = Integer.parseInt(diffCount);
this.unitCount = Integer.parseInt(unitCount);
this.exists = true;
this.userWritten = (Integer.parseInt(written) & 1) > 0;
this.junits = (Integer.parseInt(written) & 2) > 0;
}
/**
returns whether the file exists.
@return exists
*/
public boolean exists() {
return this.exists;
}
/** Set whether a submission file exists.
@param b whether it exists
*/
public void setExists(boolean b) {
this.exists = b;
}
/**
Getter for the name.
@return the name
*/
public String name() {
return this.name;
}
/**
Getter for the test count.
@return the test count
*/
public int testCount() {
return this.testCount;
}
/**
Getter for the unitCount.
@return the unit Count
*/
public int unitCount() {
return this.unitCount;
}
/**
Metho to check who wrote the java file.
@return true if written by student false if a starter file
*/
public boolean userWritten() {
return this.userWritten;
}
/**
Method to check if the file has junits attacked.
@return true if junits false otherwise
*/
public boolean hasJunits() {
return this.junits;
}
} | bralax/gradescope_autograder | Program.java | 596 | /**The number of cooresponding unit tests.*/ | block_comment | en | false | 598 | 12 | 596 | 11 | 695 | 10 | 596 | 11 | 731 | 12 | false | false | false | false | false | true |
147952_0 | /**
* Class: Robot
* @author Nathan Jackels
* Description: The only seen by the application's control class. All Keyboard/Mouse/App work is delegated through this class by Control.
*/
public class Robot {
private Application[] apps = new Application[0];
private Keyboard keyboard = null;
private Controller control = null;
/**
* Method: Robot(Control control)
* @author Nathan Jackels
* @param control The reference to control so that packets can be sent back to control.
* Description: The constructor for the class
*/
public Robot(Controller control){
//TODO Create Programs and Classes
this.control = control;
this.keyboard = new Keyboard();
if(keyboard.getKeyboard() == null){
this.keyboard = null;
}
apps = new Application[4];
apps[0] = new VLC(keyboard,control);
apps[1] = new Computer(keyboard);
apps[2] = new Chrome(keyboard);
apps[3] = new PhotoViewer(keyboard);
}
/**
* Method: sendPacket(RobotPacket e)
* @author Nathan Jackels
* @param e The RobotPacket that will be interpreted by the Robot class
* @return The resulting packet from the command (most likely either something to display, or null)
* @see TSP/Control/Robot_Packet_Design
* Description: The method used by Control to delegate work to the Robot class
*/
public RobotPacket sendPacket(RobotPacket e){
System.out.println("Got packet");
if((e.getApplication() == null) || (e.getApplication().length() == 0) || (e.getEvent() == null) || (e.getEvent().length() == 0)){
return new RobotPacket("Robot", "BadPacket", null);
}
if(this.keyboard == null){
this.keyboard = new Keyboard();
if(this.keyboard == null){
String[] infos = new String[e.getInfo().length + 2];
infos[0] = e.getApplication();
infos[1] = e.getEvent();
for(int i = 0; i < e.getInfo().length; i++){
infos[2+i] = e.getInfo()[i];
}
return new RobotPacket("Robot", "CommandFailed", infos);
} else {
for(Application t : apps){
t.setKeyboard(this.keyboard);
}
}
}
for(Application app : apps){
if(app.getName().toLowerCase().equals(e.getApplication().toLowerCase())){
System.out.println("Found an app");
return app.interpret(e);
}
}
return new RobotPacket("Robot", "BadPacket", null);
}
}
| natejackels/DisappointingProject | src/Robot.java | 671 | /**
* Class: Robot
* @author Nathan Jackels
* Description: The only seen by the application's control class. All Keyboard/Mouse/App work is delegated through this class by Control.
*/ | block_comment | en | false | 598 | 41 | 671 | 49 | 688 | 48 | 671 | 49 | 843 | 51 | false | false | false | false | false | true |
148124_0 | package com.company;
//this keyword is used to refer to the current object in a method or constructor
//it's help to differ between class attributes and parameters with same name
class Employees{
int salary;// attributes of this class employee
//let's create a constructor of this Employees class with salary parameters
public Employees(int salary){
this.salary = salary;//here this.salary refers attributes of Employees class not parameters of constructors
}
public int getSalary() {
return salary;
}
}
public class UseThis {
public static void main(String[] args) {
Employees emo = new Employees(5000);
System.out.println( emo.getSalary());
}
}
| kppaudel10/Basic_java | UseThis.java | 161 | //this keyword is used to refer to the current object in a method or constructor | line_comment | en | false | 145 | 17 | 161 | 17 | 169 | 17 | 161 | 17 | 196 | 17 | false | false | false | false | false | true |
149254_0 | import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.PriorityQueue;
import java.util.Queue;
public class Adrese {
private static class GraphPlatform {
private HashMap<PlatformInstance, List<PlatformInstance>> relationshipPlatform;
private Integer noInstances;
public GraphPlatform() {
this.relationshipPlatform = new HashMap<>();
}
public void addVertex(PlatformInstance vertex) {
relationshipPlatform.put(vertex, new ArrayList<>());
}
public boolean hasVertex(PlatformInstance key) {
return relationshipPlatform.containsKey(key);
}
public void addEdge(PlatformInstance s, PlatformInstance d) {
relationshipPlatform.get(s).add(d);
relationshipPlatform.get(d).add(s);
}
public void setNoInstances(Integer noInstances) {
this.noInstances = noInstances;
}
public HashMap<PlatformInstance, List<PlatformInstance>> getRelationshipPlatform() {
return relationshipPlatform;
}
}
private static class PlatformInstance {
String name;
// 0 - userName, 1 - address
int type;
// this one will be used not only to differentiate between
// people holding the same userName, but which might be different,
// but also for arrays like visited.
int id;
public PlatformInstance(String name, int type, int id) {
this.name = name;
this.type = type;
this.id = id;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PlatformInstance that = (PlatformInstance) o;
if ((type == 1) && (that.type == 1)) {
return name.equals(that.name);
}
return type == that.type && id == that.id && Objects.equals(name, that.name);
}
@Override
public int hashCode() {
if (type == 0) {
return Objects.hash(id);
} else if (type == 1) {
return Objects.hash(name);
}
return 0;
}
}
public static GraphPlatform createGraphPlatfom() {
MyScanner scanner = new MyScanner("adrese.in");
GraphPlatform graphPlatform = new GraphPlatform();
relationshipPlatform = graphPlatform.getRelationshipPlatform();
int N = scanner.nextInt();
HashMap<PlatformInstance, Integer> emails = new HashMap<>();
int id = 0;
// for each username, read mail addresses associated with it
// and other data like, number of mails, etc.
for (int crtUser = 0; crtUser < N; crtUser++) {
String[] infoUser = scanner.nextLine().split(" ");
String nameUser = infoUser[0];
PlatformInstance user = new PlatformInstance(nameUser, 0, id);
id++;
graphPlatform.addVertex(user);
int NoAddresses = Integer.parseInt(infoUser[1]);
for (int i = 0; i < NoAddresses; i++) {
PlatformInstance newMail = new PlatformInstance(scanner.next(), 1, id);
if (!(graphPlatform.hasVertex(newMail))) {
graphPlatform.addVertex(newMail);
emails.put(newMail, id);
id++;
} else {
newMail.id = emails.get(newMail);
}
graphPlatform.addEdge(user, newMail);
}
}
graphPlatform.setNoInstances(id);
return graphPlatform;
}
private static Boolean[] visited;
static class ResultFormat {
String userName;
Integer noMails;
PriorityQueue<String> mails;
public void setUserName(String userName) {
this.userName = userName;
}
public Integer getNoMails() {
return noMails;
}
public void setNoMails(Integer noMails) {
this.noMails = noMails;
}
public PriorityQueue<String> getMails() {
return mails;
}
public void setMails(PriorityQueue<String> mails) {
this.mails = mails;
}
}
public static ResultFormat bfs_util(PlatformInstance platformInstance) {
PriorityQueue<String> emails = new PriorityQueue<>();
String lowestName = BIGGESTNAME;
Queue<PlatformInstance> queue = new LinkedList<>();
queue.add(platformInstance);
ResultFormat result = new ResultFormat();
int no = 0;
while (!(queue.isEmpty())) {
PlatformInstance crtElem = queue.remove();
if (crtElem.type == 0) {
// case username
if (lowestName.compareTo(crtElem.name) > 0) {
lowestName = crtElem.name;
}
} else if (crtElem.type == 1) {
// case mail
emails.add(crtElem.name);
no++;
}
List<PlatformInstance> succs = relationshipPlatform.get(crtElem);
for (PlatformInstance succ : succs) {
if (visited[succ.id] == null) {
visited[succ.id] = true;
queue.add(succ);
}
}
}
result.setUserName(lowestName);
result.setMails(emails);
result.setNoMails(no);
return result;
}
static class ComparatorResult implements Comparator<ResultFormat> {
@Override
public int compare(ResultFormat a, ResultFormat b) {
int diff = a.noMails - b.noMails;
if (diff != 0) {
return diff;
}
return a.userName.compareTo(b.userName);
}
}
static HashMap<PlatformInstance, List<PlatformInstance>> relationshipPlatform;
public static Integer bfs(GraphPlatform graphPlatform) {
visited = new Boolean[graphPlatform.noInstances];
List<ResultFormat> results = new ArrayList<>();
Integer counts = 0;
HashMap<PlatformInstance, List<PlatformInstance>> relationshipPlatform =
graphPlatform.getRelationshipPlatform();
for (PlatformInstance platformInstance: relationshipPlatform.keySet()) {
if (visited[platformInstance.id] == null) {
visited[platformInstance.id] = true;
ResultFormat result = bfs_util(platformInstance);
results.add(result);
counts++;
}
}
Collections.sort(results, new ComparatorResult());
String crtMail;
try {
BufferedWriter bufWriter = new BufferedWriter(new FileWriter("adrese.out"));
bufWriter.write(String.valueOf(counts));
bufWriter.newLine();
for (ResultFormat result: results) {
bufWriter.write(result.userName + " " + result.noMails);
bufWriter.newLine();
PriorityQueue<String> mails = result.mails;
while ((crtMail = mails.poll()) != null) {
bufWriter.write(crtMail);
bufWriter.newLine();
}
}
bufWriter.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
System.out.println(counts);
return 1;
}
public static final String BIGGESTNAME = "ZZZZZZZZZZZZZZZZZZZZ";
public static void main(String[] args) {
GraphPlatform graphPlatform = createGraphPlatfom();
bfs(graphPlatform);
}
}
| Petruc-Rares/PA_HW_2---Applied_Algorithms | Adrese.java | 1,956 | // 0 - userName, 1 - address | line_comment | en | false | 1,632 | 11 | 1,956 | 10 | 1,892 | 10 | 1,956 | 10 | 2,447 | 11 | false | false | false | false | false | true |
149621_3 | /*
* Copyright (C) 2021 Grakn Labs
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
package grakn.core;
import grakn.core.common.parameters.Arguments;
import grakn.core.common.parameters.Options;
import grakn.core.concept.ConceptManager;
import grakn.core.logic.LogicManager;
import grakn.core.query.QueryManager;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Stream;
/**
* A Grakn Database API
*
* This interface allows you to open a 'Session' to connect to the Grakn
* database, and open a 'Transaction' from that session.
*/
public interface Grakn extends AutoCloseable {
Session session(String database, Arguments.Session.Type type);
Session session(String database, Arguments.Session.Type type, Options.Session options);
DatabaseManager databases();
boolean isOpen();
void close();
/**
* Grakn Database Manager
*/
interface DatabaseManager {
boolean contains(String name);
Database create(String name);
Database get(String name);
Set<? extends Database> all();
}
/**
* A Grakn Database
*
* A database is an isolated scope of data in the storage engine.
*/
interface Database {
String name();
boolean contains(UUID sessionID);
Session get(UUID sessionID);
Stream<Session> sessions();
void delete();
}
/**
* A Grakn Database Session
*
* This interface allows you to create transactions to perform READs or
* WRITEs onto the database.
*/
interface Session extends AutoCloseable {
Transaction transaction(Arguments.Transaction.Type type);
Transaction transaction(Arguments.Transaction.Type type, Options.Transaction options);
UUID uuid();
Arguments.Session.Type type();
Database database();
boolean isOpen();
void close();
}
/**
* A Grakn Database Transaction
*/
interface Transaction extends AutoCloseable {
Arguments.Transaction.Type type();
Options.Transaction options();
boolean isOpen();
ConceptManager concepts();
LogicManager logic();
QueryManager query();
void commit();
void rollback();
void close();
}
}
| Sayanta66/grakn | Grakn.java | 660 | /**
* A Grakn Database
*
* A database is an isolated scope of data in the storage engine.
*/ | block_comment | en | false | 590 | 28 | 660 | 27 | 701 | 30 | 660 | 27 | 802 | 30 | false | false | false | false | false | true |
150520_2 | /*
Copyright 2006 by Sean Luke and George Mason University
Licensed under the Academic Free License version 3.0
See the file "LICENSE" for more information
*/
package ec.eval;
import ec.*;
import java.io.*;
import ec.util.*;
/**
* Job.java
*
This class stores information regarding a job submitted to a Slave: the individuals,
the subpopulations in which they are stored, a scratch array for the individuals used
internally, and various coevolutionary information (whether we should only count victories
single-elimination-tournament style; which individuals should have their fitnesses updated).
<p>Jobs are of two types: traditional evaluations (Slave.V_EVALUATESIMPLE), and coevolutionary
evaluations (Slave.V_EVALUATEGROUPED). <i>type</i> indicates the type of job.
For traditional evaluations, we may submit a group of individuals all at one time.
Only the individuals and their subpopulation numbers are needed.
Coevolutionary evaluations require the number of individuals, the subpopulations they come from, the
pointers to the individuals, boolean flags indicating whether their fitness is to be updated or
not, and another boolean flag indicating whether to count only victories in competitive tournament.
* @author Liviu Panait
* @version 1.0
*/
public class Job
{
// either Slave.V_EVALUATESIMPLE or Slave.V_EVALUATEGROUPED
int type;
boolean sent = false;
Individual[] inds; // original individuals
Individual[] newinds; // individuals that were returned -- may be different individuals!
int[] subPops;
boolean countVictoriesOnly;
boolean[] updateFitness;
void copyIndividualsForward()
{
if (newinds == null || newinds.length != inds.length)
newinds = new Individual[inds.length];
for(int i=0; i < inds.length; i++)
{
newinds[i] = (Individual)(inds[i].clone());
}
}
// a ridiculous hack
void copyIndividualsBack(EvolutionState state)
{
try
{
DataPipe p = new DataPipe();
DataInputStream in = p.input;
DataOutputStream out = p.output;
for(int i = 0; i < inds.length; i++)
{
p.reset();
newinds[i].writeIndividual(state, out);
inds[i].readIndividual(state, in);
}
newinds = null;
}
catch (IOException e)
{
e.printStackTrace();
state.output.fatal("Caught impossible IOException in Job.copyIndividualsBack()");
}
}
}
| malyzajko/xfp | ec/eval/Job.java | 636 | // either Slave.V_EVALUATESIMPLE or Slave.V_EVALUATEGROUPED | line_comment | en | false | 573 | 17 | 636 | 24 | 643 | 19 | 636 | 24 | 730 | 27 | false | false | false | false | false | true |
151679_0 | package aeriesrefresher;
//basic container class to conveniently hold all attributes of a class
public class Class {
private String name;
private String lastUpdated;
private String teacher;
private String grade;
public Class(String n, String l, String t, String g){
name = n;
lastUpdated = l;
teacher = t;
grade = g;
}
public String getName(){
return name;
}
public String getLastUpdated(){
return lastUpdated;
}
public String getTeacher(){
return teacher;
}
public String getGrade(){
return grade;
}
public String toString(){
return name + " (" + teacher + "): " + grade + ", " + lastUpdated + " ||";
}
}
| matthewgrossman/AeriesProgram | Class.java | 195 | //basic container class to conveniently hold all attributes of a class
| line_comment | en | false | 163 | 13 | 195 | 14 | 221 | 13 | 195 | 14 | 245 | 14 | false | false | false | false | false | true |
151861_1 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.testing;
import io.trino.Session;
import io.trino.Session.SessionBuilder;
import io.trino.client.ClientCapabilities;
import io.trino.execution.QueryIdGenerator;
import io.trino.metadata.SessionPropertyManager;
import io.trino.spi.security.Identity;
import io.trino.spi.type.TimeZoneKey;
import java.util.Arrays;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static java.util.Locale.ENGLISH;
public final class TestingSession
{
private static final QueryIdGenerator queryIdGenerator = new QueryIdGenerator();
/*
* Pacific/Apia
* - has DST (e.g. January 2017)
* - DST backward change by 1 hour on 2017-04-02 04:00 local time
* - DST forward change by 1 hour on 2017-09-24 03:00 local time
* - had DST change at midnight (on Sunday, 26 September 2010, 00:00:00 clocks were turned forward 1 hour)
* - had offset change since 1970 (offset in January 1970: -11:00, offset in January 2017: +14:00, offset in June 2017: +13:00)
* - a whole day was skipped during policy change (on Friday, 30 December 2011, 00:00:00 clocks were turned forward 24 hours)
*/
public static final TimeZoneKey DEFAULT_TIME_ZONE_KEY = TimeZoneKey.getTimeZoneKey("Pacific/Apia");
private TestingSession() {}
public static Session testSession()
{
return testSessionBuilder().build();
}
public static Session testSession(Session session)
{
return testSessionBuilder(session).build();
}
public static SessionBuilder testSessionBuilder()
{
return testSessionBuilder(new SessionPropertyManager());
}
public static SessionBuilder testSessionBuilder(SessionPropertyManager sessionPropertyManager)
{
return Session.builder(sessionPropertyManager)
.setQueryId(queryIdGenerator.createNextQueryId())
.setIdentity(Identity.ofUser("user"))
.setOriginalIdentity(Identity.ofUser("user"))
.setSource("test")
.setCatalog("catalog")
.setSchema("schema")
.setTimeZoneKey(DEFAULT_TIME_ZONE_KEY)
.setLocale(ENGLISH)
.setClientCapabilities(Arrays.stream(ClientCapabilities.values()).map(Enum::name)
.collect(toImmutableSet()))
.setRemoteUserAddress("address")
.setUserAgent("agent");
}
public static SessionBuilder testSessionBuilder(Session session)
{
return Session.builder(session)
.setQueryId(queryIdGenerator.createNextQueryId());
}
}
| trinodb/trino | core/trino-main/src/main/java/io/trino/testing/TestingSession.java | 844 | /*
* Pacific/Apia
* - has DST (e.g. January 2017)
* - DST backward change by 1 hour on 2017-04-02 04:00 local time
* - DST forward change by 1 hour on 2017-09-24 03:00 local time
* - had DST change at midnight (on Sunday, 26 September 2010, 00:00:00 clocks were turned forward 1 hour)
* - had offset change since 1970 (offset in January 1970: -11:00, offset in January 2017: +14:00, offset in June 2017: +13:00)
* - a whole day was skipped during policy change (on Friday, 30 December 2011, 00:00:00 clocks were turned forward 24 hours)
*/ | block_comment | en | false | 738 | 237 | 844 | 245 | 859 | 243 | 844 | 245 | 943 | 252 | true | true | true | true | true | false |
152004_12 | public class Mountain {
public static void main(String[] args) {
}
public int peakIndexInMountainArray(int[] arr){
int start = 0;
int end = arr.length-1;
while (start< end){
// find the middle element
// int mid = (start + mid)/2;
//might be possible that(start+end)
int mid =start + (end - start) /2;
if(arr[mid] > arr[mid+1]){
// you are in dec part of array
// this may be the ans, but look at left
// this is why end!= mid -1
end=mid;
} else{
// you are in asc part of array
start = mid +1; // because we know that mid+1 element > mid elemen
}
}
// in the end, start == end and pointing to the largest number because of the 2 checks above
// start and end are always trying to find max element in the above 2 checks
// hence, when they are pointing to just one element, that is the max one because that is what the checks say
// more elaboration: at every point of time for start and end, they have the best possible answer till that time
// and if we are saying that only one item is remaining, hence cause of above line that is the best possible ans
return start; // or return end as both are =
}
}
| ashish2675/100DaysOfCode | Mountain.java | 321 | // and if we are saying that only one item is remaining, hence cause of above line that is the best possible ans
| line_comment | en | false | 320 | 25 | 321 | 25 | 358 | 25 | 321 | 25 | 366 | 25 | false | false | false | false | false | true |
152025_12 | package VtigerCRM;
import java.io.IOException;
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import CommonUtils.ExcelUtil;
import CommonUtils.JavaUtil;
import CommonUtils.ListnerImplimentation;
import CommonUtils.PropertyFileUtil;
import CommonUtils.WebDriverUtil;
@Listeners(ListnerImplimentation.class)
public class Organizations {
PropertyFileUtil putil=new PropertyFileUtil();
WebDriverUtil wutil=new WebDriverUtil();
ExcelUtil eutil=new ExcelUtil();
JavaUtil jutil=new JavaUtil();
@Test
public void OrganizationTest() throws IOException, InterruptedException
{
WebDriver d=new ChromeDriver();
//To maximize the window
wutil.maximize(d);
//to apply wait to findelement()
wutil.implicitWait(d);
// d.manage().window().maximize();
// d.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
//To read data from Property File
String URL = putil.getDataFromPropertyFile("Url");
String USERNAME = putil.getDataFromPropertyFile("Username");
String PASSWORD = putil.getDataFromPropertyFile("Password");
//To read data from excel file
String orgName = eutil.getDataFromExcel("Organisations", 0, 1);
String group = eutil.getDataFromExcel("Organisations", 1, 1);
//To launch the url
d.get(URL);
//To Enter useraname and password
d.findElement(By.name("user_name")).sendKeys(USERNAME);
d.findElement(By.name("user_password")).sendKeys(PASSWORD);
//Click on Login
d.findElement(By.id("submitButton")).click();
//Click on Organisation
d.findElement(By.xpath("(//a[text()='Organizations'])[1]")).click();
//Click on Create Organization (+)
d.findElement(By.cssSelector("img[alt='Create Organization...']")).click();
//click on account name and type "Qspiders"
//Random methos is created in javautil class to run the class multiple times.
d.findElement(By.cssSelector("input[name='accountname']")).sendKeys(orgName+jutil.getRandomNumber());
//In Assigned to click on group
//Click on Assigned radio button
d.findElement(By.xpath("(//input[@name='assigntype'])[2]")).click();
//
//In the dropdown Select support group
// //click on dropdown
WebElement dropDown = d.findElement(By.name("assigned_group_id"));
wutil.handleDropDown(dropDown, group);
//Click on save button
d.findElement(By.xpath("(//input[@name='button'])[3]")).click();
//To takescreenshot
wutil.screenShot(d, "Organization");
Thread.sleep(2000);
//MouseHover on image to signout
WebElement image = d.findElement(By.cssSelector("img[src='themes/softed/images/user.PNG']"));
wutil.mouseHover(d, image);
//Click on signout
d.findElement(By.xpath("//a[text()='Sign Out']")).click();
}
}
| GauriBhirad/m2 | Organizations.java | 903 | //click on account name and type "Qspiders"
| line_comment | en | false | 731 | 13 | 903 | 13 | 949 | 12 | 903 | 13 | 1,118 | 12 | false | false | false | false | false | true |
152079_40 | package police;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import criminals.Organization;
import criminals.Member;
import interfaces.List;
import lists.ArrayList;
public class PoliceDepartment {
/**
* Creates an instance of PoliceDepartment. It receives the name of the Captain
* as a parameter.
*
* @param captain - (String) Name of the captain of the Police Department
*/
// Define a String variable called "captain" to store the name of the captain
String captain;
// Define an int variable called "organizationPosition" to keep track of the
// organization position
int organizationPosition = 0;
// Define an ArrayList variable called "criminalOrganizations" to contain
// objects of the "Organization" class
List<Organization> criminalOrganizations = new ArrayList<>();
// Define an int variable called "arrest" to keep track of the number of arrests
// made by the police department
int arrest;
// Constructor for the "PoliceDepartment" class that takes a "captain" parameter
public PoliceDepartment(String captain) {
// Set the "captain" member variable to the value of the "captain" parameter
this.captain = captain;
}
/**
* Returns the List of Criminal Organizations that the Police Department has on
* record.
*/
// Getter method for the criminal organizations list
public List<Organization> getCriminalOrganizations() {
// Return the value of the "criminalOrganizations" member variable
return this.criminalOrganizations;
}
/**
* Does the setup of the criminal organizations List.
*
* This method will read each organization file in the Criminal Organization
* folder and and add each one to the criminal organization List.
*
* NOTE: The order the files are read is important. The files should be read in
* alphabetical order.
*
* @param caseFolder - (String) Path of the folder containing the criminal
* organization files.
* @throws IOException
*/
// This method sets up the list of criminal organizations for the police
// department
public void setUpOrganizations(String caseFolder) throws IOException {
// Construct the path to the folder containing the criminal organization files
String path = caseFolder + File.separator + "CriminalOrganizations";
// Create a File object for the folder
File folder = new File(path);
// Get an array of File objects for all files in the folder
File[] listOfFiles = folder.listFiles();
// Sort the list of files in alphabetical order
Arrays.sort(listOfFiles);
// Loop through each file in the array
for (File file : listOfFiles) {
// Check if the file is actually a file (not a directory)
if (file.isFile()) {
// Get the name of the file
String name = file.getName();
// Create an Organization object using the file path
Organization organization = new Organization(path + File.separator + name);
// Add the Organization object to the list of criminal organizations
this.criminalOrganizations.add(organization);
}
}
}
/**
* Receives the path to the message and deciphers the name of the leader of the
* operation. This also identifies the index of the current organization we are
* processing.
*
* @param caseFolder - (String) Path to the folder containing the flyer that has
* the hidden message.
* @return The name of the leader of the criminal organization.
* @throws FileNotFoundException If the file cannot be found.
* @throws IOException If there is an error reading the file.
*/
// Method to decipher a message from a file
public String decipherMessage(String caseFolder) throws IOException {
// Read the message file line by line into a list
List<String> messageDeciphered = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(caseFolder))) {
String line;
while ((line = reader.readLine()) != null) {
messageDeciphered.add(line);
}
}
// Determine the organization and leader key
this.organizationPosition = getDigiroot(messageDeciphered.get(0)) - 1;
Organization organization = criminalOrganizations.get(organizationPosition);
int leader = organization.getLeaderKey();
// Extract the leader name from the message
char[] leaderNameChars = new char[messageDeciphered.size() - 4];
for (int i = 2; i < messageDeciphered.size() - 2; i++) {
String[] message = messageDeciphered.get(i).split("\\W+");
if (message.length < leader) {
leaderNameChars[i - 2] = ' ';
} else {
leaderNameChars[i - 2] = message[leader - 1].charAt(0);
}
}
// Convert the leader name to a string and return it
return new String(leaderNameChars);
}
/**
* Calculates the digital root (digiroot) of the number received. The number is
* received as a String since it makes processing each individual number a bit
* easier.
*
* @param numbers - The string representation of the number whose digital root
* is to be found.
* @return - The digital root of the number.
*/
public int getDigiroot(String numbers) {
// Remove the "#" symbol from the input string
numbers = numbers.replaceAll("#", "");
int sum = 0;
for (int i = 0; i < numbers.length(); i++) {
sum += Character.getNumericValue(numbers.charAt(i));
}
while (sum >= 10) {
int newSum = 0;
while (sum > 0) {
newSum += sum % 10;
sum /= 10;
}
sum = newSum;
}
return sum;
}
/**
* Does the arrest operation by first finding the leader within its given
* organization. Then using that as a starting point arrest the most members
* possible.
*
* The idea is to arrest the leader and then arrest their underlings. Afterwards
* you identify which of the underlings has the most underlings under them and
* then move to arrest those. You will repeat this process until there are no
* more underlings to arrest.
*
* Notice that this process is pretty recursive...
*
* @param message - (String) Identity of the leader of the criminal operation.
*/
public void arrest(String message) {
// Get the criminal organization at the organizationPosition
Organization organization = criminalOrganizations.get(organizationPosition);
// Get all the members of the organization
List<Member> members = organization.organizationTraversal(m -> true);
// Loop through all the members of the organization
for (int i = 0; i < members.size(); i++) {
Member member = members.get(i);
// Check if the member's nickname matches the message
if (member.getNickname().equalsIgnoreCase(message)) {
// Assign the member as the leader
Member leader = member;
// Check if the leader has any underlings
if (leader.getUnderlings().size() == 0) {
// If the leader has no underlings, skip the rest of the loop iteration
continue;
} else {
// Loop through all the underlings of the leader
List<Member> underlings = leader.getUnderlings();
int maxUnderlings = 0;
Member maxMember = null;
for (int j = 0; j < underlings.size(); j++) {
Member underling = underlings.get(j);
// Arrest the underling
underling.setArrested(true);
this.arrest++;
// Find the underling with the most underlings
if (underling.getUnderlings().size() > maxUnderlings) {
maxUnderlings = underling.getUnderlings().size();
maxMember = underling;
}
}
// Arrest the underlings of the underling with the most underlings
if (maxMember != null) {
List<Member> maxUnderlingsList = maxMember.getUnderlings();
for (int k = 0; k < maxUnderlingsList.size(); k++) {
Member memberToArrest = maxUnderlingsList.get(k);
memberToArrest.setArrested(true);
this.arrest++;
}
}
// Arrest the leader
leader.setArrested(true);
this.arrest++;
}
// Exit the loop after the leader is arrested
break;
}
}
}
/**
* Generates the police report detailing how many arrests were achieved and how
* the organizations ended up afterwards.
*
* @param filePath - (String) Path of the file where the report will be saved.
* @throws IOException - If an I/O error occurs while writing to the file.
*/
// Method to generate a police report for a case
public void policeReport(String filepath) throws IOException {
// Create a new File object using the given filepath
File file = new File(filepath);
// Create a new BufferedWriter object to write to the file
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
// Write the initial heading of the police report
writer.write("CASE REPORT\n\n");
// Write the name of the police captain in charge of the operation
writer.write("In charge of Operation: " + this.captain + "\n\n");
// Write the total number of arrests made during the operation
writer.write("Total arrests made: " + this.arrest + "\n\n");
// Write the current status of all criminal organizations involved in the
// operation
writer.write("Current Status of Criminal Organizations:\n\n");
// Loop through each criminal organization and write its status to the report
for (Organization organization : getCriminalOrganizations()) {
// If the boss of the organization has been arrested, write "DISOLVED" to the
// report
if (organization.getBoss().isArrested() == true) {
writer.write("DISOLVED\n");
}
// Otherwise, write the details of the organization to the report
writer.write(organization + "\n");
writer.write("---\n");
}
// Write the end of the report and close the BufferedWriter
writer.write("END OF REPORT");
writer.close();
}
} | JaredJomar/Cracking-the-Crime-Code | src/police/PoliceDepartment.java | 2,626 | // If the leader has no underlings, skip the rest of the loop iteration | line_comment | en | false | 2,357 | 16 | 2,626 | 16 | 2,550 | 16 | 2,626 | 16 | 3,062 | 16 | false | false | false | false | false | true |
152394_2 |
package automativecarsystem;
import automativecarsystem.UpdateManagerr.Handler;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
public class updateCustomer extends JFrame implements ActionListener {
JFrame frame;
JTable table;
Object[] columns = {"Name", "ID", "Email Address", "Phone number", "Mailing address", "Type of car"};
DefaultTableModel model;
Font font;
JTextField textName;
JTextField Id;
JTextField EmailAdd;
JTextField Phonenum;
JTextField Mailingadd;
JTextField typeCar;
JLabel labelName;
JLabel labelId;
JLabel labelEmailadd;
JLabel labelPhonenum;
JLabel labelMailingadd;
JLabel typeCarl;
JButton buttonDelete = new JButton("Delete");
JButton buttonUpdate = new JButton("Edit");
JScrollPane pane;
Object[] rowData;
Customer cEdit;
Customer cDelete;
public updateCustomer(){
setSize(900,950);
cEdit = null;
cDelete = null;
table = new JTable(); //create new table
model = new DefaultTableModel(); //create new model
model.setColumnIdentifiers(columns);
table.setModel(model);
table.setBackground(Color.LIGHT_GRAY);
table.setForeground(Color.black);
font = new Font("",1,10);
table.setFont(font);
table.setRowHeight(30);
Handler myMouseListener = new Handler();
table.addMouseListener(myMouseListener);
labelName = new JLabel("User Name: ");
labelId= new JLabel("ID: ");
labelEmailadd = new JLabel("Email Address: ");
labelPhonenum = new JLabel("Phone number : ");
labelMailingadd = new JLabel("Mailing Address: ");
typeCarl = new JLabel("Car Type: ");
textName = new JTextField();
Id = new JTextField();
EmailAdd = new JTextField();
Phonenum = new JTextField();
Mailingadd = new JTextField();
typeCar = new JTextField();
add(buttonDelete);
add(buttonUpdate);
labelName.setBounds(20, 220, 100, 25);
labelId.setBounds(20, 250, 100, 25);
labelEmailadd.setBounds(20, 280, 100, 25);
labelPhonenum.setBounds(20, 310, 100, 25);
labelMailingadd.setBounds(20, 340, 100, 25);
typeCarl.setBounds(20,370,100,25);
textName.setBounds(130, 220, 100, 25);
Id.setBounds(130, 250, 100, 25);
EmailAdd.setBounds(130, 280, 100, 25);
Phonenum.setBounds(130, 310, 100, 25);
Mailingadd.setBounds(130, 340, 100, 25);
typeCar.setBounds(130,370,100,25);
buttonDelete.setBounds(250, 220, 100, 25);
buttonDelete.setVisible(true);
buttonUpdate.setBounds(250, 265, 100, 25);
buttonUpdate.setVisible(true);
buttonDelete.setBounds(250, 310, 100, 25);
buttonDelete.setVisible(true);
pane = new JScrollPane(table);
pane.setVisible(true);
pane.setBounds(0, 0, 880, 200);
add(pane);
add(labelName);
add(labelId);
add(labelEmailadd);
add(labelPhonenum);
add(labelMailingadd);
add(typeCarl);
add(textName);
add(Id);
add(EmailAdd);
add(Phonenum);
add(Mailingadd);
add(typeCar);
rowData = new Object[6]; // set the rows according to the number of customers
for(int i = 0; i < AutomativeCarSystem.allCustomer.size(); i++){
rowData[0] = AutomativeCarSystem.allCustomer.get(i).getFullnameC();
rowData[1] = AutomativeCarSystem.allCustomer.get(i).getIdentitycardC();
rowData[2] = AutomativeCarSystem.allCustomer.get(i).getEmailAdd();
rowData[3] = AutomativeCarSystem.allCustomer.get(i).getPhoneNum();
rowData[4] = AutomativeCarSystem.allCustomer.get(i).getMailingAdd();
rowData[5] = AutomativeCarSystem.allCustomer.get(i).getTypeOfCar();
model.addRow(rowData);
}
buttonDelete.addActionListener(this);
buttonUpdate.addActionListener(this);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
@Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == buttonUpdate){
// i = the index of the selected row
int i = table.getSelectedRow();
cEdit = AutomativeCarSystem.allCustomer.get(i);
if(i>=0){
model.setValueAt(textName.getText(), i, 0);
model.setValueAt(Id.getText(), i, 1);
model.setValueAt(EmailAdd.getText(), i, 2);
model.setValueAt(Phonenum.getText(), i, 3);
model.setValueAt(Mailingadd.getText(), i, 4);
model.setValueAt(typeCar.getText(),i,5);
cEdit.setFullnameC(textName.getText());
cEdit.setIdentitycardC(Id.getText());
cEdit.setEmailAdd(EmailAdd.getText());
cEdit.setPhoneNum(Phonenum.getText());
cEdit.setMailingAdd(Mailingadd.getText());
cEdit.setTypeOfCar(typeCar.getText());
//System.out.println(cEdit.getEmailAddress());
printWriting.custWriteDetails();
//addData("manager");
JOptionPane.showMessageDialog(null,"Update Successfull!");
}
else{
JOptionPane.showMessageDialog(null,"Update not successfull");
}
}if(ae.getSource()==buttonDelete){
int i = table.getSelectedRow();
if(i>=0){
model.removeRow(i);
AutomativeCarSystem.allCustomer.remove(i);
printWriting.custWriteDetails();
JOptionPane.showMessageDialog(null,"Customer removed successfully");
}else{
JOptionPane.showMessageDialog(null,"Customer did not get removed");
}
}
}
class Handler extends MouseAdapter{
@Override
public void mousePressed(MouseEvent mvt){
int i = table.getSelectedRow();
for(int j=0;j<AutomativeCarSystem.allCustomer.size();j++){ //checks the whole size of login
if(AutomativeCarSystem.allCustomer.get(i).getFullnameC().equals(textName.getText())){
cEdit = AutomativeCarSystem.allCustomer.get(j); //assign login as the specific customer object
break;
}
}
textName.setText(model.getValueAt(i, 0).toString());
Id.setText(model.getValueAt(i, 1).toString());
EmailAdd.setText(model.getValueAt(i, 2).toString());
Phonenum.setText(model.getValueAt(i, 3).toString());
Mailingadd.setText(model.getValueAt(i, 4).toString());
typeCar.setText(model.getValueAt(i, 5).toString());
}
}
}
| Maria-98-ui/Java-Automated-Car-Service-System | updateCustomer.java | 1,979 | // set the rows according to the number of customers
| line_comment | en | false | 1,717 | 11 | 1,979 | 11 | 2,183 | 11 | 1,979 | 11 | 2,430 | 11 | false | false | false | false | false | true |
154390_1 | // 456. 132 Pattern
// Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j].
//
// Return true if there is a 132 pattern in nums, otherwise, return false.
//
//
//
// Example 1:
//
// Input: nums = [1,2,3,4]
// Output: false
// Explanation: There is no 132 pattern in the sequence.
// Example 2:
//
// Input: nums = [3,1,4,2]
// Output: true
// Explanation: There is a 132 pattern in the sequence: [1, 4, 2].
// Example 3:
//
// Input: nums = [-1,3,2,0]
// Output: true
// Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].
//
//
// Constraints:
//
// n == nums.length
// 1 <= n <= 2 * 105
// -109 <= nums[i] <= 109
//
// Runtime 37 ms Beats 58.53%
// Memory 61.5 MB Beats 71.2%
class Solution {
public boolean find132pattern(int[] nums) {
if (nums.length < 3) return false;
Stack<Integer> stack = new Stack<>();
int second = Integer.MIN_VALUE;
for (int i = nums.length - 1; i >= 0; i--) {
if (nums[i] < second) {
return true;
}
while (!stack.isEmpty() && nums[i] > stack.peek()) {
second = stack.pop();
}
stack.push(nums[i]);
}
return false;
}
} | ishuen/leetcode | 456.java | 487 | // Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j]. | line_comment | en | false | 434 | 51 | 487 | 57 | 496 | 56 | 487 | 57 | 528 | 64 | false | false | false | false | false | true |
154799_1 | /* [Plant.java]
* The class for the plants in java, extending from the organism superclass
* @author Albert Quon
* 05/06/2018
*/
public class Plant extends Organism {
/**
* This method is the default constructor for the plant
*/
Plant(){
super();
}
} | AlbertQuon/EcoSimulator | Plant.java | 83 | /**
* This method is the default constructor for the plant
*/ | block_comment | en | false | 75 | 15 | 83 | 14 | 95 | 17 | 83 | 14 | 100 | 18 | false | false | false | false | false | true |
156976_0 | /**
* @(#)realRun.java
*
*
* @author
* @version 1.00 2018/5/15
*/
import java.awt.*;
import java.util.ArrayList;
import java.awt.event.*;
import javax.swing.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
public class main extends JFrame implements ActionListener, KeyListener {
Timer myTimer;
GamePanel game;
int screenX = 1900;
int screenY = 1000;
public main() {
super("Super Mario Bros");
setSize(screenX, screenY);
myTimer = new Timer (10, this);
myTimer.start();
game = new GamePanel();
add(game);
addKeyListener(this);
setResizable(false);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
if(game != null){
game.refresh();
game.repaint();
}
}
public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent e) {
game.setKey(e.getKeyCode(), true);
}
public void keyReleased(KeyEvent e) {
game.setKey(e.getKeyCode(), false);
}
public static void main(String[]args){
new main();
}
}
| CameronBeneteau/super-mario-bros | main.java | 385 | /**
* @(#)realRun.java
*
*
* @author
* @version 1.00 2018/5/15
*/ | block_comment | en | false | 295 | 35 | 385 | 39 | 414 | 43 | 385 | 39 | 464 | 46 | false | false | false | false | false | true |
159931_7 |
package GemIdentView;
import java.awt.BorderLayout;
import java.awt.Component;
import javax.swing.Box;
import javax.swing.JPanel;
/**
* 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/GemVident | GemIdentView/KPanel.java | 587 | /** sets the image panel's magnifier in the Eastern region (to be overridden) */ | block_comment | en | false | 500 | 18 | 587 | 19 | 583 | 19 | 587 | 19 | 656 | 20 | false | false | false | false | false | true |
160970_19 | import java.util.Arrays;
import java.util.Optional;
/**
* One of two possible cases for an overly encapsulated Binary Tree
* Not meant to be extended/inherited from
* Uses the Strategy pattern for deciding which algorithm to use to add ints:
* - MaxHeap
* - MinHeap
* - BST
* etc.
* Uses the Visitor Pattern to generalize traversal of each element and data
* (E.g. `map` or a very general for-loop)
*/
public class NodeBT implements IBinTree {
/** The int in this data node */
private int data;
/** The left subtree */
private IBinTree left;
/** The right subtree */
private IBinTree right;
/** The algorithm for adding integers into this tree */
private IBinTreeStrategy strategy;
/**
* A typical constructor with the default strategy of adding subsequent ints
* randomly to either the left or right subtree
*
* @param data the root data
* @param left the left subtree
* @param right the right subtree
*/
public NodeBT(int data, IBinTree left, IBinTree right) {
this.data = data;
this.left = left;
this.right = right;
this.strategy = new DefaultBTStrategy();
}
/**
* A constructor parameterized by the strategy of which algorithm to use to add
* subsequent ints to this tree
*
* @param data
* @param left
* @param right
* @param strategy
*/
public NodeBT(int data, IBinTree left, IBinTree right, IBinTreeStrategy strategy) {
this.data = data;
this.left = left;
this.right = right;
this.strategy = strategy;
}
/**
* A Copy Constructor for duplicating the tree
* Since the data is immutable,
*
* @param tree
*/
public NodeBT(NodeBT tree) {
this.data = tree.data;
this.left = tree.left.copy();
this.right = tree.right.copy();
this.strategy = tree.strategy;
}
/**
* Add an integer to the contents of this tree using the algorithm in the stored
* strategy
*
* @param i the number to insert.
* @return a new tree combining the data of this node and it's subtrees with the
* input int i
*/
@Override
public NodeBT addInt(int i) {
return this.strategy.addInt(i, this.left, this.data, this.right);
}
/**
* Combining all the data in this tree with another tree
*
* @param other the other tree to "insert into" to make a new tree, but no
* mutation occurs
* @return a new tree with the data of this tree and the other tree
*/
@Override
public IBinTree addAll(IBinTree other) {
return other.addAll(this.left).addAll(this.right).addInt(this.data);
}
/**
* Compute a tree containing the data of this node's left and right subtrees
*
* @return a new tree with the data of this tree except for the root node
*/
@Override
public Optional<IBinTree> removeRoot() {
return Optional.of(this.left.addAll(this.right));
}
/**
* Used for debugging, produces the root int
*
* @return the int at the root of this node
*/
@Override
public Optional<Integer> getRoot() {
return Optional.of(this.data);
}
/**
* Traverses this node using the given object to handle the data of this node as
* well as the left and right subtrees
* Uses depth first search for traversing the subtrees
*
* @param v an object that can handle either the values in a current NodeBT or
* an EmptyBT
* @return true if whoever called this.accept() should keep traversing according
* to the visitor object
*/
@Override
public boolean accept(IVisitor v) {
boolean keepGoing = v.visit(this.data, this.left, this.right); // visit this node and see if the visitor wants
// to keep going
if (keepGoing) {
keepGoing = this.left.accept(v); // recursively visit the left subtree and see if the visitor wants to keep
// going
}
if (keepGoing) {
keepGoing = this.right.accept(v); // recursivly visit the right subtree and see if the visitor wants to keep
// going
}
return keepGoing;
}
/**
* Mutation: changes the strategy of this node and all of the subtrees
*
* @param strategy a strategy which knows how to add elements to create NodeBTs
*/
@Override
public void apply(IBinTreeStrategy strategy) {
this.strategy = strategy;
this.left.apply(strategy);
this.right.apply(strategy);
}
/**
* Deep copy the full tree recursively
*
* @return A deep copy of the current Node and its subtrees with a shallow copy
* of the strategy
*/
@Override
public IBinTree copy() {
return new NodeBT(this.data, this.left.copy(), this.right.copy(), this.strategy);
}
/**
* A helper method for formating numbers to 3 digits (numbers greater than 3
* digits don't get pretty printed well)
*
* @return
*/
private String toThreeDigit() {
int num = Math.abs(this.data);
if (num < 10) {
return "00" + num;
} else if (num < 100) {
return "0" + num;
} else
return "" + num;
}
/**
* Code to pretty-print the binary tree
*
* @return the pretty-printed tree which is easier on the eyes than the
* debugging window
*/
@Override
public String toString() {
String[] leftLines = this.left.toString().split("\n");
String[] rightLines = this.right.toString().split("\n");
int maxLeft = 0;
int maxRight = 0;
for (String s : leftLines) {
maxLeft = Math.max(maxLeft, s.length());
}
for (String s : rightLines) {
maxRight = Math.max(maxRight, s.length());
}
int length = 4 + maxLeft + maxRight;
for (int i = 0; i < leftLines.length; i++) {
int pad = maxLeft - leftLines[i].length();
for (int j = 0; j < pad; j++) {
leftLines[i] += " ";
}
leftLines[i] += " ";
}
for (int i = 0; i < rightLines.length; i++) {
int pad = maxRight - rightLines[i].length();
for (int j = 0; j < pad; j++) {
rightLines[i] += " ";
}
}
String[] lines = new String[Math.max(leftLines.length, rightLines.length)];
for (int i = 0; i < Math.max(leftLines.length, rightLines.length); i++) {
if (i < leftLines.length) {
lines[i] = leftLines[i];
} else {
lines[i] = "";
for (int j = 0; j < 4 + maxLeft; j++) {
lines[i] += " ";
}
}
if (i < rightLines.length) {
lines[i] += rightLines[i];
} else {
for (int j = 0; j < maxRight; j++) {
lines[i] += " ";
}
}
}
String firstLine = "";
for (int i = 0; i < maxLeft; i++) {
firstLine += " ";
}
firstLine += " | ";
for (int i = 0; i < maxRight; i++) {
firstLine += " ";
}
firstLine += "\n";
for (int i = 0; i < maxLeft; i++) {
firstLine += "_";
}
firstLine += (this.data >= 0 ? "+" : "-") + this.toThreeDigit();
for (int i = 0; i < maxRight; i++) {
firstLine += "_";
}
return firstLine + "\n" + Arrays.stream(lines).reduce((s, a) -> s + "\n" + a).get();
}
/**
* Overriding equality to mean the same data and shape. Ignores strategy
* equality.
*
* @param o another tree, hopefully
* @return true if the two trees have the same data in the same "structure".
*/
@Override
public boolean equals(Object o) {
if (!(o instanceof NodeBT)) {
return false;
}
NodeBT no = (NodeBT) o;
return no.data == this.data && no.left.equals(this.left) && no.right.equals(this.right);
}
}
| prectriv/cs2102 | HW/HW4/src/NodeBT.java | 2,096 | /**
* Mutation: changes the strategy of this node and all of the subtrees
*
* @param strategy a strategy which knows how to add elements to create NodeBTs
*/ | block_comment | en | false | 2,008 | 42 | 2,096 | 39 | 2,325 | 44 | 2,096 | 39 | 2,440 | 46 | false | false | false | false | false | true |
161417_0 | import java.io.*;
import java.net.*;
import java.nio.*;
import java.util.*;
import java.util.concurrent.*;
/*
Class that will hold information about the local processes's Peers
*/
public class PeerRecord {
public int peerID;
public String host;
public int portNumber;
public boolean hasFile;
public DataInputStream inStream;
public DataOutputStream outStream;
public Socket socket;
public BitField bitField;
public int piecesSinceLastRound;
public boolean sentHandShake;
public boolean isInterested;
public boolean interestedIn;
public boolean isChoked;
public boolean isOptimisticallyUnchoked;
public PeerRecord(int peerID, String host, int portNumber, boolean hasFile, int pieceCount) {
this.peerID = peerID;
this.host = host;
this.portNumber = portNumber;
this.hasFile = hasFile;
this.sentHandShake = false;
this.bitField = new BitField(pieceCount);
this.isInterested = false;
this.piecesSinceLastRound = 0;
this.isChoked = true;
this.isOptimisticallyUnchoked = false;
this.interestedIn = false;
}
} | daltonv/CNT4007_Project | PeerRecord.java | 313 | /*
Class that will hold information about the local processes's Peers
*/ | block_comment | en | false | 249 | 15 | 313 | 16 | 315 | 16 | 313 | 16 | 347 | 17 | false | false | false | false | false | true |
161828_4 | // { Driver Code Starts
//Initial Template for Java
import java.util.*;
import java.io.*;
import java.lang.*;
class trainPlat
{
public static void main(String args[])throws IOException
{
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(read.readLine());
while(t-- > 0)
{
String str[] = read.readLine().trim().split(" ");
int n = Integer.parseInt(str[0]);
int arr[] = new int[n];
int dep[] = new int[n];
str = read.readLine().trim().split(" ");
for(int i = 0; i < n; i++)
arr[i] = Integer.parseInt(str[i]);
str = read.readLine().trim().split(" ");
for(int i = 0; i < n; i++)
dep[i] = Integer.parseInt(str[i]);
System.out.println(new Platform().findPlatform(arr, dep, n));
}
}
}
// } Driver Code Ends
//User function Template for Java
class Platform
{
static int findPlatform(int a[], int d[], int n)
{
Arrays.sort(a);
Arrays.sort(d);
int i=1,j=0;
int count=1,max=1;
while(i<n && j<n)
{
if(a[i]<=d[j]) //if arrival time is less than or equal to the departure time,
{
count++; //then we increment the count of required platforms, because the platform would be occupied by the already standing train
i++; //so a new platform would be required for the arriving train
}
else if(d[j]<a[i]) //if the arrival time is greater than the departure time
{
count--; //then we decrement the no. of platform required, becoz, when a train leaves the platform becomes empty, so it can be used
j++; //instead of a new platform
}
max=Math.max(count,max); //we store the maximum requirement of platform reached ,throughout the day
}
return max; //and return the maximum count
}
}
| KC1919/MyPrograms | trainPlat.java | 522 | //if arrival time is less than or equal to the departure time, | line_comment | en | false | 466 | 14 | 522 | 16 | 571 | 14 | 522 | 16 | 602 | 14 | false | false | false | false | false | true |
162233_1 | /***************************************************************
JBackgammon (http://jbackgammon.sf.net)
Copyright (C) 2002
George Vulov <[email protected]>
Cody Planteen <[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.
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., 675 Mass Ave, Cambridge, MA 02139, USA.
****************************************************************/
/* File: FixedButton.java
*
* Description: This file contains the custom button class for absolute
* positioning of JButtons. */
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.*;
public class FixedButton extends JButton
{
Container content;
Game parent;
public static final long serialVersionUID = 1L; // version 1
public FixedButton(Container c, Game p)
{
content = c;
parent = p;
content.setLayout(null);
content.add(this);
} // FixedButton constructor
/**
* ?? probably for drawing blots onto points, with hard-coded pixel insets
*/
public void drawOnPoint(int point)
{
Insets in = parent.getInsets();
if (point > 12) {
setBounds(parent.findX(point) - in.left, parent.findY(point) - in.top, 28, 10);
} else {
setBounds(parent.findX(point) - in.left, parent.findY(point) - 10 - in.top, 28, 10);
}
setVisible(true);
parent.repaint();
} // drawOnPoint
} // class FixedButton
| backgammon-java-ai/backg_java2012 | FixedButton.java | 553 | /* File: FixedButton.java
*
* Description: This file contains the custom button class for absolute
* positioning of JButtons. */ | block_comment | en | false | 471 | 28 | 553 | 31 | 563 | 30 | 553 | 31 | 642 | 33 | false | false | false | false | false | true |
164057_3 | /**
* This program demonstrates the basic usage of the Comparable
* Note that we implement the Comparable interface.
* This allows us to the use the methods of lists, such as LinkedList,
* Usually called ".sort" to sort our list based off of our compareTo criteria.
* If we just made a compareTo method, we'd still be able to compare our objects by that
* criteria, however we would have to make a method to sort the list...not so toasty sounding, huh?
* @author Maker-Mark
*
*/
public class Apple implements Comparable<Apple> {
private int weight;
private String variety;
private Color c; //Nested object, very well could have just been a string
public Apple(String color, String variety, int weight)
{
this.variety = variety;
this.weight = weight;
c = new Color(color); //makes new nested color object
}
/**
* The compareTo method for an Apple
* compares the apple's weight and returns a flag
* to indicate if the weight is greater than, less than or
* equal.
*/
@Override
public int compareTo(Apple other)
{
if (this.weight < other.weight) {
return -1;
}
if (this.weight == other.weight) {
return 0;
}
//flag for this.Apple greater than apple being compared
return 1;
}
public String toString() {
return "I am an apple with a color: " +
c.getObjColor() + " I am of variety: " + variety +
" I weigh: " + weight + " ounces." ;
}
//Rest of file: simple setters(mutators) and getters(assessors)
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public String getVariety() {
return variety;
}
public void setVariety(String variety) {
this.variety = variety;
}
public Color getC() {
return c;
}
public void setC(Color c) {
this.c = c;
}
} | Maker-Mark/Comparable-Demo-UsingLinkedLists | Apple.java | 547 | /**
* The compareTo method for an Apple
* compares the apple's weight and returns a flag
* to indicate if the weight is greater than, less than or
* equal.
*/ | block_comment | en | false | 468 | 46 | 547 | 45 | 544 | 51 | 547 | 45 | 610 | 52 | false | false | false | false | false | true |
168053_0 | /**
* This class contains constants used throughout the program.
*
* @author Kedar Abhyankar
* @version June 26th, 2019
*/
class CollegeConstants {
static final double PURDUE_UNIVERSITY_IN_STATE_TUITION = 22882;
static final double PURDUE_UNIVERSITY_OUT_OF_STATE_TUITION = 41844;
static final String PURDUE_UNIVERSITY_NAME = "Purdue University";
static final double INDIANA_UNIVERSITY_IN_STATE_TUITION = 24778;
static final double INDIANA_UNIVERSITY_OUT_OF_STATE_TUITION = 49554;
static final String INDIANA_UNIVERSITY_NAME = "Indiana University";
static final double UNIVERSITY_OF_MICHIGAN_IN_STATE_TUITION = 15262;
static final double UNIVERSITY_OF_MICHIGAN_OUT_OF_STATE_TUITION = 49350;
static final String UNIVERSITY_OF_MICHIGAN_NAME = "University of Michigan";
static final double OHIO_STATE_UNIVERSITY_IN_STATE_TUITION = 10726;
static final double OHIO_STATE_UNIVERSITY_OUT_OF_STATE_TUITION = 30742;
static final String OHIO_STATE_UNIVERSITY_NAME = "The Ohio State University";
static final double PENN_STATE_UNIVERSITY_IN_STATE_TUITION = 18454;
static final double PENN_STATE_UNIVERSITY_OUT_OF_STATE_TUITION = 34858;
static final String PENN_STATE_UNIVERSITY_NAME = "Pennsylvania State University";
static final String ON_CAMPUS = "On Campus";
static final String OFF_CAMPUS = "Off Campus";
}
| arhamhundia007/cs180 | projects/Project5/src/CollegeConstants.java | 489 | /**
* This class contains constants used throughout the program.
*
* @author Kedar Abhyankar
* @version June 26th, 2019
*/ | block_comment | en | false | 391 | 38 | 489 | 42 | 422 | 40 | 489 | 42 | 547 | 42 | false | false | false | false | false | true |
171673_14 |
//import java.awt.*;
//import java.awt.font.*;
//import java.awt.geom.*;
import java.awt.image.BufferedImage;
//import java.text.*;
//import java.util.*;
//import java.util.List; // resolves problem with java.awt.List and java.util.List
/**
* A class that represents a picture. This class inherits from SimplePicture and
* allows the student to add functionality to the Picture class.
*
* Copyright Georgia Institute of Technology 2004-2005
*
* @author Barbara Ericson [email protected]
*/
public class Picture extends SimplePicture {
///////////////////// constructors //////////////////////////////////
/**
* Constructor that takes no arguments
*/
public Picture() {
/*
* not needed but use it to show students the implicit call to super()
* child constructors always call a parent constructor
*/
super();
}
/**
* Constructor that takes a file name and creates the picture
*
* @param fileName
* the name of the file to create the picture from
*/
public Picture(String fileName) {
// let the parent class handle this fileName
super(fileName);
}
/**
* Constructor that takes the width and height
*
* @param width
* the width of the desired picture
* @param height
* the height of the desired picture
*/
public Picture(int width, int height) {
// let the parent class handle this width and height
super(width, height);
}
/**
* Constructor that takes a picture and creates a copy of that picture
*/
public Picture(Picture copyPicture) {
// let the parent class do the copy
super(copyPicture);
}
/**
* Constructor that takes a buffered image
*
* @param image
* the buffered image to use
*/
public Picture(BufferedImage image) {
super(image);
}
////////////////////// methods ///////////////////////////////////////
/**
* Method to return a string with information about this picture.
*
* @return a string with information about the picture such as fileName,
* height and width.
*/
public String toString() {
String output = "Picture, filename " + getFileName() + " height " + getHeight() + " width " + getWidth();
return output;
}
public static void main(String[] args) {
// String fileName = FileChooser.pickAFile();
// Picture pictObj = new Picture(fileName);
// pictObj.explore();
}
} // this } is the end of class Picture, put all new methods before this
| BluuArc/BFFrameAnimator | src/Picture.java | 630 | /**
* Constructor that takes a picture and creates a copy of that picture
*/ | block_comment | en | false | 564 | 18 | 630 | 17 | 696 | 20 | 630 | 17 | 754 | 22 | false | false | false | false | false | true |
172016_1 | package hw7;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CampusPaths
{
/**
* Overview:
* view the list of names of all buildings.
*
* @param g a CampusMapGraph object
*/
public static void listBuilding(CampusMapGraph g)
{
System.out.print(g.listAllBuildings());
}
/**
* Overview:
* main function
* the control component and handles the user input
*/
public static void main(String[] argv)
{
CampusMapGraph g = new CampusMapGraph();
try
{
g.createNewGraph("hw7/data/RPI_map_data_Nodes.csv", "hw7/data/RPI_map_data_Edges.csv");
}
catch (IOException i)
{
return;
}
String menu = "Menu:\n"
+ "b: lists all buildings\n"
+ "r: prints directions for the shortest route between two buildings or their IDs\n"
+ "q: quits the program\n"
+ "m: prints a menu of all commands\n";
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String input = "";
while(!input.equals("q"))
{
try
{
input = reader.readLine();
}
catch (IOException e)
{
break;
}
if(input.equals("b"))
listBuilding(g);
else if(input.equals("r"))
{
String start;
String end;
System.out.print("First building id/name, followed by Enter: ");
try
{
start = reader.readLine();
}
catch (IOException badinput)
{
break;
}
System.out.print("Second building id/name, followed by Enter: ");
try
{
end = reader.readLine();
}
catch (IOException badinput)
{
break;
}
System.out.print(g.findPath(start, end));
}
else if(input.equals("q"))
break;
else if(input.equals("m"))
System.out.print(menu);
else
System.out.print("Unknown option\n");
}
return;
}
}
| sringram96/Principles-of-Software | hw7/CampusPaths.java | 600 | /**
* Overview:
* main function
* the control component and handles the user input
*/ | block_comment | en | false | 487 | 23 | 600 | 21 | 599 | 25 | 600 | 21 | 771 | 26 | false | false | false | false | false | true |
173295_0 | /* Write a program that has class Publisher , Book , Literature and fiction. Read the information and print the
details of the book from either the category , using inheritance. */
import java.util.Scanner;
class Publisher {
String publisher;
Publisher(String publisher) {
this.publisher = publisher;
}
}
class Book extends Publisher{
String author;
int noOfPages,price;
Book(String publisher , String author , int noOfPages, int price){
super(publisher);
this.author = author;
this.noOfPages = noOfPages;
this.price = price;
}
}
class Literature extends Book {
String litName;
Literature(String publisher, String author, int noOfPages, int price, String litName) {
super(publisher, author, noOfPages, price);
this.litName = litName;
}
void display() {
System.out.printf(
"\nBook Name : %s\nGenere : Literature\nAuthor : %s\nPublisher : %s\nNumber of pages : %d\nPrice : %d\n\n",
this.litName, this.author, this.publisher, this.noOfPages, this.price);
}
}
class Fiction extends Book {
String fictName;
Fiction(String publisher, String author, int noOfPages, int price, String fictName) {
super(publisher, author, noOfPages, price);
this.fictName = fictName;
}
void display() {
System.out.printf(
"\nBook Name : %s\nGenere : Fiction\nAuthor : %s\nPublisher : %s\nNumber of pages : %d\nPrice : %d\n\n",
this.fictName, this.author, this.publisher, this.noOfPages, this.price);
}
}
class Program4 {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
int choice;
do{
System.out.print("enter a choice :\n0) exit\n1) Literature book\n2) Fiction book\n\n-> ");
choice = scanner.nextInt();
switch (choice) {
case 0 -> {
System.out.println("exiting...");
}
case 1 -> {
System.out.printf("Enter the book title , author name , publisher name , price and number of pages of literature : ");
String title = scanner.next();
String author = scanner.next();
String publisher = scanner.next();
int price = scanner.nextInt();
int pageNo = scanner.nextInt();
Literature lit = new Literature(publisher, author, pageNo, price, title);
System.out.print("Literature details\n-----------------\n");
lit.display();
}
case 2 -> {
System.out.printf("Enter the book title , author name , publisher name , price and number of pages of fiction : ");
String title = scanner.next();
String author = scanner.next();
String publisher = scanner.next();
int price = scanner.nextInt();
int pageNo = scanner.nextInt();
Fiction fict = new Fiction(publisher, author, pageNo, price, title);
System.out.print("Literature details\n-----------------\n");
fict.display();
}
default -> {
System.out.println("Wrong choice");
}
}
} while (choice != 0);
scanner.close();
}
}
| aswinr019/object-oriented-programming-lab | CO3/Program4.java | 826 | /* Write a program that has class Publisher , Book , Literature and fiction. Read the information and print the
details of the book from either the category , using inheritance. */ | block_comment | en | false | 697 | 35 | 826 | 38 | 848 | 35 | 826 | 38 | 948 | 37 | false | false | false | false | false | true |
174683_0 | /*
CreateWeblogs.java: CreateWeblogs application driver
Last Updated 10/29/13
Dave Jaffe, Dell Solution Centers
Distributed under Creative Commons with Attribution by Dave Jaffe ([email protected]).
Provided as-is without any warranties or conditions.
Creates Apache web logs using map-only program, CreateWeblogsMapper.java
* Uses real distribution of remote ips per country based on GeoLite data from MaxMind for top 20 web-using countries
* Assumes consumer oriented website located in Central time zone - more activity in evening local time
* Does simple sessionization (user clickstreams are sequential, don't overlap days)
Syntax:
hadoop jar CreateWeblogs.jar CreateWeblogs -files all_classbs.txt,referrers.txt,requests.txt,user_agents.txt \
<HDFS input directory> <HDFS output directory>
Input: file(s) containing lines with space-separated year, month, day, number of records per day
Output: weblogs with name access_log-yyyymmdd
Files all_classbs.txt, referrers.txt, requests.txt, user_agents.txt must exist in local directory
all_classbs.txt: a list of class B IP addresses and associated country, from the GeoLite dataset
Only those class B's that come from a single country are used. Full IP addresses are randomly generated from these
class B addresses following the country distribution of Internet use.
Example line: 23.242 US
requests.txt: a list of the request part of the web log. These are randomly added to the web log.
Example line: GET /ds2/dslogin.php?username=user15363&password=password HTTP/1.1
referrers.txt: a list of the referrers part of the web log. These are randomly added to the web log.
Example line: http://110.240.0.17/
user_agents.txt: a list of the user_agents part of the web log. These are randomly added to the web log.
Example line: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; .NET CLR 3.0.04506;)
This product includes GeoLite data created by MaxMind, available from http://www.maxmind.com
Example weblog line:
172.16.3.1 - - [27/Jun/2012:17:48:34 -0500] "GET /favicon.ico HTTP/1.1" 404 298 "-" "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"
Remote host/-/-/Date-timestamp/Request line/status/size/-/Referer/User agent
See http://httpd.apache.org/docs/current/logs.html
*/
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
public class CreateWeblogs extends Configured implements Tool
{
@Override
public int run(String[] args) throws Exception
{
if (args.length != 2)
{
System.out.print("Usage: CreateWeblogs <input dir> <output dir>\n");
return -1;
}
Job job = new Job(getConf());
job.setJarByClass(CreateWeblogs.class);
job.setJobName("CreateWeblogs");
job.setNumReduceTasks(0);
job.setOutputFormatClass(NullOutputFormat.class);
FileInputFormat.setInputPaths(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
job.setMapperClass(CreateWeblogsMapper.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
boolean success = job.waitForCompletion(true);
return success ? 0 : 1;
}
public static void main(String[] args) throws Exception
{
int exitCode = ToolRunner.run(new Configuration(), new CreateWeblogs(), args);
System.exit(exitCode);
}
} // End Class CreateWeblogs
| payne/BigDataDemos | CreateWeblogs.java | 1,115 | /*
CreateWeblogs.java: CreateWeblogs application driver
Last Updated 10/29/13
Dave Jaffe, Dell Solution Centers
Distributed under Creative Commons with Attribution by Dave Jaffe ([email protected]).
Provided as-is without any warranties or conditions.
Creates Apache web logs using map-only program, CreateWeblogsMapper.java
* Uses real distribution of remote ips per country based on GeoLite data from MaxMind for top 20 web-using countries
* Assumes consumer oriented website located in Central time zone - more activity in evening local time
* Does simple sessionization (user clickstreams are sequential, don't overlap days)
Syntax:
hadoop jar CreateWeblogs.jar CreateWeblogs -files all_classbs.txt,referrers.txt,requests.txt,user_agents.txt \
<HDFS input directory> <HDFS output directory>
Input: file(s) containing lines with space-separated year, month, day, number of records per day
Output: weblogs with name access_log-yyyymmdd
Files all_classbs.txt, referrers.txt, requests.txt, user_agents.txt must exist in local directory
all_classbs.txt: a list of class B IP addresses and associated country, from the GeoLite dataset
Only those class B's that come from a single country are used. Full IP addresses are randomly generated from these
class B addresses following the country distribution of Internet use.
Example line: 23.242 US
requests.txt: a list of the request part of the web log. These are randomly added to the web log.
Example line: GET /ds2/dslogin.php?username=user15363&password=password HTTP/1.1
referrers.txt: a list of the referrers part of the web log. These are randomly added to the web log.
Example line: http://110.240.0.17/
user_agents.txt: a list of the user_agents part of the web log. These are randomly added to the web log.
Example line: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; .NET CLR 3.0.04506;)
This product includes GeoLite data created by MaxMind, available from http://www.maxmind.com
Example weblog line:
172.16.3.1 - - [27/Jun/2012:17:48:34 -0500] "GET /favicon.ico HTTP/1.1" 404 298 "-" "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"
Remote host/-/-/Date-timestamp/Request line/status/size/-/Referer/User agent
See http://httpd.apache.org/docs/current/logs.html
*/ | block_comment | en | false | 955 | 624 | 1,115 | 696 | 1,122 | 684 | 1,115 | 696 | 1,216 | 749 | true | true | true | true | true | false |
174800_0 | package com.tree.family;
import java.util.List;
/*
* Model to keep information of Family for a person
*/
public class Household {
private Person husband;
private Person wife;
private List<Person> children;
public Household(Person member1, Person member2) {
super();
this.husband = (member1.getGender().equals(GENDER.MALE))?member1:member2;
this.wife = (member1.getGender().equals(GENDER.FEMALE))?member1:member2;;
}
public Person getHusband() {
return husband;
}
public Person getWife() {
return wife;
}
public List<Person> getChildren() {
return children;
}
public void setChildren(List<Person> children) {
this.children = children;
}
}
| richierich1610/family-relationship-tree | src/com/tree/family/Household.java | 229 | /*
* Model to keep information of Family for a person
*/ | block_comment | en | false | 166 | 13 | 229 | 14 | 216 | 14 | 229 | 14 | 241 | 14 | false | false | false | false | false | true |
177190_14 | /*
* @(#)MultiMap.java
*
* Copyright (c) 2002: The Trustees of Columbia University in the City of New York. All Rights Reserved
*
* Copyright (c) 2002: @author Dan Phung ([email protected])
*
* CVS version control block - do not edit manually
* $RCSfile$
* $Revision$
* $Date$
* $Source$
*/
package psl.worklets;
import java.util.*;
/**
* Implementation of a map that allows multiple entries for the same
* key by associating a vector to a key to contain the multiple value
* entries
*/
public class MultiMap {
/** The underlying container is a TreeMap */
private Map _mmap = Collections.synchronizedMap(new TreeMap());
/** Creates a MultiMap */
public MultiMap(){}
/**
* Adds a key/value pair
*
* @param key: identifier for the value
* @param value: object corresponding to the key
*/
public void put(Object key, Object value){
if (_mmap.containsKey(key)){
Vector v = (Vector)_mmap.get(key);
v.addElement(value);
} else {
Vector v = new Vector();
v.addElement(value);
_mmap.put(key, v);
}
}
/**
* Removes the key (with all the values) from the map
*
* @param key: identifier for the values to remove
* @return values associated with the key or null
*/
public Object remove(Object key){
if (_mmap.containsKey(key))
return _mmap.remove(key);
return null;
}
/**
* Removes a specific value from the map. If the value is the last
* object in the vector, the key is also removed
*
* @param key: key associated with the value
* @param value: specific value to remove
* @return object associated with the key/value pair or null
*/
public Object remove(Object key, Object value){
Object o = null;
if (_mmap.containsKey(key)){
Vector v = (Vector)_mmap.get(key);
int i = v.indexOf(value);
if (i > 0) {
o = v.remove(i);
if (v.size() == 1)
_mmap.remove(key);
}
}
return o;
}
/**
* Checks to see if this key is present
*
* @param key: identifier to check for
* @return presence of the key
*/
public boolean contains(Object key){
if (_mmap.containsKey(key))
return true;
else
return false;
}
/**
* Checks to see if this key/value pair is present
*
* @param key: identifier to check for
* @param value: value to check for
* @return presence of the key/value pair
*/
public boolean contains(Object key, Object value){
if (_mmap.containsKey(key)){
Vector v = (Vector)_mmap.get(key);
if (v.indexOf(value) > 0)
return true;
}
return false;
}
/**
* Gets the values assoiated with the key
*
* @param key: identifier of object to retrieve
* @return values associated with the key
*/
public Object get(Object key){
if (_mmap.containsKey(key))
return _mmap.get(key);
else
return null;
}
/**
* Get the available keys
*
* @return <code>Set</code> of available keys
*/
public Set keySet(){
return _mmap.keySet();
}
/**
* Get the number of keys in the map
*
* @return number of keys in the map
*/
public int size(){
return _mmap.size();
}
/**
* Get the number of values in the map
*
* @return number of values in the map
*/
public int sizeValues(){
int valueSize = 0;
Set s = _mmap.keySet();
Iterator setItr = s.iterator();
while (setItr.hasNext()) {
Vector v = (Vector)_mmap.get(setItr.next());
valueSize += v.size();
}
return valueSize;
}
/** Prints the key,value vector */
// Note: this is a cleaner look at the values, as compared to using
// entrySet() or values()
public void printAll(){
Set s = _mmap.keySet();
Iterator setItr = s.iterator();
if (s.size() > 0){
while (setItr.hasNext()) {
Object key = setItr.next();
WVM.out.print(" " + key + " <");
Vector v = (Vector)_mmap.get(key);
Iterator vecItr = v.iterator();
while (vecItr.hasNext()) {
Object value = vecItr.next();
WVM.out.print(value + ",");
}
WVM.out.println(">");
}
}
}
/** Removes all key,vector(value) entries */
public void clear(){
_mmap.clear();
}
}
| Programming-Systems-Lab/archived-worklets | MultiMap.java | 1,193 | // Note: this is a cleaner look at the values, as compared to using | line_comment | en | false | 1,125 | 16 | 1,193 | 16 | 1,318 | 16 | 1,193 | 16 | 1,440 | 16 | false | false | false | false | false | true |
177715_0 | import java.beans.PropertyChangeSupport;
import java.beans.PropertyChangeListener;
/** Hosts methods involving everything to do with player's currency, manages all classes that are related to currency.
*
* @author Julia
* @version January 2024
*/
public class EconomyManager
{
private static PropertyChangeSupport support;
public EconomyManager()
{
support = new PropertyChangeSupport(this);
}
/**
* Add pcl as a listener to EconomyManager's property changes
*
* @param pcl PropertyChangeListener to be added as a listener. Will be notified upon property changes
*/
public static void addListener(PropertyChangeListener pcl) {
support.addPropertyChangeListener(pcl);
}
/**
* Remove pcl from being a listener.
*
* @param pcl PropertyChangeListener to be removed from list of listeners
*/
public static void removeListener(PropertyChangeListener pcl) {
support.removePropertyChangeListener(pcl);
}
/**
* Checks whether or not player has enough currency to purchase seed
*
* @param price price of seed
* @return whether or not player has enough currency to purchase seed
*/
public static boolean hasEnoughMoney(int price) {
return PlayerDataManager.getPlayerData().currency >= price;
}
/**
* Increases currency by a certain value
*
* @param value value of currency to increased by
*/
public static void addMoney(int value) {
int oldValue = PlayerDataManager.getPlayerData().currency;
PlayerDataManager.getPlayerData().currency += value;
support.firePropertyChange("coins", oldValue, PlayerDataManager.getPlayerData().currency);
}
/**
* Set player's currency to a certain value
*
* @param value value of currency to be set to
*/
public static void setMoney(int value) {
int oldValue = PlayerDataManager.getPlayerData().currency;
PlayerDataManager.getPlayerData().currency = value;
support.firePropertyChange("coins", oldValue, value);
}
/**
* @return player's currency value
*/
public static int getMoney() {
return PlayerDataManager.getPlayerData().currency;
}
}
| yrdsb-peths/final-greenfoot-project-Jujunipers | EconomyManager.java | 486 | /** Hosts methods involving everything to do with player's currency, manages all classes that are related to currency.
*
* @author Julia
* @version January 2024
*/ | block_comment | en | false | 469 | 40 | 486 | 42 | 558 | 42 | 486 | 42 | 605 | 44 | false | false | false | false | false | true |
177873_5 | /**
* The base class for all number games.
* Your guessing game should extend this class and
* override the methods: guess(), toString(), getUpperBound().
*
* Your class should not override getMessage() and setMessage(),
* just use the methods from this class.
*/
public class NumberGame{
/** A helpful message for user. */
private String message;
/** Initialize a new default game. */
public NumberGame() {
// initialize your game.
message = "";
}
/**
* Evaluate a user's answer to the game.
* @param answer is the user's answer, as an integer.
* @return true if correct, false otherwise
*/
public boolean guess(int answer) {
message = "Sorry, that's not correct";
return false;
}
/**
* Return a message about the most recent call to guess().
* Initially the message should tell the user something so
* the user knows what to guess, such as
* "I'm thinking of a number between 1 and xx".
* @return string message related to the most recent guess.
*/
public String getMessage() {
return message;
}
/**
* Set a message about the game.
* @param newmessage a string about game or most recent guess.
*/
public void setMessage(String newmessage) {
this.message = newmessage;
}
/**
* Get the largest possible value of the solution for this game.
* For a guessing game, this should be the upper bound of secret.
*/
public int getUpperBound() {
return Integer.MAX_VALUE; // not very helpful :-)
}
/**
* toString describes the game or problem.
* @return description of this game or the problem to be solved.
*/
@Override
public String toString() {
return "Guessing game!";
}
/**
* Get count number
* @return Count number how many guessing game
*/
public int getCount(){
return 0;
}
} | OOP2018/guessing-game-SupalukBenz | src/NumberGame.java | 469 | /**
* Return a message about the most recent call to guess().
* Initially the message should tell the user something so
* the user knows what to guess, such as
* "I'm thinking of a number between 1 and xx".
* @return string message related to the most recent guess.
*/ | block_comment | en | false | 438 | 70 | 469 | 67 | 534 | 76 | 469 | 67 | 564 | 79 | false | false | false | false | false | true |
178127_4 | import java.util.LinkedList;
public class Tank {
// Water tank status
double waterLevel = 0.00;
// Maximum capacity of the water tank
double capacity = 100.00;
// Critical level of the water tank
double criticalLevel = 0.1 * capacity; // 10% of capacity
// Flag to indicate if water level is at or below critical level
boolean isCritical = true;
// Create a list shared by producer and consumer
// The list doesn't directly represent the water tank's volume but is used for
// synchronization.
LinkedList<Integer> list = new LinkedList<>();
int listCapacity = 10; // Arbitrary capacity for the list to demonstrate synchronization;
public Tank(double waterLevel) {
this.waterLevel = waterLevel;
if (waterLevel > criticalLevel) {
isCritical = false;
} else {
isCritical = true;
}
}
public double getWaterLevel() {
return waterLevel;
}
public void setWaterLevel(double waterLevel) {
this.waterLevel = waterLevel;
}
public double getCapacity() {
return capacity;
}
public void setCapacity(double capacity) {
this.capacity = capacity;
}
public double getCriticalLevel() {
return criticalLevel;
}
public boolean getIsCritical() {
return isCritical;
}
public void setIsCritical(double waterLevel) {
if (waterLevel > criticalLevel) {
isCritical = false;
} else {
isCritical = true;
}
}
}
| Natssh7/OSassignment2 | Tank.java | 352 | // Flag to indicate if water level is at or below critical level | line_comment | en | false | 342 | 13 | 352 | 13 | 395 | 13 | 352 | 13 | 442 | 13 | false | false | false | false | false | true |
180616_47 | package program;
import static org.testng.Assert.fail;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Keys;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Day6BigBasket {
public static ChromeDriver driver;
public static void main(String[] args) throws InterruptedException {
//Launch BigBasket site
System.setProperty("webdriver.chrome.driver", "./Drivers/chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://www.bigbasket.com/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
String title = driver.getTitle();
if (title.contains("bigbasket")) {
System.out.println("BigBasket launched successfully: " + title);
} else
fail("BigBasket launch failed");
Day6BigBasket bb=new Day6BigBasket();
WebDriverWait wait = new WebDriverWait(driver, 10);
Actions builder = new Actions(driver);
//Set location pincode
driver.findElementByXPath("//span[@class='arrow-marker']").click();
driver.findElementById("areaselect").sendKeys("600026");
Thread.sleep(500);
driver.findElementById("areaselect").sendKeys(Keys.ENTER);
driver.findElementByXPath("//button[text()='Continue']").click();
//Mouse hover on Shop by Category
builder.moveToElement(driver.findElementByXPath("//a[text()=' Shop by Category ']")).perform();
//Go to FOODGRAINS, OIL & MASALA --> RICE & RICE PRODUCTS
builder.moveToElement(driver.findElementByXPath("(//a[text()='Foodgrains, Oil & Masala'])[2]")).build().perform();
wait.until(ExpectedConditions.visibilityOf(driver.findElementByXPath("(//a[text()='Rice & Rice Products'])[2]")));
builder.moveToElement(driver.findElementByXPath("(//a[text()='Rice & Rice Products'])[2]")).build().perform();
//Click on Boiled & Steam Rice
wait.until(ExpectedConditions.elementToBeClickable(driver.findElementByXPath("(//a[text()='Boiled & Steam Rice'])[2]")));
builder.moveToElement(driver.findElementByXPath("(//a[text()='Boiled & Steam Rice'])[2]")).click().build().perform();
if((driver.getTitle()).contains("Boiled Steam Rice"))
{
System.out.println("Navigated to Boiled & Steam Rice products page");
}
else fail("Navigation to Boiled & Steam Rice page failed");
//Choose the Brand as bb Royal
wait.until(ExpectedConditions.elementToBeClickable(driver.findElementByXPath("//span[text()='bb Royal']")));
driver.findElementByXPath("//span[text()='bb Royal']").click();
Thread.sleep(1000);
wait.until(ExpectedConditions.visibilityOf(driver.findElementByXPath("//div[contains(@class,'prod-name')]/h6")));
int count = 0;
List<WebElement> eleBrandNames = driver.findElementsByXPath("//div[contains(@class,'prod-name')]/h6");
Thread.sleep(2000);
for (WebElement eachBrand : eleBrandNames) {
if((eachBrand.getText()).equalsIgnoreCase("bb Royal"))
{
count++;
}}
if(count==eleBrandNames.size())
{
System.out.println("bb Royal brand products are displayed");
}
//Go to Ponni Boiled Rice - Super Premium and select 5kg bag from Dropdown
String riceType="Ponni Boiled Rice - Super Premium";
WebElement eleRiceQuantity = driver.findElementByXPath("//a[text()='"+riceType+"']/parent::div/following-sibling::div//button/span");
if(eleRiceQuantity.getText().contains("5 kg"))
{
System.out.println("Rice Quantity as 5kg selected by default");
}
else
{
driver.findElementByXPath("//a[text()='"+riceType+"']/parent::div/following-sibling::div//button").click();
driver.findElementByXPath("//a[text()='"+riceType+"']/parent::div/following-sibling::div//ul//a").click();
System.out.println("Rice Quantity selected as 5kg");
}
//Print the price of the product
String riceprodPrice = driver.findElementByXPath("//a[text()='"+riceType+"']/parent::div/following-sibling::div[2]//span[@class='discnt-price']/span").getText();
System.out.println("Product price of Rice: "+riceprodPrice.replaceAll("\\D", ""));
//Click Add button
driver.findElementByXPath("//a[text()='"+riceType+"']/parent::div/following-sibling::div[2]//div[@class='delivery-opt']//button").click();
//Verify the success message displayed
wait.until(ExpectedConditions.visibilityOf(driver.findElementByXPath("//div[@class='toast-title']")));
String riceAddedMsg = driver.findElementByXPath("//div[@class='toast-title']").getText();
System.out.println("Second item added: "+riceAddedMsg);
driver.findElementByClassName("toast-close-button").click();
//Type Dal in Search field and enter
driver.findElementById("input").sendKeys("Dal");
driver.findElementByXPath("//button[@qa='searchBtn']").click();
System.out.println("Search for Dal products");
Thread.sleep(1000);
//Go to Toor/Arhar Dal and select 2kg & set Qty 2
String dalType="Toor/Arhar Dal/Thuvaram Paruppu";
driver.findElementByXPath("//a[text()='"+dalType+"']/parent::div//following-sibling::div//button").click();
driver.findElementByXPath("//a[text()='Toor/Arhar Dal/Thuvaram Paruppu']/parent::div//following-sibling::div//ul/li[4]").click();
System.out.println("Dal Quantity selected as 2kg");
driver.findElementByXPath("//a[text()='"+dalType+"']/parent::div/following-sibling::div[2]//div[3]//input").clear();
driver.findElementByXPath("//a[text()='"+dalType+"']/parent::div/following-sibling::div[2]//div[3]//input").sendKeys("2");
System.out.println("2 Dal products selected");
//Print the price of Dal
String dalPrice = driver.findElementByXPath("//a[text()='"+dalType+"']/parent::div/following-sibling::div[2]//h4/span[2]/span").getText();
System.out.println("Price of Dal product: "+dalPrice.replaceAll("//D", ""));
//Click Add button and verify success message
driver.findElementByXPath("//a[text()='"+dalType+"']/parent::div/following-sibling::div[2]//div[3]//button").click();
wait.until(ExpectedConditions.visibilityOf(driver.findElementByXPath("//div[@class='toast-title']")));
String dalAddedMsg = driver.findElementByXPath("//div[@class='toast-title']").getText();
System.out.println("Second item added: "+dalAddedMsg);
driver.findElementByClassName("toast-close-button").click();
//Mouse hover on My Basket
Thread.sleep(500);
wait.until(ExpectedConditions.visibilityOf(driver.findElementByXPath("//span[text()='My Basket']")));
builder.moveToElement(driver.findElementByXPath("//span[text()='My Basket']")).click().build().perform();
//Validate the Sub Total displayed for the selected items
List<WebElement> eleProd = driver.findElementsByXPath("//div[@class='container-fluid item-wrap']");
System.out.println("Total calculation for first set of item selection");
//method called to verify Total against selected items
bb.verifyTotal(eleProd);
//Reduce the Quantity of Dal as 1
driver.findElementByXPath("//a[text()='bb Popular Toor/Arhar Dal 2 kg Pouch']/ancestor::div[3]/following-sibling::div//button").click();
Thread.sleep(1000);
//Validate the Sub Total for the current items
List<WebElement> eleReduceProd = driver.findElementsByXPath("//div[@class='container-fluid item-wrap']");
System.out.println("Total calculation after reduction of an item quantity");
//method called to verify Total against selected items
bb.verifyTotal(eleReduceProd);
//Close browser
driver.close();
}
//Resuable method to verify Grand total against sub total of selected items
public void verifyTotal(List<WebElement> eleProducts) throws InterruptedException
{
int prodCount = eleProducts.size();
WebDriverWait wt = new WebDriverWait(driver, 10);
wt.until(ExpectedConditions.visibilityOf(driver.findElementByXPath("//p[text()='Sub Total : ']/span/span")));
String strTotal = driver.findElementByXPath("//p[text()='Sub Total : ']/span/span").getText();
double grandTotal = Double.parseDouble(strTotal);
System.out.println("Grand total: "+grandTotal);
double splitTotal=0;
for(int i=0;i<prodCount;i++)
{
String strItemPrice = driver.findElementsByXPath("//div[@class='row mrp']/span").get(i).getText();
double itemPrice = Double.parseDouble(strItemPrice);
System.out.println("Item "+(i+1)+" price: "+itemPrice);
Thread.sleep(1000);
wt.until(ExpectedConditions.visibilityOf(driver.findElementByXPath("//div[@class='product-qty ng-binding']")));
String rawstrQty = driver.findElementsByXPath("//div[@class='product-qty ng-binding']").get(i).getText();
String[] split = rawstrQty.split("x");
double itemQty = Double.parseDouble(split[0]);
System.out.println("Item "+(i+1)+" quantity: "+itemQty);
splitTotal=splitTotal+(itemPrice*itemQty);
}
if(splitTotal==grandTotal)
{
System.out.println("Total matches with selected items: "+grandTotal);
}
else fail("Total mismatch");
}
}
| Janani-Palani/MyLearningSpace | Day6BigBasket.java | 2,698 | //Validate the Sub Total displayed for the selected items
| line_comment | en | false | 2,202 | 11 | 2,698 | 11 | 2,682 | 11 | 2,698 | 11 | 3,267 | 12 | false | false | false | false | false | true |
181208_0 | /*
Guy Bernstein
id: 206558439
Main application class that loads and displays the Painter's GUI.
*/
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.util.Objects;
public class Painter extends Application {
@Override
public void start(Stage stage) throws Exception {
Parent root =
FXMLLoader.load(Objects.requireNonNull(getClass().getResource("Painter.fxml")));
Scene scene = new Scene(root);
stage.setTitle("Painter"); // displayed in window's title bar
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
| GuyBernstein/JavaFXPainterApplication | Painter.java | 204 | /*
Guy Bernstein
id: 206558439
Main application class that loads and displays the Painter's GUI.
*/ | block_comment | en | false | 152 | 30 | 204 | 39 | 210 | 35 | 204 | 39 | 236 | 40 | false | false | false | false | false | true |
182052_2 | package com;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.UnknownHostException;
import org.voltdb.client.ClientConfig;
import org.voltdb.client.ClientResponse;
import org.voltdb.client.ProcedureCallback;
public class basket {
/**
* @param args
* @throws IOException
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException {
/*
* Get the file from the path
*/
File file = new File("/opt/poc/main_execute/basket_dump.txt");
int vCounter = 0;
/*
*Get the argument from the command line
*/
/* if(args[0].length() > 0){
vCounter = Integer.parseInt(args[0].toString());
} else {
vCounter = 1000;
}*/
int ch;
StringBuffer strContent = new StringBuffer("");
FileReader fileInSt = null;
String readLine;
boolean firstLine = true;
ClientConfig clientConfig = new ClientConfig();
org.voltdb.client.Client client = org.voltdb.client.ClientFactory.createClient(clientConfig);
// Client instance connected to the database running on
// the specified IP address, in this case 127.0.0.1. The
// database always runs on TCP/IP port 21212.
client.createConnection("localhost");
try{
FileInputStream fStream = new FileInputStream(file);
DataInputStream in = new DataInputStream(fStream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
fileInSt = new FileReader(file);
int curLineNr = 1;
int skipLines = 1;
int count = 0;
/*
* Skip the first line
*/
while ((readLine = br.readLine()) != null) {
if (curLineNr++ <= skipLines) {
System.out.println("ReadLine "+readLine.toString());
break;
}
}
while ((readLine = br.readLine()) != null) {
String[] values = readLine.toString().split("\\|");
System.out.println(values[0]+"|"+values[1]+"|"+values[2]+"|"+values[3]+"|"+values[4]);
client.callProcedure(new ProcedureCallback() {
@Override
public void clientCallback(ClientResponse clientResponse) throws Exception {
if (clientResponse.getStatus() != ClientResponse.SUCCESS) {
System.err.println(clientResponse.getStatusString());
}
}
},"BasketInsert",
values[0].toString(),
values[1].toString(),
Float.parseFloat(values[2].toString()),
values[3].toString(),
values[4].toString()
);
count++;
System.out.println("count "+count);
}
/*
* File close
*/
fileInSt.close();
}catch (FileNotFoundException e)
{
System.out.println("file" + file.getAbsolutePath()+ "could not be found");
}
catch (IOException ioe) {
System.out.println("problem reading the file" + ioe);
}catch(Exception e){
e.printStackTrace();
}
}
}
| ben-haim/TickDataStreaming | basket.java | 885 | /*
*Get the argument from the command line
*/ | block_comment | en | false | 764 | 15 | 885 | 14 | 1,025 | 19 | 885 | 14 | 1,196 | 21 | false | false | false | false | false | true |
183371_10 | package orders;
import catalogue.Basket;
import catalogue.Product;
import debug.DEBUG;
import middle.OrderException;
import middle.OrderProcessing;
import java.util.stream.Collectors;
import java.util.*;
/**
* The order processing system.<BR>
* Manages the progression of customer orders,
* instances of a Basket as they are progressed through the system.
* These stages are:
* <BR><B>Waiting to be processed<BR>
* Currently being picked<BR>
* Waiting to be collected<BR></B>
* @author Mike Smith University of Brighton
* @version 3.0
*/
public class Order implements OrderProcessing
{
private enum State {Waiting, BeingPicked, NeedAttention, ToBeCollected };
/**
* Wraps a Basket and it state into a folder
*/
private class Folder
{
private State stateIs; // Order state
private Basket basket; // For this basket
public Folder( Basket anOrder )
{
stateIs = State.Waiting;
basket = anOrder;
}
public State getState() { return this.stateIs; }
public Basket getBasket() { return this.basket; }
public void newState( State newState ) { stateIs = newState; }
}
// Active orders in the Catshop system
private final ArrayList<Folder> folders = new ArrayList<>();
/**
* Used to generate debug information
* @param basket an instance of a basket
* @return Description of contents
*/
private String asString( Basket basket )
{
StringBuilder sb = new StringBuilder(1024);
Formatter fr = new Formatter(sb);
fr.format( "#%d (", basket.getOrderNum() );
for ( Product pr: basket )
{
fr.format( "%-15.15s: %3d ", pr.getDescription(), pr.getQuantity() );
}
fr.format( ")" );
fr.close();
return sb.toString();
}
/**
* Add a new order to the order processing system
* @param bought A new order that is to be processed
*/
public synchronized void newOrder( Basket bought )
throws OrderException
{
DEBUG.trace( "DEBUG: New order" );
folders.add( new Folder( bought ) );
for ( Folder bws : folders )
{
DEBUG.trace( "Order: " + asString( bws.getBasket() ) );
}
}
/**
* Returns an order to pick from the warehouse.
* @return An order to pick or null if no order
*/
public synchronized Basket getOrderToPick()
throws OrderException
{
DEBUG.trace( "DEBUG: Get order to pick" );
Basket foundWaiting = null;
for ( Folder bws : folders )
{
if ( bws.getState() == State.Waiting )
{
foundWaiting = bws.getBasket();
bws.newState( State.BeingPicked );
break;
}
}
return foundWaiting;
}
/**
* Returns an order to need attention from the orders.
* @return An order to need attention or null if no order
*/
public synchronized Basket getOrderToNeedAttention()
throws OrderException
{
DEBUG.trace( "DEBUG: Get order to need attention" );
Basket foundAttention = null;
for ( Folder bws : folders )
{
if ( bws.getState() == State.NeedAttention )
{
foundAttention = bws.getBasket();
folders.remove(bws); // remove folder
break;
}
}
return foundAttention;
}
/**
* Informs the order processing system that the order has been
* picked and the products are now being delivered to the
* collection desk
* @param orderNum The order that has been picked
* @return true Order in system, false no such order
*/
public synchronized boolean informOrderPicked( int orderNum )
throws OrderException
{
DEBUG.trace( "DEBUG: Order picked [%d]", orderNum );
for ( int i=0; i < folders.size(); i++)
{
if ( folders.get(i).getBasket().getOrderNum() == orderNum &&
folders.get(i).getState() == State.BeingPicked )
{
folders.get(i).newState( State.ToBeCollected );
return true;
}
}
return false;
}
/**
* Informs the order processing system that the order has been
* collected by the customer
* @return true If order is in the system, otherwise false
*/
public synchronized boolean informOrderCollected( int orderNum )
throws OrderException
{
DEBUG.trace( "DEBUG: Order collected [%d]", orderNum );
for ( int i=0; i < folders.size(); i++)
{
if ( folders.get(i).getBasket().getOrderNum() == orderNum &&
folders.get(i).getState() == State.ToBeCollected )
{
folders.remove(i);
return true;
}
}
return false;
}
/**
* Informs the order processing system that the order has been
* needed attention by the customer
* @return true If order is in the system, otherwise false
*/
public synchronized boolean informNeedAttention(int orderNum) {
DEBUG.trace( "DEBUG: Need Attention [%d]", orderNum );
for ( int i=0; i < folders.size(); i++)
{
if ( folders.get(i).getBasket().getOrderNum() == orderNum &&
folders.get(i).getState() == State.BeingPicked )
{
folders.get(i).newState( State.NeedAttention );
return true;
}
}
return false;
}
/**
* Returns information about all the orders (there order number)
* in the order processing system
* This consists of a map with the following keys:
*<PRE>
* Key "Waiting" a list of orders waiting to be processed
* Key "BeingPicked" a list of orders that are currently being picked
* Key "ToBeCollected" a list of orders that can now be collected
* Associated with each key is a List<Integer> of order numbers.
* Note: Each order number will be unique number.
* </PRE>
* @return a Map with the keys: "Waiting", "BeingPicked", "ToBeCollected"
*/
public synchronized Map<String, List<Integer> > getOrderState()
throws OrderException
{
//DEBUG.trace( "DEBUG: get state of order system" );
Map < String, List<Integer> > res = new HashMap<>();
res.put( "Waiting", orderNums(State.Waiting) );
res.put( "BeingPicked", orderNums(State.BeingPicked) );
res.put( "ToBeCollected", orderNums(State.ToBeCollected) );
return res;
}
/**
* Return the list of order numbers in selected state
* @param inState The state to find order numbers in
* @return A list of order numbers
*/
private List<Integer> orderNumsOldWay( State inState )
{
List <Integer> res = new ArrayList<>();
for ( Folder folder : folders )
{
if ( folder.getState() == inState )
{
res.add( folder.getBasket().getOrderNum() );
}
}
return res;
}
/**
* Return the list of order numbers in selected state
* @param inState The state to find order numbers in
* @return A list of order numbers
*/
private List<Integer> orderNums( State inState )
{
return folders.stream()
.filter( folder -> folder.getState() == inState )
.map( folder -> folder.getBasket().getOrderNum() )
.collect( Collectors.toList() );
}
}
| Imesh-Isuranga/Catshop | orders/Order.java | 1,795 | /**
* Informs the order processing system that the order has been
* picked and the products are now being delivered to the
* collection desk
* @param orderNum The order that has been picked
* @return true Order in system, false no such order
*/ | block_comment | en | false | 1,736 | 63 | 1,795 | 59 | 1,991 | 64 | 1,795 | 59 | 2,159 | 65 | false | false | false | false | false | true |
183469_0 | package enigma;
/** Class that represents a rotor in the enigma machine.
* @author Felix Liu
*/
class Rotor {
/** Base fields needed for correct run */
/** the variable TEST holds the information for the cypher
* or where each letter should be converted to. */
private static String[][] test = PermutationData.ROTOR_SPECS;
/** the variable ALPHABET creates a blueprint for the methods
* to look at when determining the indexing number. */
private static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/** the variable PARTICULAR holds the information on the specific
* that is currently being used. This isn't static because it needs
* the change when new rotors are created. */
private String[] particular;
/** the variable START holds the current letter's number or position
* so the methods can add on or alter it with ROTOR_SPECS to get the
* correct decoding information. */
private int start;
/** A Rotor with null input and start0. */
Rotor() {
this (null);
}
/** A list with type INPUT and position START0. */
Rotor(String input) {
int place = 0;
while (place < test.length) {
if (test[place][0].equals(input)) {
particular = test[place];
}
place += 1;
}
}
/** A getter method to obtain PARTICULAR for machine
* and returns particular. */
String[] getParticular() {
return particular;
}
/** the function startpos takes in START0 to change the char into
* an index number, easily accessed by in int methods, convertForward and
* convertBackwards. */
void startpos(char start0) {
start = toIndex(start0);
}
/** Size of ALPHABET used for plaintext and ciphertext. */
static final int ALPHABET_SIZE = 26;
/** Assuming that P is an integer in the range 0..25, returns the
* corresponding upper-case letter in the range A..Z. */
static char toLetter(int p) {
return ALPHABET.charAt(p);
}
/** Assuming that C is an upper-case letter in the range A-Z, return the
* corresponding index in the range 0..25. Inverse of toLetter. */
static int toIndex(char c) {
return ALPHABET.indexOf(c);
}
/** Returns true iff this rotor has a ratchet and can advance. */
boolean advances() {
return particular.length == 4;
}
/** Returns true iff this rotor has a left-to-right inverse. */
boolean hasInverse() {
return particular.length > 2;
}
/** Return the conversion of P (an integer in the range 0..25)
* according to my permutation. */
int convertForward(int p) {
int combo = (p + start) % ALPHABET_SIZE;
String perm = particular[1];
int letternumber, finalnumber;
finalnumber = (toIndex(perm.charAt(combo)) - start);
if (finalnumber < 0) {
finalnumber += ALPHABET_SIZE;
}
return finalnumber % ALPHABET_SIZE;
}
/** Return the conversion of E (an integer in the range 0..25)
* according to the inverse of my permutation. */
int convertBackward(int e) {
int combo = (e + start) % ALPHABET_SIZE;
String perm = particular[2];
int letternumber, finalnumber;
finalnumber = (toIndex(perm.charAt(combo)) - start);
if (finalnumber < 0) {
finalnumber += ALPHABET_SIZE;
}
return finalnumber % ALPHABET_SIZE;
}
/** Returns true iff I am positioned to allow the rotor to my left
* to advance. */
boolean atNotch() {
if (!this.advances()) {
return false;
}
if (start == toIndex(particular[3].charAt(0))) {
return true;
} else if (particular[3].length() > 1
&& start == toIndex(particular[3].charAt(1))) {
return true;
}
return false;
}
/** Advance me one position. */
void advance() {
start = (start + 1) % ALPHABET_SIZE;
}
}
| felixitous/JavaConverter | Rotor.java | 1,045 | /** Class that represents a rotor in the enigma machine.
* @author Felix Liu
*/ | block_comment | en | false | 992 | 20 | 1,045 | 24 | 1,088 | 20 | 1,045 | 24 | 1,229 | 23 | false | false | false | false | false | true |
185830_1 | /*
* Name: Nicholas Campos
* PID: A17621673
* Email: [email protected]
* References: JDK, Lecture Notes
*
* Contains a class that defines a Lion object that extends from the
* Feline class.
*/
import java.awt.Color;
/**
* a class defining all the possible methods
* that can be called on a Lion. Lions move in squares.
*/
public class Lion extends Feline {
private static final String SPECIES_NAME = "Lion";
private static final String REVERSED_SPECIES_NAME = "noiL";
private static final int WALK_LENGTH = 5;
private int eastSteps;
private int southSteps;
private int westSteps;
private int northSteps;
private int fightsWon;
/**
* Default constructor - creates critter with name Lion, fights won 0, and
* steps in all directions 0
*/
public Lion() {
displayName = SPECIES_NAME;
fightsWon = 0;
eastSteps = 0;
southSteps = 0;
westSteps = 0;
northSteps = 0;
}
/**
* called when getting the color of a Lion.
*
* @return yellow color
*/
@Override
public Color getColor() {
return Color.YELLOW;
}
/**
* called to move in a certain direction.
*
* @return the direction
*/
@Override
public Direction getMove() {
if (eastSteps < WALK_LENGTH) {
eastSteps++;
return Direction.EAST;
} else if (eastSteps == WALK_LENGTH && southSteps < WALK_LENGTH) {
southSteps++;
return Direction.SOUTH;
} else if (southSteps == WALK_LENGTH && westSteps < WALK_LENGTH) {
westSteps++;
return Direction.WEST;
} else if (westSteps == WALK_LENGTH && northSteps < WALK_LENGTH) {
northSteps++;
return Direction.NORTH;
} else {
eastSteps = 1;
southSteps = 0;
westSteps = 0;
northSteps = 0;
return Direction.EAST;
}
}
/**
* Returns whether the critter wants to eat the encountered food or not.
*
* @return lions get hungry after winning a fight
*/
@Override
public boolean eat() {
if (fightsWon > 0) {
fightsWon = 0;
return true;
}
return false;
}
/**
* called when your animal is put to sleep for eating too much food.
* Fights won is reset to 0 and display name is reversed.
*/
@Override
public void sleep() {
fightsWon = 0;
displayName = REVERSED_SPECIES_NAME;
}
/**
* called when your animal wakes up from sleeping. display name is
* reverted back to original name
*/
@Override
public void wakeup() {
displayName = SPECIES_NAME;
}
/**
* called when you win a fight against another animal.
* Lion's fights won increments.
*/
@Override
public void win() {
fightsWon++;
}
} | nickcamp13/cse11 | PA7/Lion.java | 769 | /**
* a class defining all the possible methods
* that can be called on a Lion. Lions move in squares.
*/ | block_comment | en | false | 702 | 25 | 769 | 29 | 798 | 27 | 769 | 29 | 919 | 28 | false | false | false | false | false | true |
187094_8 |
// Java implementation of finding length of longest
// Common substring using Dynamic Programming
public
class
LongestCommonSubSequence
{
/*
Returns length of longest common substring
of X[0..m-1] and Y[0..n-1]
*/
static
int
LCSubStr(
char
X[],
char
Y[],
int
m,
int
n)
{
// Create a table to store lengths of longest common suffixes of
// substrings. Note that LCSuff[i][j] contains length of longest
// common suffix of X[0..i-1] and Y[0..j-1]. The first row and
// first column entries have no logical meaning, they are used only
// for simplicity of program
int
LCStuff[][] =
new
int
[m +
1
][n +
1
];
int
result =
0
;
// To store length of the longest common substring
// Following steps build LCSuff[m+1][n+1] in bottom up fashion
for
(
int
i =
0
; i <= m; i++)
{
for
(
int
j =
0
; j <= n; j++)
{
if
(i ==
0
|| j ==
0
)
LCStuff[i][j] =
0
;
else
if
(X[i -
1
] == Y[j -
1
])
{
LCStuff[i][j] = LCStuff[i -
1
][j -
1
] +
1
;
result = Integer.max(result, LCStuff[i][j]);
}
else
LCStuff[i][j] =
0
;
}
}
return
result;
}
// Driver Program to test above function
public
static
void
main(String[] args)
{
String X =
"OldSite:GeeksforGeeks.org"
;
String Y =
"NewSite:GeeksQuiz.com"
;
int
m = X.length();
int
n = Y.length();
System.out.println(
"Length of Longest Common Substring is "
+ LCSubStr(X.toCharArray(), Y.toCharArray(), m, n));
}
}
// This code is contributed by Sumit Ghosh | dhyan/code2vec_code_complexity | Dataset/346.java | 589 | // To store length of the longest common substring | line_comment | en | false | 497 | 10 | 589 | 10 | 588 | 10 | 589 | 10 | 661 | 10 | false | false | false | false | false | true |
188544_0 | class Solution {
public int[] findBall(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int[] result = new int[n];
if (n == 1) {
result[0] = -1;
return result;
}
int curCol = 0;
outerloop:
for (int j = 0; j < n; j++) {
curCol = j;
result[j] += curCol;
for (int i = 0; i < m; i++) {
if (curCol < n && curCol >= 0) {
result[j] = result[j] + grid[i][curCol];
if (result[j] >= n) result[j] = -1;
if (grid[i][curCol] == 1) {
curCol++;
if (curCol < n) {
if (grid[i][curCol] == -1) {
result[j] = -1;
continue outerloop;
}
}
}
else {
curCol--;
if (curCol >= 0) {
if (grid[i][curCol] == 1) {
result[j] = -1;
continue outerloop;
}
}
}
}
else {
result[j] = -1;
}
}
}
//if its going to right and right+1 is -1 continue (hit V)
//if its going to left and left+1 is 1 continue
return result;
}
} | jdolphin5/leetcode | 1706.java | 354 | //if its going to right and right+1 is -1 continue (hit V) | line_comment | en | false | 340 | 18 | 354 | 18 | 405 | 18 | 354 | 18 | 435 | 18 | false | false | false | false | false | true |
192254_3 | import java.io.File;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
/**
* This class contains all the methods for playing all the different ringtones and sounds.
*
* @author Kate Moksina
* @editor Luke Simmons
* @version 25/02/2015
*/
public class Ringtone {
/*
* These Strings represent the names of the files to be used in each method call.
*/
final static String ringtoneSound = "Ringtone.wav";
final static String happySound = "HappySound.wav";
final static String sadSound = "SadSound.wav";
final static String tritoneSound = "Tritone.wav";
final static String helloSound = "HelloSound.wav";
final static String goodbyeSound = "GoodbyeSound.wav";
final static int buffer_size = 128000;
public static void ringtoneSound() { //This method plays the phone's ringtone.
try {
File audioFile = new File( ringtoneSound );
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream( audioFile );
AudioFormat audioFormat = audioInputStream.getFormat();
DataLine.Info info = new DataLine.Info( SourceDataLine.class, audioFormat );
SourceDataLine sourceLine = ( SourceDataLine ) AudioSystem.getLine( info );
sourceLine.open( audioFormat );
sourceLine.start();
byte[] audioBuffer = new byte[ buffer_size ];
int n = 0;
while ( n != -1 ) {
n = audioInputStream.read( audioBuffer, 0, audioBuffer.length );
if ( n >= 0 ) {
sourceLine.write( audioBuffer, 0, n );
}
}
sourceLine.drain();
sourceLine.close();
} catch ( Exception e ) {
e.printStackTrace();
System.exit( 1 );
}
}
public static void happySound() { //This method plays the phone's happy sound.
try {
File audioFile = new File( happySound );
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream( audioFile );
AudioFormat audioFormat = audioInputStream.getFormat();
DataLine.Info info = new DataLine.Info( SourceDataLine.class, audioFormat );
SourceDataLine sourceLine = ( SourceDataLine ) AudioSystem.getLine( info );
sourceLine.open( audioFormat );
sourceLine.start();
byte[] audioBuffer = new byte[ buffer_size ];
int n = 0;
while ( n != -1 ) {
n = audioInputStream.read( audioBuffer, 0, audioBuffer.length );
if ( n >= 0 ) {
sourceLine.write( audioBuffer, 0, n );
}
}
sourceLine.drain();
sourceLine.close();
} catch ( Exception e ) {
e.printStackTrace();
System.exit( 1 );
}
}
public static void sadSound() { //This method plays the phone's sad sound.
try {
File audioFile = new File( sadSound );
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream( audioFile );
AudioFormat audioFormat = audioInputStream.getFormat();
DataLine.Info info = new DataLine.Info( SourceDataLine.class, audioFormat );
SourceDataLine sourceLine = ( SourceDataLine ) AudioSystem.getLine( info );
sourceLine.open( audioFormat );
sourceLine.start();
byte[] audioBuffer = new byte[ buffer_size ];
int n = 0;
while ( n != -1 ) {
n = audioInputStream.read( audioBuffer, 0, audioBuffer.length );
if ( n >= 0 ) {
sourceLine.write( audioBuffer, 0, n );
}
}
sourceLine.drain();
sourceLine.close();
} catch ( Exception e ) {
e.printStackTrace();
System.exit( 1 );
}
}
public static void tritoneSound() { //This method plays the phone's tritone.
try {
File audioFile = new File( tritoneSound );
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream( audioFile );
AudioFormat audioFormat = audioInputStream.getFormat();
DataLine.Info info = new DataLine.Info( SourceDataLine.class, audioFormat );
SourceDataLine sourceLine = ( SourceDataLine ) AudioSystem.getLine( info );
sourceLine.open( audioFormat );
sourceLine.start();
byte[] audioBuffer = new byte[ buffer_size ];
int n = 0;
while ( n != -1 ) {
n = audioInputStream.read( audioBuffer, 0, audioBuffer.length );
if ( n >= 0 ) {
sourceLine.write( audioBuffer, 0, n );
}
}
sourceLine.drain();
sourceLine.close();
} catch ( Exception e ) {
e.printStackTrace();
System.exit( 1 );
}
}
public static void helloSound() { //This method plays the phone's hello sound.
try {
File audioFile = new File( helloSound );
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream( audioFile );
AudioFormat audioFormat = audioInputStream.getFormat();
DataLine.Info info = new DataLine.Info( SourceDataLine.class, audioFormat );
SourceDataLine sourceLine = ( SourceDataLine ) AudioSystem.getLine( info );
sourceLine.open( audioFormat );
sourceLine.start();
byte[] audioBuffer = new byte[ buffer_size ];
int n = 0;
while ( n != -1 ) {
n = audioInputStream.read( audioBuffer, 0, audioBuffer.length );
if ( n >= 0 ) {
sourceLine.write( audioBuffer, 0, n );
}
}
sourceLine.drain();
sourceLine.close();
} catch ( Exception e ) {
e.printStackTrace();
System.exit( 1 );
}
}
public static void goodbyeSound() { //This method plays the phone's goodbye sound.
try {
File audioFile = new File( goodbyeSound );
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream( audioFile );
AudioFormat audioFormat = audioInputStream.getFormat();
DataLine.Info info = new DataLine.Info( SourceDataLine.class, audioFormat );
SourceDataLine sourceLine = ( SourceDataLine ) AudioSystem.getLine( info );
sourceLine.open( audioFormat );
sourceLine.start();
byte[] audioBuffer = new byte[ buffer_size ];
int n = 0;
while ( n != -1 ) {
n = audioInputStream.read( audioBuffer, 0, audioBuffer.length );
if ( n >= 0 ) {
sourceLine.write( audioBuffer, 0, n );
}
}
sourceLine.drain();
sourceLine.close();
} catch ( Exception e ) {
e.printStackTrace();
System.exit( 1 );
}
}
}
| je-durrans/dumbphone | src/Ringtone.java | 1,640 | //This method plays the phone's happy sound. | line_comment | en | false | 1,566 | 10 | 1,640 | 10 | 1,901 | 11 | 1,640 | 10 | 1,959 | 11 | false | false | false | false | false | true |
192810_1 | import org.junit.Test;
import static org.junit.Assert.assertEquals;
import java.io.*;
public class UnitTestExample {
private Integer n; // not used, just showing a style issue
private String planet = "Earth";
private String satellite = "moon";
@Test
public void test1() {
String expectedName = "Earth";
String resultName = this.planet; // or would be something a method could return, etc
assertEquals(expectedName, resultName);
}
@Test
public void test2() {
String expectedName = "Moon";
String resultName = this.satellite; // or would be something a method could return, etc
assertEquals(expectedName, resultName);
}
// illustrates running something from the terminal via Java/Junit
@Test
public void test3() {
String outputCollected = "";
String command = "java -jar checkstyle-9.2.1-all.jar -c ./CS1111_checks.xml UnitTestExample.java";
try {
Process process = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null)
outputCollected += line;
reader.close();
reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while ((line = reader.readLine()) != null)
outputCollected += line;
reader.close();
} catch (IOException exc) {
exc.printStackTrace();
}
System.out.println(outputCollected);
String expectedName = "Starting audit...Audit done.";
String resultName = outputCollected;
assertEquals(expectedName, resultName);
}
// no main method
}
| cs2113-s24/cs2113-s24.github.io | labs/UnitTestExample.java | 430 | // or would be something a method could return, etc | line_comment | en | false | 359 | 11 | 430 | 11 | 429 | 11 | 430 | 11 | 514 | 11 | false | false | false | false | false | true |
193210_6 | import java.util.Collections;
import java.util.ArrayList;
public class Bank2 implements BankInterface{
String nameOfBank;
private ArrayList<Account> accounts;
private int numOfAccounts;
public Bank2(String name) {
nameOfBank = name;
accounts = new ArrayList<>();
numOfAccounts = 0;
}
public void addAccount(Account account) {
accounts.add(account);
numOfAccounts++;
}
public Account search(String id) {
int index = binarySearchWithArrayList(accounts, 0, accounts.size()-1, id);
if (index == -1) {
return null;
} else {
return accounts.get(index);
}
}
public void deposit(String id, Money amount) {
Account account = search(id);
if (account != null) {
account.deposit(amount);
}
}
public void withdraw(String id, Money amount) {
Account account = search(id);
if (account != null) {
account.withdraw(amount);
}
}
public String toString() {
StringBuilder result = new StringBuilder("Bank name: " + nameOfBank + "\n");
for (int i = 0; i < numOfAccounts; i++) {
result.append(accounts.get(i).toString()).append("\n");
}
return result.toString();
}
public void sortAccounts(){
Collections.sort(accounts);
}
public int getNumOfAccounts() {
return numOfAccounts;
}
public String getNameOfBank() {
return nameOfBank;
}
public int binarySearchWithArrayList(ArrayList<Account> anArray, int first, int last, String value) {
// Searches the array items anArray[first] through
// anArray[last] for value by using a binary search.
// Precondition: 0 <= first, last <= SIZE-1, where
// SIZE is the maximum size of the array, and
// anArray[first] <= anArray[first+1] <= ... <= anArray[last].
// Postcondition: If value is in the array, the method
// returns the index of the array item that equals value;
// otherwise the method returns -1.
int index;
if (first > last) {
index = -1; // value not in original array
}
else {
// Invariant: If value is in anArray,
// anArray[first] <= value <= anArray[last]
int mid = (first + last)/2;
if (value.equals(anArray.get(mid).getId())) {
index = mid; // value found at anArray[mid]
}
else if (value.compareTo(anArray.get(mid).getId()) < 0) {
index = binarySearchWithArrayList(anArray, first, mid-1, value); // point X
}
else {
index = binarySearchWithArrayList(anArray, mid+1, last, value); // point Y
} // end if
} // end if
return index;
} // end binarySearch
}
| toji-ut/TDD-of-Bank-program | Bank2.java | 694 | // returns the index of the array item that equals value; | line_comment | en | false | 652 | 12 | 694 | 12 | 769 | 12 | 694 | 12 | 833 | 12 | false | false | false | false | false | true |
194518_2 | package unisa.gps.etour.repository;
import java.sql.SQLException;
import java.util.ArrayList;
import unisa.gps.etour.bean.BeanCulturalHeritage;
import unisa.gps.etour.bean.BeanTourist;
/**
* Interface for the management of tourists in the database
*
*/
public interface IDBTourist {
/**
* Add a tourist
*
* @Param to add pTourist Tourist
*/
public boolean insertTourist(BeanTourist pTourist) throws SQLException;
/**
* Modify a tourist
*
* @Param to change pTourist Tourist
* @Return True if and 'been changed otherwise false
*/
public boolean modifyTourist(BeanTourist pTourist) throws SQLException;
/**
* Delete a tourist from the database
*
* @Param pIdTourist Identificatie Tourist delete
* @Return True if and 'been changed otherwise false
*/
public boolean delete(int pIdTourist) throws SQLException;
/**
* Returns the data of the Tourist
*
* @Param pUsername Username tourists
* @Return Information about tourist
*/
public BeanTourist getTourist(String pUsername) throws SQLException;
/**
* Attach a cultural tourists preferred
*
* @Param ID pIdTourist tourists
* @Param pIdCulturalHeritage ID of the cultural
*/
public boolean insertCulturalHeritagePreference(int pIdTourist, int pIdCulturalHeritage) throws SQLException;
/**
* Attach a point of catering to the tourist favorite
*
* @Param ID pIdTourist tourists
* @Param pIdRefreshmentPoint ID of the cultural
*/
public boolean insertRefreshmentPointPreference(int pIdTourist, int pIdRefreshmentPoint) throws SQLException;
/**
* Delete a cultural favorite
*
* @Param ID pIdTourist tourists
* @Param pIdCulturalHeritage ID of the cultural
* @Return True if and 'been changed otherwise false
*/
public boolean clearCulturalHeritagePreference(int pIdTourist, int pIdCulturalHeritage) throws SQLException;
/**
* Delete a favorite resting spot
*
* @Param ID pIdTourist tourists
* @Param pIdRefreshmentPoint ID of the cultural
* @Return True if and 'was deleted false otherwise
*/
public boolean clearRefreshmentPointPreference(int pIdTourist, int pIdRefreshmentPoint) throws SQLException;
/**
* Returns an ArrayList of tourists who have a username like that Given as
* argument
*
* @Param pUsernameTourist Usrername tourists to search
* @Return data for Tourists
*/
public ArrayList<BeanTourist> getTourists(String pUsernameTourist) throws SQLException;
/**
* Returns the list of tourists turned on or off
*
* @Param select pact True False those tourists turned off
* @Return data for Tourists
*/
public ArrayList<BeanTourist> getTourist(boolean condition) throws SQLException;
/**
* Returns the data of the tourist with ID equal to that given in Input
*
* @Param ID pIdTourist tourists to find
* @Return Tourists with id equal to the input, null if there is
*/
public BeanTourist getTourist(int pIdTourist) throws SQLException;
/**
* Returns the list of cultural favorites from a particular Tourist
*
* @Param ID pIdTourist tourists to find
* @Return List of Cultural Heritage Favorites
*/
public ArrayList<Integer> getCulturalHeritagePreference(int pIdTourist) throws SQLException;
/**
* Returns a list of favorite resting spot by a particular Tourist
*
* @Param ID pIdTourist tourists to find
* @Return List of Refreshment Favorites
*/
public ArrayList<Integer> getRefreshmentPointPreference(int pIdTourist) throws SQLException;
} | ZZYG0g0g0/AC-XWCoDe | datasets/eTour/code/IDBTourist.java | 941 | /**
* Modify a tourist
*
* @Param to change pTourist Tourist
* @Return True if and 'been changed otherwise false
*/ | block_comment | en | false | 877 | 36 | 941 | 35 | 979 | 39 | 941 | 35 | 1,174 | 47 | false | false | false | false | false | true |
195964_9 | /*
* 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/>.
*/
/*
* Memory.java
* Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import javax.swing.JCheckBox;
import javax.swing.JOptionPane;
/**
* A little helper class for Memory management. The memory management can be
* disabled by using the setEnabled(boolean) method.
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision: 9493 $
* @see #setEnabled(boolean)
*/
public class Memory implements RevisionHandler {
/** whether memory management is enabled */
protected static boolean m_Enabled = true;
/** whether a GUI is present */
protected boolean m_UseGUI = false;
/** the managed bean to use */
protected static MemoryMXBean m_MemoryMXBean = ManagementFactory
.getMemoryMXBean();
/** the last MemoryUsage object obtained */
protected MemoryUsage m_MemoryUsage = null;
/**
* initializes the memory management without GUI support
*/
public Memory() {
this(false);
}
/**
* initializes the memory management
*
* @param useGUI whether a GUI is present
*/
public Memory(boolean useGUI) {
m_UseGUI = useGUI;
}
/**
* returns whether the memory management is enabled
*
* @return true if enabled
*/
public boolean isEnabled() {
return m_Enabled;
}
/**
* sets whether the memory management is enabled
*
* @param value true if the management should be enabled
*/
public void setEnabled(boolean value) {
m_Enabled = value;
}
/**
* whether to display a dialog in case of a problem (= TRUE) or just print on
* stderr (= FALSE)
*
* @return true if the GUI is used
*/
public boolean getUseGUI() {
return m_UseGUI;
}
/**
* returns the initial size of the JVM heap, obtains a fresh MemoryUsage
* object to do so.
*
* @return the initial size in bytes
*/
public long getInitial() {
m_MemoryUsage = m_MemoryMXBean.getHeapMemoryUsage();
return m_MemoryUsage.getInit();
}
/**
* returns the currently used size of the JVM heap, obtains a fresh
* MemoryUsage object to do so.
*
* @return the used size in bytes
*/
public long getCurrent() {
m_MemoryUsage = m_MemoryMXBean.getHeapMemoryUsage();
return m_MemoryUsage.getUsed();
}
/**
* returns the maximum size of the JVM heap, obtains a fresh MemoryUsage
* object to do so.
*
* @return the maximum size in bytes
*/
public long getMax() {
m_MemoryUsage = m_MemoryMXBean.getHeapMemoryUsage();
return m_MemoryUsage.getMax();
}
/**
* checks if there's still enough memory left by checking whether there is
* still a 50MB margin between getUsed() and getMax(). if ENABLED is true,
* then false is returned always. updates the MemoryUsage variable before
* checking.
*
* @return true if out of memory (only if management enabled, otherwise always
* false)
*/
public boolean isOutOfMemory() {
m_MemoryUsage = m_MemoryMXBean.getHeapMemoryUsage();
if (isEnabled()) {
return ((m_MemoryUsage.getMax() - m_MemoryUsage.getUsed()) < 52428800);
} else
return false;
}
/**
* Checks to see if memory is running low. Low is defined as available memory
* less than 20% of max memory.
*
* @return true if memory is running low
*/
public boolean memoryIsLow() {
m_MemoryUsage = m_MemoryMXBean.getHeapMemoryUsage();
if (isEnabled()) {
long lowThreshold = (long) (0.2 * m_MemoryUsage.getMax());
// min threshold of 100Mb
if (lowThreshold < 104857600) {
lowThreshold = 104857600;
}
long avail = m_MemoryUsage.getMax() - m_MemoryUsage.getUsed();
return (avail < lowThreshold);
} else {
return false;
}
}
/**
* returns the amount of bytes as MB
*
* @return the MB amount
*/
public static double toMegaByte(long bytes) {
return (bytes / (double) (1024 * 1024));
}
/**
* prints an error message if OutOfMemory (and if GUI is present a dialog),
* otherwise nothing happens. isOutOfMemory() has to be called beforehand,
* since it sets all the memory parameters.
*
* @see #isOutOfMemory()
* @see #m_Enabled
*/
public void showOutOfMemory() {
if (!isEnabled() || (m_MemoryUsage == null))
return;
System.gc();
String msg = "Not enough memory (less than 50MB left on heap). Please load a smaller "
+ "dataset or use a larger heap size.\n"
+ "- initial heap size: "
+ Utils.doubleToString(toMegaByte(m_MemoryUsage.getInit()), 1)
+ "MB\n"
+ "- current memory (heap) used: "
+ Utils.doubleToString(toMegaByte(m_MemoryUsage.getUsed()), 1)
+ "MB\n"
+ "- max. memory (heap) available: "
+ Utils.doubleToString(toMegaByte(m_MemoryUsage.getMax()), 1)
+ "MB\n"
+ "\n"
+ "Note:\n"
+ "The Java heap size can be specified with the -Xmx option.\n"
+ "E.g., to use 128MB as heap size, the command line looks like this:\n"
+ " java -Xmx128m -classpath ...\n"
+ "This does NOT work in the SimpleCLI, the above java command refers\n"
+ "to the one with which Weka is started. See the Weka FAQ on the web\n"
+ "for further info.";
System.err.println(msg);
if (getUseGUI())
JOptionPane.showMessageDialog(null, msg, "OutOfMemory",
JOptionPane.WARNING_MESSAGE);
}
/**
* Prints a warning message if memoryIsLow (and if GUI is present a dialog).
*
* @return true if user opts to continue, disabled or GUI is not present.
*/
public boolean showMemoryIsLow() {
if (!isEnabled() || (m_MemoryUsage == null))
return true;
String msg = "Warning: memory is running low - available heap space is less than "
+ "20% of maximum or 100MB (whichever is greater)\n\n"
+ "- initial heap size: "
+ Utils.doubleToString(toMegaByte(m_MemoryUsage.getInit()), 1)
+ "MB\n"
+ "- current memory (heap) used: "
+ Utils.doubleToString(toMegaByte(m_MemoryUsage.getUsed()), 1)
+ "MB\n"
+ "- max. memory (heap) available: "
+ Utils.doubleToString(toMegaByte(m_MemoryUsage.getMax()), 1)
+ "MB\n\n"
+ "Consider deleting some results before continuing.\nCheck the Weka FAQ "
+ "on the web for suggestions on how to save memory.\n"
+ "Note that Weka will shut down when less than 50MB remain."
+ "\nDo you wish to continue regardless?\n\n";
System.err.println(msg);
/* if (getUseGUI()) {
if (!Utils.getDontShowDialog("weka.core.Memory.LowMemoryWarning")) {
JCheckBox dontShow = new JCheckBox("Do not show this message again");
Object[] stuff = new Object[2];
stuff[0] = msg;
stuff[1] = dontShow;
int result = JOptionPane.showConfirmDialog(null, stuff, "Memory",
JOptionPane.YES_NO_OPTION);
if (dontShow.isSelected()) {
try {
Utils.setDontShowDialog("weka.core.Memory.LowMemoryWarning");
} catch (Exception ex) {
// quietly ignore
}
}
return (result == JOptionPane.YES_OPTION);
}
}
*/
return true;
}
/**
* stops all the current threads, to make a restart possible
*/
public void stopThreads() {
int i;
Thread[] thGroup;
Thread t;
thGroup = new Thread[Thread.activeCount()];
Thread.enumerate(thGroup);
for (i = 0; i < thGroup.length; i++) {
t = thGroup[i];
if (t != null) {
if (t != Thread.currentThread()) {
if (t.getName().startsWith("Thread"))
t.stop();
else if (t.getName().startsWith("AWT-EventQueue"))
t.stop();
}
}
}
thGroup = null;
System.gc();
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision: 9493 $");
}
/**
* prints only some statistics
*
* @param args the commandline arguments - ignored
*/
public static void main(String[] args) {
Memory mem = new Memory();
System.out.println("Initial memory: "
+ Utils.doubleToString(Memory.toMegaByte(mem.getInitial()), 1) + "MB"
+ " (" + mem.getInitial() + ")");
System.out.println("Max memory: "
+ Utils.doubleToString(Memory.toMegaByte(mem.getMax()), 1) + "MB"
+ " (" + mem.getMax() + ")");
}
}
| time-series-machine-learning/tsml-java | src/main/java/weka/core/Memory.java | 2,516 | /**
* returns whether the memory management is enabled
*
* @return true if enabled
*/ | block_comment | en | false | 2,391 | 24 | 2,516 | 21 | 2,745 | 26 | 2,516 | 21 | 2,970 | 26 | false | false | false | false | false | true |
196255_0 | public class Graduate extends Student{
private String researchTopic;
public Graduate(String firstName, String lastName, int studentId, String researchTopic) {
super(firstName, lastName, studentId); // Properly include the studentId in the superclass constructor.
this.researchTopic = researchTopic;
}
public String getResearchTopic() {
return researchTopic;
}
public void setResearchTopic(String researchTopic) {
if (researchTopic == null || researchTopic.isEmpty()) {
throw new IllegalArgumentException("Research topic cannot be empty.");
}
this.researchTopic = researchTopic;
}
public String toString() {
return super.toString() + " | Research Topic: " + getResearchTopic();
}
}
| drewjordan414/Comp-271-Capstone | Ramiz/Graduate.java | 162 | // Properly include the studentId in the superclass constructor. | line_comment | en | false | 152 | 12 | 162 | 13 | 177 | 12 | 162 | 13 | 212 | 14 | false | false | false | false | false | true |
200516_7 | import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
/**
* A class that represents a drawer of a rectangle shape.
* This class extends the Drawer class.
* This class is used to create a rectangle shape on the drawing area.
*/
public class RectangleDrawer extends Drawer {
private Rectangle rectangle = null; // The rectangle that is being drawn.
private double initialX; // The x-coordinate of the initial/starting point.
private double initialY; // The y-coordinate of the initial/starting point.
/**
* Constructor of the RectangleDrawer class.
* With the given drawing area, the constructor initializes the drawing area.
* @param pane The drawing area.
*/
public RectangleDrawer(Pane pane) {
super(pane);
}
/**
* Start drawing a rectangle when the mouse is pressed.
* @param e The mouse event.
*/
@Override
public void startDrawing(MouseEvent e) {
if(e.getButton() == MouseButton.PRIMARY) {
initialX = e.getX(); // Get the coordinates of the mouse as the initial point.
initialY = e.getY();
rectangle = new MyRectangle();
rectangle.setX(initialX); // Set the x-coordinate of the rectangle.
rectangle.setY(initialY); // Set the y-coordinate of the rectangle.
pane.getChildren().add(rectangle); // Add the rectangle to the drawing area.
}
}
/**
* Continue drawing a rectangle when the mouse is dragged.
* @param e The mouse event.
*/
@Override
public void continueDrawing(MouseEvent e) {
rectangle.setWidth(Math.abs(e.getX() - initialX)); // Change the width and height of the rectangle based on the mouse movement.
rectangle.setHeight(Math.abs(e.getY() - initialY));
rectangle.setX(Math.min(e.getX(), initialX)); // Change the position of first corner of the rectangle based on the mouse movement.
rectangle.setY(Math.min(e.getY(), initialY)); // To prevent negative width and height.
rectangle.setStroke(Color.BLACK); // Set the stroke color of the rectangle.
}
/**
* Stop drawing a rectangle when the mouse is released.
* @param e The mouse event.
*/
@Override
public void stopDrawing(MouseEvent e) {
rectangle = null;
}
}
| Dominik-Galus/Figures_DrawingApp | RectangleDrawer.java | 571 | // Set the x-coordinate of the rectangle. | line_comment | en | false | 502 | 9 | 571 | 10 | 612 | 10 | 571 | 10 | 661 | 10 | false | false | false | false | false | true |
202124_1 | package Ramps;
public abstract class Ramp implements IRamp {
private RampState rampStateWhenDriving;
private int rampAngle;
private final int MAX_ANGLE;
private final int MIN_ANGLE;
private RampState rampState;
Ramp(int MAX_ANGLE, RampState rampStateWhenDriving) {
this.MAX_ANGLE = MAX_ANGLE;
this.MIN_ANGLE = 0;
this.rampAngle = 0;
this.rampStateWhenDriving = rampStateWhenDriving;
this.rampState = rampStateWhenDriving;
}
private void setRampState(RampState newRampState){
rampState = newRampState;
}
private RampState getRampState() {
return rampState;
}
public int getMaxAngle() {
return this.MAX_ANGLE;
}
public int getMinAngle() {
return this.MIN_ANGLE;
}
public int getRampAngle() {
return rampAngle;
}
private void setRampAngle(int newAngle) {
rampAngle = newAngle;
}
// raise ramp from current position, can only between [0-70].
public void raiseRamp(int degrees) {
ensureDegreesIsValidRange(degrees);
int newAngle = getRampAngle() + degrees;
if (0 < degrees && newAngle <= MAX_ANGLE) {
setRampAngle(newAngle);
setRampState(RampState.UP);
} else if(newAngle > MAX_ANGLE) {
raiseRampToMax();
}
}
// lower ramp from current position, can only between [0-70].
public void lowerRamp(int degrees) {
ensureDegreesIsValidRange(degrees);
int newAngle = getRampAngle() - degrees;
if (MIN_ANGLE < degrees && newAngle >= MIN_ANGLE) {
setRampAngle(newAngle);
} else if (newAngle < MIN_ANGLE) {
lowerRampToMin();
}
if (getRampAngle() == MIN_ANGLE) {
setRampState(RampState.DOWN);
}
}
public void raiseRampToMax() {
rampAngle = MAX_ANGLE;
setRampState(RampState.UP);
}
public void lowerRampToMin() {
rampAngle = MIN_ANGLE;
setRampState(RampState.DOWN);
}
private void ensureDegreesIsValidRange(int degrees) {
if (degrees < MIN_ANGLE || degrees > MAX_ANGLE) {
throw new IllegalArgumentException("Degrees must be in the interval [0-maxAngle]");
}
}
public boolean rampIsInDrivingPosition() {
getRampState();
if (getRampState() == rampStateWhenDriving){
return true;
} else {
return false;
}
}
} | linuskar/TDA553-lab3 | src/Ramps/Ramp.java | 666 | // lower ramp from current position, can only between [0-70]. | line_comment | en | false | 596 | 16 | 666 | 17 | 685 | 16 | 666 | 17 | 818 | 17 | false | false | false | false | false | true |
204220_1 | /*
* Copyright 2008-2010 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.btrace.samples;
import com.sun.btrace.annotations.*;
import static com.sun.btrace.BTraceUtils.*;
/**
* This BTrace program demonstrates command line
* arguments. $ method helps in getting command line
* arguments. In this example, desired thread name is
* passed from the command line (of the BTrace client).
*/
@BTrace public class CommandArg {
@OnMethod(
clazz="java.lang.Thread",
method="run"
)
public static void started() {
if (Strings.strcmp(Threads.name(Threads.currentThread()), Sys.$(2)) == 0) {
println(Strings.strcat("started ", Sys.$(2)));
}
}
}
| xxzmxx/btrace_extend | samples/CommandArg.java | 487 | /**
* This BTrace program demonstrates command line
* arguments. $ method helps in getting command line
* arguments. In this example, desired thread name is
* passed from the command line (of the BTrace client).
*/ | block_comment | en | false | 437 | 47 | 487 | 49 | 485 | 49 | 487 | 49 | 554 | 50 | false | false | false | false | false | true |
204388_0 | import java.awt.geom.Point2D;
import java.util.Iterator;
/**
* An interface for a collection of points in two dimensions that can
* be searched by coordinates.
*
* @author Jim Teresco
* @version Spring 2022
*/
public interface PointSet2D<E extends Point2D.Double> extends Iterable<E> {
/**
* Add a new object to the collection.
*
* @param point the new object to be added
*/
public void add(E point);
/**
* Get the object at the same coordinates at the given point. If multiple
* objects with the same coordinates have been added to the structure,
* one of them will be returned, but there is no guarantee made about
* which one.
*
* @param point a point with the coordinates being sought
* @return an object at the same coordinates as point, null if no
* such object is in the collection
*/
public E get(Point2D.Double point);
/**
* Remove an object at the same coordinates at the given point. If multiple
* objects with the same coordinates have been added to the structure,
* one of them will be removed and returned, but there is no guarantee made about
* which one.
*
* @param point a point with the coordinates at which an item to be removed
* is located
* @return an the object removed, null if no object at the coordinates
* of point is in the collection
*/
public E remove(Point2D.Double point);
/**
* Return the number of points in the collection.
*
* @return the number of points in the collection
*/
public int size();
}
| SienaCSISAdvancedProgramming/PointSet2D | PointSet2D.java | 386 | /**
* An interface for a collection of points in two dimensions that can
* be searched by coordinates.
*
* @author Jim Teresco
* @version Spring 2022
*/ | block_comment | en | false | 379 | 41 | 386 | 44 | 422 | 44 | 386 | 44 | 431 | 45 | false | false | false | false | false | true |
208161_7 | import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;
/**
* Database Class
*
* @author Matt
*
*/
public class Database implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private static final String strSavePath = System.getProperty("user.dir");
private static final String strMemberSavePath = isWindows() ? strSavePath
+ "\\member.sav" : strSavePath + "/member.sav";
private static final String strProviderSavePath = isWindows() ? strSavePath
+ "\\provider.sav" : strSavePath + "/provider.sav";
private static final String strRecordSavePath = isWindows() ? strSavePath
+ "\\record.sav" : strSavePath + "/record.sav";
// // hashed on member number
static Map<Integer, Member> members = new HashMap<Integer, Member>();
// Hashed on provider number
static Map<Integer, Provider> providers = new HashMap<Integer, Provider>();
// Hashed on provider number
static Map<Integer, Record> providerBillRecords = new HashMap<Integer, Record>();
/**
* Database loads members, providers, and the provider's bill records
*/
public Database() {
// System.out.println(strMemberSavePath);
members = loadMembers();
providers = loadProviders();
providerBillRecords = loadProviderBillRecords();
}
/**
*
* @param person
* This method adds a member to the hashmap members
*/
public void addMember(Member person) {
members.put(person.getNumber(), person);
}
/**
*
* @param person
* This method removes a member from the hashmap members
*/
public void removeMember(Member person) {
members.remove(person.getNumber());
}
public void removeMember(int memberNumber) {
// comment test
members.remove(memberNumber);
}
/**
*
* @param person
* adds provider to system with provider number
*/
public void addProvider(Provider person) {
providers.put(person.getNumber(), person);
}
/**
*
* @param person
* removes provider from system based on provider number
*/
public void removeProvider(Provider person) {
providers.remove(person.getNumber());
}
public void removeProvider(int providerNumber) {
providers.remove(providerNumber);
}
/**
*
* @param report
* adds billing records from provider based on provider number
*/
public void addProviderBillRecord(Record report) {
providerBillRecords.put(report.providerNumber, report);
}
/**
*
* @param report
* removes bill records based on provider number
*/
public void removeBillRecord(Record report) {
providerBillRecords.remove(report.providerNumber);
}
/**
* This method takes in a member ID number, and returns the member object
*
* @param memberId
* @return the member ID that was retrieved
*/
public Member getMember(int memberId) {
return members.get(memberId);
}
/**
*
* @param serviceCode
* uses service code provided to check against listed service
* codes
* @return if service code matches, returns the provided service name
*/
public String getServiceName(int serviceCode) {
if (serviceCode == 666665) {
return "Diet Consultation";
} else if (serviceCode == 451956) {
return "Excercise Session";
} else if (serviceCode == 102865) {
return "Massage Session";
} else if (serviceCode == 551947) {
return "Weight-loss Crying Session";
} else if (serviceCode == 800085) {
return "Yoga Session";
}
return "Incorrect Code";
}
/**
* This method takes in a provider number, and returns a Provider object
*
* @param providerNumber
* @return the selected provider object
*/
public Provider getProvider(int providerNumber) {
return providers.get(providerNumber);
}
/**
* @param providerNumber
* uses supplied provider number to look up bill records
* @return returns bill records based on the provider number supplied
*/
public Record getProviderBillRecord(int providerNumber) {
return providerBillRecords.get(providerNumber);
}
/**
* This method saves the members, providers, and provider bill records to
* the database
*/
public void saveDb() {
saveMembers();
saveProviderRecords();
saveProviders();
}
/**
* This method saves the members to the database
*/
private void saveMembers() {
saveObject(strMemberSavePath, members);
}
/**
* This method loads members in database
*
* @return a hashmap of members
*/
private Map<Integer, Member> loadMembers() {
Map<Integer, Member> members = (Map<Integer, Member>) loadObject(strMemberSavePath);
if (members == null) {
return new HashMap<Integer, Member>();
}
return members;
}
/**
* This method saves providers to database
*/
private void saveProviders() {
saveObject(strProviderSavePath, providers);
}
/**
* This method loads providers in database
*
* @return a hashmap of providers
*/
private Map<Integer, Provider> loadProviders() {
Map<Integer, Provider> providers = (Map<Integer, Provider>) loadObject(strProviderSavePath);
if (providers == null) {
return new HashMap<Integer, Provider>();
}
return providers;
}
/**
* This method saves provider records to database
*/
private void saveProviderRecords() {
saveObject(strRecordSavePath, providerBillRecords);
}
/**
* This method loads bill records for provider services
*
* @return a hashmap of provider bill records
*/
private Map<Integer, Record> loadProviderBillRecords() {
Map<Integer, Record> providerBillRecords = (Map<Integer, Record>) loadObject(strRecordSavePath);
if (providerBillRecords == null) {
return new HashMap<Integer, Record>();
}
return providerBillRecords;
}
/**
* This method determines where to save object provided to save to path
*
* @param path
* @param toSave
*/
private void saveObject(String path, Object toSave) {
try {
FileOutputStream stream = new FileOutputStream(path);
ObjectOutputStream objectStream = new ObjectOutputStream(stream);
objectStream.writeObject(toSave);
objectStream.close();
stream.close();
} catch (IOException e) {
System.out
.println("The database could not be found. Are you running the program from the correct location?");
}
}
/**
* @param path
* determines where to load object from
* @return returns object loaded from path, If no path, returns nothing
*/
private static Object loadObject(String path) {
try {
FileInputStream stream = new FileInputStream(path);
ObjectInputStream objectStream = new ObjectInputStream(stream);
Object obj = objectStream.readObject();
objectStream.close();
stream.close();
return obj;
} catch (IOException | ClassNotFoundException e) {
System.out
.println("Could not load database. Are you running the program from the correct location?");
}
return null;
}
/**
* This method determines is the user is using windows or no
*
* @return true if operating system is windows, false otherwise
*/
private static boolean isWindows() {
return System.getProperty("os.name").toLowerCase().indexOf("win") > -1;
}
}
| jmbeach/cs315 | src/Database.java | 1,931 | /**
*
* @param person
* This method removes a member from the hashmap members
*/ | block_comment | en | false | 1,713 | 25 | 1,931 | 23 | 2,019 | 28 | 1,931 | 23 | 2,273 | 28 | false | false | false | false | false | true |
208944_0 | import java.util.*;
interface AdvancedArithmetic{
int divisor_sum(int n);
}
class MyCalculator implements AdvancedArithmetic{
int sum = 0;
public int divisor_sum(int n){
for(int i=1;i<=(n+1)/2;i++){
if(n%i==0){
sum+=i;
}
}
if(n==1){
return 1;
}
return (sum+n);
}
}
class Solution{
public static void main(String []args){
MyCalculator my_calculator = new MyCalculator();
System.out.print("I implemented: ");
ImplementedInterfaceNames(my_calculator);
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.print(my_calculator.divisor_sum(n) + "\n");
sc.close();
}
/*
* ImplementedInterfaceNames method takes an object and prints the name of the interfaces it implemented
*/
static void ImplementedInterfaceNames(Object o){
Class[] theInterfaces = o.getClass().getInterfaces();
for (int i = 0; i < theInterfaces.length; i++){
String interfaceName = theInterfaces[i].getName();
System.out.println(interfaceName);
}
}
}
// Keep Growing
| StarKnightt/Hacker-Rank-Questions | Java Interface.java | 302 | /*
* ImplementedInterfaceNames method takes an object and prints the name of the interfaces it implemented
*/ | block_comment | en | false | 260 | 23 | 302 | 22 | 330 | 24 | 302 | 22 | 359 | 26 | false | false | false | false | false | true |
209683_16 | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package jack.auctions;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import jack.server.ClientHandler;
import jack.scheduler.Task;
/**
* The auction class is the base class for all auction implementations. It it
* responsible for running the auction and handles the serialization and
* deserialization of all messages to and from the clients. Subclasses should
* define MessageHandlers for each message type that they wish to respond to.
* When that message type is recieved by this class it will forward the message
* to the appropriate handler. In addition, auction implementations can override
* their choice of functions below to gain even more control over their
* interactions with the clients.
*/
public abstract class Auction extends Task
{
/* Message keys required by this auction*/
protected final String SESSION_KEY = "sessionId";
protected final String AUCTION_KEY = "auctionId";
/** The parameters used to initialize this auction */
protected Map<String, String> params = new HashMap<String, String>();
/** A collection of sockets for client communication */
protected Vector<ClientHandler> clients;
/** The minium time to wait before idle function calls in ms */
private static final long IDLE_TIMEOUT = 50;
/** A queue of messages to handle */
private final BlockingQueue<String> messages;
/** A map of message handlers */
private final Map<String, MessageHandler> handlers;
/** Logger for writing log messages */
protected final Logger LOGGER = Logger.getLogger(Auction.class.getName());
/**
* Constructs an auction with the specified identification.
* @param auctionId The unique identified of this auction
*/
public Auction(int auctionId) {
super(auctionId);
messages = new LinkedBlockingQueue<String>();
handlers = new HashMap<String, MessageHandler>();
}
/**
* Returns this auctions unique identification. This is the same as the task
* identifier.
* @return The auction identifier
*/
public final int getAuctionId() {
return getTaskId();
}
/**
* Sets the client handlers to use for all auction communication. When the
* auction is started, it will register itself with these clients, and when
* the auction is ended, it will unregister itself with these clients.
* @param newClients The new set of client handlers
*/
public final void setClients(Vector<ClientHandler> newClients) {
clients = newClients;
}
/**
* Adds the message to the end of the message queue. This function should be
* called whenever a new message arrives for this auction. The message
* queue is drained and each message is passed to its corresponding handler
* when the auction is in STATE_RUNNING or STATE_ENDABLE. This function is
* thread safe, but it is not synchronized on the same lock as the auctions
* state.
* @param message Message to be handled by this auction
*/
public void queueMessage(String message) {
try {
messages.put(message);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
/**
* This function sets the specified auction parameters. Subclasses should
* override this function to receive configuration parameters. These
* parameters are read from the configuration xml file and passed to each
* auction by the AuctionFactory.
* @param newParams A map of configuration parameters.
*/
public void setParams(Map<String, String> newParams) {
params = new HashMap<String, String>(newParams);
}
/**
* This function sends the auction specification to each of the clients. The
* auction specification consists of the "auction" tag followed by all of
* the parameters used to initialize the auction. Subclasses should override
* this function to only send the information that they want.
*/
public void sendSpec() {
sendMessage("auction", params);
}
/**
* This function runs the auction. All auctions at their most basic level
* can be represented as a series of messages passed between the auctions
* and thir bidders. This function tries to take care of most of the leg
* work of receiving messages. It drains the message queue and passes each
* message to its registered handler. When their are no messages to drain it
* calls the idle function in which a subclass can do whatever they would
* like.
*/
@Override
public void run() {
// If this auction has already been run then it cannot be run again.
// This restriction could be relaxed in the future, but for the moment
// it seems like the safest behavior.
if (getState() != STATE_NEW) {
return;
}
// Initialize the auction. This involes setting the state to be
// STATE_RUNNING, registering the auction with the ComThreads so that
// they can receive messages from the bidders, and calling the auction
// specific initialization routine.
setState(STATE_RUNNING);
register();
initialize();
try {
// Begin processing messages. As long as the curretn state of the
// auction is not state ending we will continue to process messages.
// This includes STATE_ENDABLE, where an auction can still receive
// messages, but may be ended at any time.
while (getState() < STATE_ENDING) {
// Get the message off the top of the queue. If there is no
// message then idle and try again.
String message = messages.poll(IDLE_TIMEOUT,
TimeUnit.MILLISECONDS);
if (message == null) {
idle();
continue;
}
// Split the message by whitespace. Here we expect an auction
// message starts with the type and is followed by an
// unspecified number of key=value pairs:
// "messageType key1=value1 ... keyN=valueN"
// Messages that do not fit this format will either not be
// processed or processed incorrectly.
String[] keyVals = message.split("\\s+");
if (keyVals.length > 0) {
// Parse the message type and the arguments
String messageType = keyVals[0];
Map<String, String> args =
toMap(Arrays.copyOfRange(keyVals, 1, keyVals.length));
// Check if this message was intended for this auction
if (!args.containsKey(SESSION_KEY)) {
LOGGER.warning("Invalid message: no " + SESSION_KEY);
continue;
}
if (!args.containsKey(AUCTION_KEY)) {
LOGGER.warning("Invalid message: no " + AUCTION_KEY);
continue;
}
// Silently ignore messages meant for other auctions
int sessionId = Integer.parseInt(args.get(SESSION_KEY));
int auctionId = Integer.parseInt(args.get(AUCTION_KEY));
if (sessionId != getSessionId() || auctionId != getAuctionId()) {
continue;
}
// Pass the message to the appropriate handler and
// ignore any unknown messages.
MessageHandler handler = handlers.get(messageType);
if (handler != null) {
try {
handler.handle(args);
} catch (IllegalArgumentException e) {
LOGGER.warning(e.toString());
}
} else {
LOGGER.warning("Unknown message type: " + messageType);
}
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
// Finally resolve the message, unregister this auction from the
// ClientHandlers and set the state to be ended.
resolve();
unregister();
// TODO: This is currently an unfortunate hack which is necessary
// because of the multithreaded nature of the scheduler. As soon as
// we set the state to ended then the scheduler will try to launch
// additional auctions in their own threads. If any auction
// implementations decided to send a message to their clients in the
// resolve function (which most will) then there is a chance that
// clients will not receive this message until the after the next
// auction starts. This is clearly undesirable behavior for clients
// which want to know the results of the previous auction before moving
// onto the next.
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
setState(STATE_ENDED);
}
/**
* Called Immediately before the auction begins. Subclasses should override
* this method to setup their own initialization routines and send any
* pertinant information to the bidders.
*/
protected void initialize() {}
/**
* Called whenever there are no messages to process. Subclasses should
* override this method if they want to perform actions that are not
* triggered by client messages, such as timed events.
*/
protected void idle() throws InterruptedException {}
/**
* Called immediately after the auction ends. Subclasses should override
* this method to setup their own resolution routines. This generally
* includes informing the bidders of the winner.
*/
protected void resolve() {}
/**
* Adds the specified handler to the handler map. If a handler has already
* been specified for the given message type then this call will replace
* that handler.
* @param type The message type that this handler should be called on.
* @param handler The handler responsible for handling this message type.
*/
protected final void putHandler(String type, MessageHandler handler) {
handlers.put(type, handler);
}
/**
* Sends a message of the specifed type with the specifeid parameters to
* each of the clients. In addition to the arguments passed into this
* function, the sessionId and auctionId will be automatically appended.
* @param type The message type that is being sent
* @param args A key value map of arguments to pass with that message
*/
protected final void sendMessage(String type, Map<String, String> args) {
args.put(SESSION_KEY, Integer.toString(getSessionId()));
args.put(AUCTION_KEY, Integer.toString(getAuctionId()));
String message = type + toString(args);
for (ClientHandler client : clients) {
client.sendMessage(message);
}
}
/**
* This function registers this auction with all of its clients. Once
* registered this auction will receive message from these clients, which
* will be palced in the message queue and passed to their corresponding
* handlers.
*/
private final void register() {
for (ClientHandler client : clients) {
client.register(this);
}
}
/**
* This function unregisters this auction with all of its clients. After
* unregistering this auction no no longer be able to receive messages from
* its clients.
*/
private final void unregister() {
for (ClientHandler client : clients) {
client.unregister(this);
}
}
/**
* Constructs a map from an array of key value strings. Each string in the
* array should be of the form "key=value". Extra whitespace on either end
* of the key or value will be trimmed. Any non conformant strings will be
* silently ignored.
* @param keyVals An array of strings of the form "key=value"
* @return A map of values indexed by their corresponding keys
*/
private static final Map<String, String> toMap(String[] keyVals) {
Map<String, String> m = new HashMap<String, String>();
for (String keyVal : keyVals) {
String[] pair = keyVal.split("=");
if (pair.length == 2) {
m.put(pair[0].trim(), pair[1].trim());
}
}
return m;
}
/**
* Constructs a key value string from a map of strings. Each key value pair
* in the result will be of the form "key=value" seperated from ech other by
* whitespace.
* @param map A map of key value pairs
* @return A string of key value pairs
*/
public static final String toString(Map<String, String> keyVals) {
String s = new String();
for (Map.Entry<String, String> entry : keyVals.entrySet()) {
s += " " + entry.getKey() + "=" + entry.getValue().replace(' ', '_');
}
return s;
}
/**
* The MessageHandler interface provides an abstraction between the
* deserialization of messages coming over the wire and the auctions that
* wish to handle them. Subclasses of Auction should create handlers for
* each message type they wish to handle, and then register that handler
* with this class.
*/
protected interface MessageHandler {
public void handle(Map<String, String> args)
throws IllegalArgumentException;
}
}
| BrownGLAMOR/JACK | src/jack/auctions/Auction.java | 3,011 | // If this auction has already been run then it cannot be run again. | line_comment | en | false | 2,895 | 15 | 3,011 | 15 | 3,256 | 15 | 3,011 | 15 | 3,624 | 16 | false | false | false | false | false | true |
211131_34 | /**
*<BR> Name: Kush Patel
*<BR> Date: 2-22-2022
*<BR> Period: 2
*<BR> Assignment: ICY Lesson 17, 18, 25, 26
*<BR> Description: We will be ciounting the steps for each sort
*<BR> Cite Sources: Mr.Elliot explained where we had to count steps
*<BR> Sort Code by: Jason Quesenberry, Nancy Quesenberry, Mr. Eliot
*/
import java.util.ArrayList;
public class Sorts
{
private long steps; //long integer up to 9,223,372,036,854,775,807
public Sorts()
{
steps = 0;
}
public void bubbleSort(ArrayList <Integer> List)
{
int outer;
int inner;
Integer Temp;
for (outer = 0; outer < List.size() - 1; outer++)
{
for (inner = 0; inner < List.size() - outer - 1; inner++)
{
steps += 3; // counts two .get(), one .compareTo()
if (List.get(inner).compareTo(List.get(inner + 1)) > 0)
{
//swap
steps += 4; //counted two .set() methods and two .get() methods
Temp = List.get(inner);
List.set(inner, List.get(inner + 1));
List.set(inner + 1, Temp);
}
}
}
}
public void selectionSort(ArrayList <Integer> List)
{
int outer;
int inner;
int min;
Integer Temp;
for (outer = 0; outer < List.size() - 1; outer++)
{
min = outer;
for (inner = outer + 1; inner < List.size(); inner++)
{
steps += 3; // counts two .get(), one .compareTo()
if (List.get(inner).compareTo(List.get(min)) < 0)
{
min = inner; // a new smallest item is found
}
}
//swap
steps += 4; //counted two .set() methods and two .get() methods
Temp = List.get(outer);
List.set(outer, List.get(min));
List.set(min, Temp);
}
}
public void insertionSort(ArrayList <Integer> List)
{
int outer;
int inner;
int position;
Integer key;
for (outer = 1; outer < List.size(); outer++)
{
position = outer;
steps += 1; //counted one .get() methods
key = List.get(position);
steps += 2; //counted one .get() and one .compareTo() methods if while loop condition is false
while (position > 0 && List.get(position - 1).compareTo(key) > 0)
{
steps += 2; //counted one .get() and one .compareTo() methods if while loop condition is true
steps += 2; //counted one .set() and one .get() methods
List.set(position, List.get(position - 1));
position--;
}
steps += 1; //counted one .set() methods
List.set(position, key);
}
}
private void merge(ArrayList <Integer> List, int first, int mid, int last)
{
int PositionA = first;
int PositionB = mid + 1;
int PositionTemp = first;
int total = last - first + 1;
int loop;
boolean doneA = false;
boolean doneB = false;
//Use Copy Constructor to make "Temp" a **COPY** of "List"
ArrayList<Integer> Temp = new ArrayList<Integer>(List);
//merge two sub-arrays together into Temp array
for (loop = 1; loop <= total; loop++)
{
if (doneA)
{
steps += 2; //counted one .set() and one .get() methods
Temp.set(PositionTemp, List.get(PositionB));
PositionB++;
}
else if (doneB)
{
steps += 2; //counted one .set() and one .get() methods
Temp.set(PositionTemp, List.get(PositionA));
PositionA++;
}
else if (List.get(PositionA).compareTo(List.get(PositionB)) < 0)
{
steps += 3; //counted two .get() and one .compareTo() methods if if conditional true
steps += 2; //counted one .get() and one .set() methods
Temp.set(PositionTemp, List.get(PositionA));
PositionA++;
}
else //List[PositionA] >= List[PositionB]
{
steps += 3; //counted two .get() and one .compareTo() methods if else if conditional is false
steps += 2; //counted one .get() and one .set() methods
Temp.set(PositionTemp, List.get(PositionB));
PositionB++;
}
PositionTemp++;
if (PositionA > mid)
{
doneA = true;
}
if (PositionB > last)
{
doneB = true;
}
}
// copy Temporary array into original array
for (loop = first; loop <= last; loop++)
{
steps += 2; //counted one .get() and one .set() methods
List.set(loop, Temp.get(loop));
}
}
public void mergeSort(ArrayList <Integer> List, int first, int last)
{
int mid;
int Temp;
if (first == last)
{
// 1 value, do nothing
}
else
{
if (first + 1 == last)
{
// 2 values, swap if necessary
steps += 3; //counted two .get() and one .compareTo() methods when the if statement is false
if (List.get(first).compareTo(List.get(last)) > 0)
{
steps += 3; //counted two .get() and one .compareTo() methods when the if statement is true
swap(List, first, last); //**SWAP METHOD**
}
}
else
{
// more than 2 values, split List again
mid = (first + last) / 2;
mergeSort(List, first, mid);
mergeSort(List, mid + 1, last);
merge(List, first, mid, last);
}
}
}
public void quickSort (ArrayList <Integer> List, int first, int last)
{
int g = first, h = last;
int midIndex = (first + last) / 2;
steps += 1; //counted one .get() method
Integer dividingValue = List.get(midIndex);
do
{
steps += 2; //counted one .get() and one .compareTo() methods if loop condition is false
while (List.get(g).compareTo(dividingValue) < 0)
{
steps += 2; //counted one .get() and one .compareTo() methods if loop conditon is true
g++;
}
steps += 2; //counted one .get() and one .compareTo() methods if loop condition is false
while (List.get(h).compareTo(dividingValue) > 0)
{
steps += 2; //counted one .get() and one .compareTo() methods if loop conditon is true
h--;
}
if (g <= h)
{
//swap(List[g], List[h]);
swap(List, g, h); //**SWAP METHOD**
g++;
h--;
}
}
while (g < h);
if (h > first)
{
quickSort (List, first, h);
}
if (g < last)
{
quickSort (List, g, last);
}
}
public long getStepCount()
{
return steps;
}
public void setStepCount(long stepCount)
{
steps = stepCount;
}
private void swap(ArrayList <Integer> List, int a, int b)
{
Integer Temp;
steps += 4; //counted two .get() and two .set() methods
Temp = List.get(a);
List.set(a, List.get(b));
List.set(b, Temp);
}
} | kushpatelj86/Kush-Patel-Coding-History-2021-2023 | Sorts.java | 2,187 | //counted one .get() and one .compareTo() methods if loop condition is false
| line_comment | en | false | 1,996 | 19 | 2,187 | 19 | 2,257 | 18 | 2,187 | 19 | 2,729 | 20 | false | false | false | false | false | true |
211297_1 | // @author Alson(Group 12H)
import java.util.Scanner;
/**
* This class implements a shop simulation.
*
* @author Wei Tsang
* @version CS2030S AY21/22 Semester 2
*/
class ShopSimulation extends Simulation {
/**
* The availability of counters in the shop.
*/
public boolean[] available;
/**
* The list of customer arrival events to populate
* the simulation with.
*/
public Event[] initEvents;
/**
* Constructor for a shop simulation.
*
* @param sc A scanner to read the parameters from. The first
* integer scanned is the number of customers; followed
* by the number of service counters. Next is a
* sequence of (arrival time, service time) pair, each
* pair represents a customer.
*/
public ShopSimulation(Scanner sc) {
initEvents = new Event[sc.nextInt()];
int numOfCounters = sc.nextInt();
int numOfQueue = sc.nextInt();
Shop shop = new Shop(numOfCounters, numOfQueue);
int id = 0;
Customer customer;
while (sc.hasNextDouble()) {
double arrivalTime = sc.nextDouble();
double serviceTime = sc.nextDouble();
customer = new Customer(id, serviceTime);
initEvents[id] = new Arrival(customer,
arrivalTime, shop);
id += 1;
}
}
/**
* Retrieve an array of events to populate the
* simulator with.
*
* @return An array of events for the simulator.
*/
@Override
public Event[] getInitialEvents() {
return initEvents;
}
}
| alson001/CS2030s | lab2-alson001-master/ShopSimulation.java | 390 | /**
* This class implements a shop simulation.
*
* @author Wei Tsang
* @version CS2030S AY21/22 Semester 2
*/ | block_comment | en | false | 374 | 38 | 390 | 43 | 431 | 40 | 390 | 43 | 474 | 42 | false | false | false | false | false | true |
211639_5 | /*===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
*/
package ngs;
/**
* Represents a slice through a stack of Alignments at a given position on the Reference
*/
public interface Pileup
extends PileupEventIterator
{
/*----------------------------------------------------------------------
* Reference
*/
/**
* getReferenceSpec
* @return name of the Reference
* @throws ErrorMsg upon an error accessing data
*/
String getReferenceSpec ()
throws ErrorMsg;
/**
* getReferencePosition
* @return current position on the Reference
* @throws ErrorMsg upon an error accessing data
*/
long getReferencePosition ()
throws ErrorMsg;
/**
* @return base at current Reference position
* @throws ErrorMsg upon an error accessing data
*/
char getReferenceBase ()
throws ErrorMsg;
/*----------------------------------------------------------------------
* details of this pileup row
*/
/**
* getPileupDepth
* @return the coverage depth at the current reference position
* @throws ErrorMsg upon an error accessing data
*/
int getPileupDepth ()
throws ErrorMsg;
}
| seandavi/ngs-1 | ngs-java/ngs/Pileup.java | 499 | /**
* @return base at current Reference position
* @throws ErrorMsg upon an error accessing data
*/ | block_comment | en | false | 470 | 25 | 499 | 23 | 532 | 26 | 499 | 23 | 579 | 27 | false | false | false | false | false | true |
212507_2 | package classes;
public class Helipad {
public Coordinates coordinates;
public String designation, radius, radiusUnit;
public String surface, id, type;
public static int idCount = 1;
public static int getNextId(){
return idCount++;
}
public Helipad(){
designation = "XXXXXXX";
coordinates = new Coordinates();
surface="XXXXXXX";
radius = "XXXXX";
radiusUnit = "Meter";
id = "h"+String.valueOf(Helipad.getNextId());
}
public String toSDL(String offset){
String msg =
offset+"<helipad id=\""+ id +"\" >\n"+
coordinates.toSDL(offset+" ")+
offset+" <designation>"+designation+"</designation>\n"+
offset+" <surface>"+surface+"</surface>\n"+
offset+" <radius lengthUnit=\""+this.radiusUnit+"\">"+radius+"</radius>\n"+
offset+"</helipad>\n";
return msg;
}
public Coordinates getCoordinates() {
return coordinates;
}
public void setCoordinates(Coordinates coordinates) {
this.coordinates = coordinates;
}
public String getSurface() {
return surface;
}
public void setSurface(String surface) {
String first = surface.substring(0, 1);
String rem = surface.substring(1, surface.length());
this.surface = first.toUpperCase()+rem.toLowerCase();
//Concrete, Grass, Water, Grass_bumpy, Asphalt, Short_grass, Long_grass, Hard_turf,
//Snow, Ice, Urban, Forest, Dirt, Coral, Gravel, Oil_treated, Steel_mats, Bituminus,
//Brick, Macadam, Planks, Sand, Shale, Tarmac, Wood, Cement
}
public String getRadius() {
return radius;
}
public void setRadius(String radius) {
this.radius = radius;
}
public String getRadiusUnit() {
return radiusUnit;
}
public void setRadiusUnit(String altU) {
switch(altU){
case "M": this.radiusUnit = "Meter"; break;
case "N": this.radiusUnit = "Nautical Mile"; break;
case "F": this.radiusUnit = "Foot"; break;
}
}
public void calculateRadius(String length) {
this.radius = ""+Double.parseDouble(length)/2.0;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
} | norim13/feup-comp-bgl2sdl | src/classes/Helipad.java | 702 | //Brick, Macadam, Planks, Sand, Shale, Tarmac, Wood, Cement
| line_comment | en | false | 580 | 22 | 702 | 24 | 733 | 21 | 702 | 24 | 867 | 25 | false | false | false | false | false | true |
213088_0 | package goosegame;
public class WaitingCell extends Cell{
int waitingTime;
int nbTours;
/**
*allows to know if the player on this cell can move or no
@return <code>true</code> if can move <code>false</code>else
*/
public boolean canBeLeft(){
if (this.nbTours==0){
return true ;
}
else{
this.nbTours--;
}
return false;
}
/**
*Constructor of WaitingCell
*@param index the index of the cell
*@param waitingTime the number of tours to wait to play
*/
public WaitingCell(int index,int waitingTime){
super(index);
this.waitingTime=waitingTime;
}
/**
*allows to add a player on the cell
*/
public void setPlayer(){
this.nbTours=this.waitingTime;
super.setPlayer(player);
}
}
| filaliyouva1/GooseGame | WaitingCell.java | 217 | /**
*allows to know if the player on this cell can move or no
@return <code>true</code> if can move <code>false</code>else
*/ | block_comment | en | false | 197 | 40 | 217 | 40 | 226 | 36 | 217 | 40 | 255 | 44 | false | false | false | false | false | true |
213219_7 | /*Player.java
* By: Malek Hammoud
* January 22, 2023
* This is the main Player class. Players are drawn and key input is taken in seperate file*/
import java.awt.*;
public class Player extends Rectangle{
int speed, startX, startY;
int gravity = 10;
boolean fall = true;
boolean jumping = false;
double timer;
int lifeCount = 3;
boolean movingRight = false;
boolean movingLeft= false;
Player(int startX, int startY, int speed, int width, int height){
this.speed =speed;
this.width = width;
this.height = height;
this.x = 10;
this.y = 10;
this.startX = startX;
this.startY = startY;
this.setup();
this.fall();
}
/*Move the player right*/
void moveRight() {
this.movingRight = true;
this.movingLeft = false;
this.x+=this.speed;
}
/*Move the player left */
void moveLeft() {
this.movingLeft= true;
this.movingRight= false;
this.x-=this.speed;
}
/*Move down, called automatically*/
void fall() {
if(this.jumping) {
this.y-=gravity;
}
else if(fall) {
this.y+=gravity;
}
}
/*Move player down faster*/
void jumpdown() {
this.jumping = false;
gravity +=1;
}
/**
* Detects wheather if landed on a platform
* @param platform
*/
void DetectPlatform(Platform platform) {
//if the player intersects with the top of the platform, stop falling
if (this.intersects(platform.getTop())) {
this.fall=false;
this.gravity = 10;
this.y = platform.getTop().y-this.height;
}else this.fall = true;
//if the player intersects with the bottom of the platform stop jumping
if (this.intersects(platform.getBottom())) {
this.fall=true;
this.jumping = false;
this.y = platform.getBottom().y+(platform.height);
}
//if the player intersects with the side of the a platform then stop moving
if(this.intersects(platform.getRight())) {
this.x += speed;
}
if(this.intersects(platform.getLeft())) {
this.x -= speed;
}
}
/**
* @return Top Rectangle
*/
Rectangle getTop() {
return new Rectangle(this.x, this.y, this.width, (int)this.height/2);
}
/**
* @return Bottom Rectangle
*/
Rectangle getBottom() {
return new Rectangle(this.x, this.y+(this.height/4)*3, this.width, (int)this.height/2);
}
int sidesWidth = 10;
int heightOffset = 10;
/**
* @return left Rectangle
*/
Rectangle getLeft() {
return new Rectangle(this.x-this.sidesWidth, this.y+heightOffset, sidesWidth, this.height-(heightOffset*2));
}
/**
* @return right Rectangle
*/
Rectangle getRight() {
return new Rectangle(this.x+this.width, this.y+heightOffset, sidesWidth, this.height-(heightOffset*2));
}
/**
* sets up values
*/
void setup() {
this.x = this.startX;
this.y = this.startY;
this.fall = true;
}
/**
* Checks if collided with oponent
* @param opponent object
*/
void getPlayerColide(Player opponent) {
//If the bottom of this player intersects with the top of another player reset everything and remove life from opponent
if (this.getBottom().intersects(opponent.getTop()) && !this.jumping) {
this.setup();
opponent.setup();
opponent.lifeCount -=1;
}
//if the player collides with another player then prevent from going through
if (this.getLeft().intersects(opponent.getRight()) && this.movingLeft) {
this.x = opponent.getRight().x+opponent.sidesWidth+this.sidesWidth-7;
}
if (this.getRight().intersects(opponent.getLeft()) && this.movingRight) {
this.x = opponent.getLeft().x-this.sidesWidth-this.width+7;
}
}
}
| mhammoud-os/JavaProject | Player.java | 1,167 | //if the player intersects with the bottom of the platform stop jumping | line_comment | en | false | 970 | 13 | 1,167 | 15 | 1,179 | 13 | 1,167 | 15 | 1,345 | 15 | false | false | false | false | false | true |
214414_19 | import java.util.HashMap;
/**
* This class represent the City
*/
public class City implements Comparable<City> {
// Store neighbors
private HashMap<String, Integer> neighbors;
// Store city name
private String name;
// Store discovered information
private boolean discovered;
// Store visited information
private boolean visited;
// Store temporary neighbors information for max flow
private HashMap<String, Integer> tempNeighbors;
/**
* constructor for initialize fields
* @param name city name
*/
public City(String name) {
neighbors = new HashMap<>();
tempNeighbors = new HashMap<>();
this.name = name;
}
/**
* getter method for neighbors
* @return neighbors
*/
public HashMap<String, Integer> getNeighbors() {
return neighbors;
}
/**
* setter method for neighbors
*/
public void setNeighbors(HashMap<String, Integer> neighbors) {
this.neighbors = neighbors;
}
/**
* getter method for name
* @return name
*/
public String getName() {
return name;
}
/**
* setter method for name
*/
public void setName(String name) {
this.name = name;
}
/**
* getter method for discovered
* @return discovered
*/
public boolean isDiscovered() {
return discovered;
}
/**
* setter method for discovered
*/
public void setDiscovered(boolean discovered) {
this.discovered = discovered;
}
/**
* getter method for visited
* @return visited
*/
public boolean isVisited() {
return visited;
}
/**
* setter method for visited
*/
public void setVisited(boolean visited) {
this.visited = visited;
}
/**
* getter method for tempNeighbors
* @return tempNeighbors
*/
public HashMap<String, Integer> getTempNeighbors() {
return tempNeighbors;
}
/**
* setter method for tempNeighbors
*/
public void setTempNeighbors(HashMap<String, Integer> tempNeighbors) {
this.tempNeighbors = tempNeighbors;
}
/**
* add neighbor to neighbors
*/
public void addNeighbour(String name, int capacity) {
neighbors.put(name, capacity);
addTempNeighbour(name,capacity);
}
/**
* add neighbor to tempNeighbors
*/
public void addTempNeighbour(String name, int capacity) {
tempNeighbors.put(name, capacity);
}
/**
* compare method for compare two city
* @param o other city
* @return compare using city name
*/
@Override
public int compareTo(City o) {
return name.compareTo(o.name);
}
/**
* for printing purpose
* @return city name
*/
public String toString() {
return name;
}
}
| mohamzamir/Traffic-Congestion-Modeling-Tool | src/City.java | 622 | /**
* compare method for compare two city
* @param o other city
* @return compare using city name
*/ | block_comment | en | false | 617 | 29 | 620 | 26 | 727 | 30 | 622 | 26 | 834 | 30 | false | false | false | false | false | true |
218702_0 | import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.xml.crypto.Data;
import java.awt.event.*;
import java.awt.*;
public class part2 {
public static TernarySearchTree STOP_NAMES_TST = new TernarySearchTree();
public static File STOPS;
public part2(String stopsPath) throws IOException {
STOPS = new File(stopsPath);
ArrayList<String> stopNames = getStopNames(STOPS);
insertStopNamesToTST(stopNames);
}
public static String[] getColumnNames(File filename) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(filename));
String st;
while ((st = br.readLine()) != null) {
String[] line = st.split(",");
br.close();
return line;
}
br.close();
return null;
}
public static String[] getColumnNamesFromStopTimes() throws IOException {
return getColumnNames(STOPS);
}
// In order for this to provide meaningful search functionality please move
// keywords flagstop, wb, nb, sb, eb from start of the names to the end of the
// names of the stops when reading the file into a TST (eg “WB HASTINGS ST FS
// HOLDOM AVE” becomes “HASTINGS ST FS HOLDOM AVE WB”)
public static String makeMeaningful(String stopName) {
int normalKeywordLength = 2;
int flagtstopLength = 8;
String temp = stopName.substring(0, normalKeywordLength).strip().toUpperCase();
String tempFlagStop = stopName.substring(0, flagtstopLength).strip().toUpperCase();
if (temp.equals("WB") || temp.equals("NB") || temp.equals("SB") || temp.equals("EB")) {
String lastPart = stopName.substring(normalKeywordLength + 1);
String firstPart = stopName.substring(0, normalKeywordLength);
String meaningfulStr = lastPart.concat(" ").concat(firstPart);
return makeMeaningful(meaningfulStr);
}
if (tempFlagStop.equals("FLAGSTOP")) {
String lastPart = stopName.substring(flagtstopLength + 1);
String firstPart = stopName.substring(0, flagtstopLength);
String meaningfulStr = lastPart.concat(" ").concat(firstPart);
return makeMeaningful(meaningfulStr);
} else
return stopName;
}
public static String removeSpacesAndCapitlize(String s) {
s.replace(" ", "");
return s.toUpperCase();
}
public static ArrayList<String> getStopNames(File filename) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(filename));
String st;
ArrayList<String> stopNames = new ArrayList<String>();
while ((st = br.readLine()) != null) {
String[] line = st.split(",");
if (!line[2].equals("stop_name")) {
String meaningfulName = makeMeaningful(line[2]);
stopNames.add(removeSpacesAndCapitlize(meaningfulName));
}
}
br.close();
return stopNames;
}
public static void printDuplicateStations(ArrayList<String> stopNames) {
ArrayList<String> stopNamesUniques = new ArrayList<String>();
int duplicateCount = 0;
System.out.println("------- Duplicate Stop Names -------");
for (String x : stopNames) {
if (stopNamesUniques.contains(x)) {
duplicateCount++;
System.out.println(duplicateCount + " " + x);
} else
stopNamesUniques.add(x);
}
System.out.println("Stops count - " + stopNames.size());
System.out.println("Unique Stops count - " + stopNamesUniques.size());
}
public static Map<String, ArrayList<String[]>> createNameDetailsMap(File filename) throws IOException {
int indexOfStopName = 2;
Map<String, ArrayList<String[]>> Time_Line = new HashMap<>();
BufferedReader br = new BufferedReader(new FileReader(filename));
String st;
while ((st = br.readLine()) != null) {
String[] line = st.split(",");
if (!line[indexOfStopName].equals("stop_name")) {
String meaningfulName = makeMeaningful(line[indexOfStopName]);
line[indexOfStopName] = meaningfulName;
Time_Line.computeIfAbsent(meaningfulName, k -> new ArrayList<>()).add(line);
// stopNames.add(meaningfulName);
}
}
br.close();
return Time_Line;
}
public static Map<String, ArrayList<String[]>> createNameDetailsMapFromStops() throws IOException {
return createNameDetailsMap(STOPS);
}
public static void insertStopNamesToTST(ArrayList<String> stopNames) {
for (String stopName : stopNames) {
STOP_NAMES_TST.insert(stopName);
}
}
public static void part2GUI() throws IOException {
String stops_path = "inputs/stops.txt";
File stops = new File(stops_path);
ArrayList<String> stopNames = getStopNames(stops);
// printDuplicateStations(stopNames);
insertStopNamesToTST(stopNames);
Map<String, ArrayList<String[]>> stopDetails = createNameDetailsMapFromStops();
JFrame f = new JFrame("PART 2 GUI");
String[] columnLabels = getColumnNames(stops);
String[][] tableData = new String[10][10];
DefaultTableModel dtm = new DefaultTableModel(tableData, columnLabels);
JTable table = new JTable(dtm);
JTableHeader header = table.getTableHeader();
String fg_color = "#ffffff";
String bg_color = "#000000";
header.setBackground(Color.decode(bg_color));
header.setForeground(Color.decode(fg_color));
table.setShowHorizontalLines(false);
table.setShowVerticalLines(true);
table.setGridColor(Color.decode(bg_color));
JScrollPane scrollPane = new JScrollPane(table);
// JScrollBar vScroll = scrollPane.getVerticalScrollBar();
table.setLayout(new BorderLayout());
int N_ROWS = tableData.length;
Dimension d = new Dimension(800, N_ROWS * table.getRowHeight());
table.setPreferredScrollableViewportSize(d);
TableColumn column = null;
// column = table.getColumnModel().getColumn(0);
// column.setPreferredWidth(columnLabels[0].length() * 10);
for (int i = 0; i < columnLabels.length; i++) {
column = table.getColumnModel().getColumn(i);
column.setPreferredWidth(columnLabels[i].length() * 10);
}
for (int i = 0; i < N_ROWS; i++) {
dtm.addRow(tableData[i]);
}
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(scrollPane, BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
final JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setVerticalAlignment(JLabel.CENTER);
// label.crossVerticalAlignment(JLabel.CENTER);s
// label.setBounds(300, -35, 100, 20);
label.setSize(table.getWidth(), table.getHeight() * 135 / 100);
// f.add(label,BorderLayout.CENTER);
final JLabel count_label = new JLabel();
// count_label.setBounds(250, -15, 100, 20);
count_label.setHorizontalAlignment(JLabel.CENTER);
count_label.setVerticalAlignment(JLabel.CENTER);
count_label.setSize(table.getWidth(), table.getHeight() * 160 / 100);
JTextField tf1 = new JTextField(20);
tf1.setBounds(425, 300, 150, 20);
JButton b = new JButton("Show");
b.setBounds(625, 300, 90, 20);
f.add(tf1);
f.add(b);
f.add(label);
f.add(count_label);
f.setLayout(null);
f.setSize(820, 600);
f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String input = tf1.getText();
Pattern p = Pattern.compile("[^a-z0-9\\- ]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(input);
boolean b = m.find();
if ((!input.equals("") && !input.equals(" ") && !input.substring(0, 2).equals(" ")) && !b) {
String displayData = "Input String - " + input;
System.out.println(displayData);
String searchInput = removeSpacesAndCapitlize(input);
String[] searchResults = STOP_NAMES_TST.search(searchInput);
if (searchResults == null) {
String errorMessage = "Sorry, There doesn't seem to be any buses at the time you have selected";
count_label.setHorizontalAlignment(JLabel.CENTER);
// count_label.alignCenter();
count_label.setText(errorMessage);
System.out.println(errorMessage);
// dtm.setDataVector(null, columnLabels);
String[][] emptyData = new String[10][columnLabels.length];
dtm.setDataVector(emptyData, columnLabels);
}
ArrayList<String[]> lines = new ArrayList<>();
for (String res : searchResults) {
ArrayList<String[]> details = stopDetails.get(res);
for (String[] d : details) {
lines.add(d);
}
}
// lines =
// printTripDetailsFromList(lines);
String[][] stopsData;
stopsData = new String[lines.size()][columnLabels.length];
for (int i = 0; i < stopsData.length; i++) {
stopsData[i] = lines.get(i);
}
int stopsCount = stopsData.length;
count_label.setText("There seem to be " + stopsCount + " matching bus stops");
dtm.setDataVector(stopsData, columnLabels);
} else
throw new IllegalArgumentException();
} catch (NullPointerException np) {
String errorMessage = "Sorry, There doesn't seem to be any bus stops with the words you have typed in";
count_label.setHorizontalAlignment(JLabel.CENTER);
// count_label.alignCenter();
count_label.setText(errorMessage);
System.out.println(errorMessage);
// dtm.setDataVector(null, columnLabels);
String[][] emptyData = new String[10][columnLabels.length];
dtm.setDataVector(emptyData, columnLabels);
} catch (IllegalArgumentException ie) {
System.out.println("print something valid");
}
}
});
}
public static void main(String[] args) throws IOException {
String stops_path = "inputs/stops.txt";
File stops = new File(stops_path);
// String[] stops_column_names = getColumnNames(stops);
ArrayList<String> stopNames = getStopNames(stops);
// printDuplicateStations(stopNames);
insertStopNamesToTST(stopNames);
String input = "Hasting";
String[] HastingsSearch = STOP_NAMES_TST.search(removeSpacesAndCapitlize(input));
Map<String, ArrayList<String[]>> stopDetails = createNameDetailsMap(stops);
for (String searchResult : HastingsSearch) {
ArrayList<String[]> details = stopDetails.get(searchResult);
for (String[] x : details) {
for (String s : x) {
System.out.print(s + " - ");
}
System.out.println();
}
}
Pattern p = Pattern.compile("[^a-z0-9\\- ]", Pattern.CASE_INSENSITIVE); // in order to check for
// an empty string input
Matcher m = p.matcher(input);
boolean b = m.find();
System.out.println(b);
// part2GUI();
}
}
| jonwk/CSU22012-DSA-Group-Project | part2.java | 2,989 | // In order for this to provide meaningful search functionality please move | line_comment | en | false | 2,586 | 12 | 2,989 | 12 | 3,163 | 12 | 2,989 | 12 | 3,601 | 13 | false | false | false | false | false | true |
220925_10 |
/**
* Created by tpre939 on 22/01/2018.
*/
import dao.ArticleDAO;
import dao.UserDAO;
import db.MySQLDatabase;
import dbObjects.Article;
import dbObjects.User;
import org.json.simple.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
public class MultimediaServlet extends HttpServlet {
private HttpSession session;
private MySQLDatabase db;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.db = new MySQLDatabase(getServletContext());
String paths = "";
session = req.getSession();
//This block handles deleting images, videos and audios
if (req.getParameter("deletePhotoButton") != null) {
deleteMultimedia(req, resp);
return;
}
//This block handles adding a youtube link to the database
else if (req.getParameter("youtubeLink") != null) {
addYoutubeLink(req, resp);
return;
}
//This block handles sending a response back to the ajax call for youtube links
else if (req.getParameter("youtubeAjax") != null) {
sendYoutubeAjax(req, resp);
}
//This block handles displaying (setting attributes for) gallery.jsp
else if(req.getParameter("allMedia") != null){
String allMedia = req.getParameter("allMedia");
//shows all media
if(allMedia.equals("true")){
paths = getAllMedia();
sortAndSetAttribute(req, paths);
}
//shows only the logged-in user's media
else{
//dealing with images
paths = getUserMedia(req);
sortAndSetAttribute(req, paths);
}
req.getRequestDispatcher("gallery.jsp").forward(req, resp);
}
}
private void sendYoutubeAjax(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String articleid = req.getParameter("articleid");
Article article = null;
try(ArticleDAO articleDAO = new ArticleDAO(db)){
article = articleDAO.getArticleById(articleid);
} catch (SQLException e) {
e.printStackTrace();
}
JSONObject obj = new JSONObject();
obj.put("Youtube", article.getYoutubeLink());
obj.put("Author", article.getUserName());
obj.put("ArticleId", articleid);
if (obj.size() != 0) {
String object = obj.toJSONString();
resp.getWriter().write(object);
}
}
private void addYoutubeLink(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String rawLink = req.getParameter("youtube-url");
String embedLink = rawLink.replace("watch?v=", "embed/");
if(embedLink.contains("<iframe>")){
embedLink = "";
}
String articleidString = req.getParameter("articleid");
int articleid = Integer.parseInt(articleidString);
try(ArticleDAO articleDAO = new ArticleDAO(db)){
articleDAO.addYoutubeLink(embedLink, articleid);
} catch (SQLException e) {
e.printStackTrace();
}
//redirect user back to same article page after deleting their comment
String username = req.getParameter("userLoggedIn");
String author = req.getParameter("author");
req.getRequestDispatcher("ArticleServlet?articleid=" + articleid + "&userLoggedIn=" + username + "&author=" + author).forward(req, resp);
}
private void deleteMultimedia(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Article article = null;
String articleId = req.getParameter("articleid");
Map<String, String[]> map = req.getParameterMap();
try (ArticleDAO articleDAO = new ArticleDAO(db)) {
article = articleDAO.getArticleById(articleId);
} catch (SQLException e) {
e.printStackTrace();
}
String currentImagePaths = article.getImages();
String[] currentImagePathsArray = currentImagePaths.split(",");
String deleteImagePaths = "";
//finding the paths of images selected to be deleted
for (String s : map.keySet()) {
if (!s.equals("deletePhotoButton") && !s.equals("articleid")) {
if (deleteImagePaths.equals("")) {
deleteImagePaths += map.get(s)[0];
} else {
deleteImagePaths = deleteImagePaths + "," + map.get(s)[0];
}
}
}
String[] deleteImagePathsArray = deleteImagePaths.split(",");
String finalImagePaths = getNewPathString(currentImagePathsArray, deleteImagePathsArray);
try (ArticleDAO articleDAO = new ArticleDAO(db)) {
articleDAO.addImages(Integer.parseInt(articleId), finalImagePaths);
} catch (SQLException e) {
e.printStackTrace();
}
//redirect user back to same article page after deleting their comment
String username = req.getParameter("userLoggedIn");
String author = req.getParameter("author");
req.getRequestDispatcher("ArticleServlet?articleid=" + articleId + "&userLoggedIn=" + username + "&author=" + author).forward(req, resp);
}
private String getNewPathString(String[] currentImagePathsArray, String[] deleteImagePathsArray) {
String finalImagePaths = "";
//creating new string of image paths for database which excludes those selected to be deleted
outer:
for (int i = 0; i < currentImagePathsArray.length; i++) {
for (int j = 0; j < deleteImagePathsArray.length; j++) {
if (currentImagePathsArray[i].equals(deleteImagePathsArray[j])) {
continue outer;
}
}
if (finalImagePaths.equals("")) {
finalImagePaths = currentImagePathsArray[i];
} else {
finalImagePaths = finalImagePaths + "," + currentImagePathsArray[i];
}
}
return finalImagePaths;
}
private String getAllMedia(){
List<Article> articleList = null;
try(ArticleDAO articleDAO = new ArticleDAO(db)){
articleList = articleDAO.getAllArticles();
} catch (SQLException e) {
e.printStackTrace();
}
String paths = "";
for(Article a: articleList){
paths += (a.getImages() + ",");
}
return paths.substring(0, paths.length() -1);
}
private String getUserMedia(HttpServletRequest req){
List<Article> articleList = null;
String username = (String)req.getSession().getAttribute("username");
User user = null;
String finalPath = "";
try(UserDAO userDAO = new UserDAO(db)){
user = userDAO.getUserByUname(username);
} catch (SQLException e) {
e.printStackTrace();
}
if(user != null) {
try (ArticleDAO articleDAO = new ArticleDAO(db)) {
articleList = articleDAO.getMyArticles(user);
} catch (SQLException e) {
e.printStackTrace();
}
//go through each Article object in list to get images of each article
String paths = "";
for (Article a : articleList) {
paths += (a.getImages() + ",");
}
//if there are images in any article in list, get rid of comma at end of string
if(paths.length() > 0) {
finalPath = paths.substring(0, (paths.length() - 1));
}
}
return finalPath;
}
//attributes for gallery.jsp
private void setGalleryAttributes(String paths, String id, HttpServletRequest req) throws ServletException, IOException {
String[] imagesArray = paths.split(",");
int numMedia = -1;
for (int i = 0; i < imagesArray.length; i++) {
String currentMedia = imagesArray[i];
if(!currentMedia.equals("")) {
String currentPath = imagesArray[i];
req.setAttribute(id + i, currentPath);
numMedia++;
}
}
req.setAttribute("num" + id, numMedia);
}
//sorts list depending on file extensions then calls method to set attributes for gallery.jsp
private String sortList(String paths, String ext, HttpServletRequest req) throws ServletException, IOException {
String sortedString = "";
String[] imagesArray = paths.split(",");
for (int i = 0; i < imagesArray.length; i++) {
String currentPath = imagesArray[i];
if(currentPath.contains("null")){
continue;
}
else if(currentPath.contains(ext)){
sortedString += (currentPath + ",");
}
}
if(sortedString.length() > 0) {
sortedString = sortedString.substring(0, sortedString.length() -1);
}
setGalleryAttributes(sortedString, ext, req);
return sortedString;
}
//calls method to sort list depending on file extensions (which then calls method to set attributes)
private void sortAndSetAttribute(HttpServletRequest req, String paths) throws ServletException, IOException {
String[] extensionArray = {"jpg", "jpeg", "png", "mp3", "wav", "ogg", "mp4", "webm"};
for (int i = 0; i < extensionArray.length; i++) {
sortList(paths, extensionArray[i], req);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
} | gayounglee57/smartCookiesBlog | src/MultimediaServlet.java | 2,151 | //redirect user back to same article page after deleting their comment | line_comment | en | false | 1,960 | 12 | 2,151 | 12 | 2,358 | 12 | 2,151 | 12 | 2,623 | 12 | false | false | false | false | false | true |
221744_8 | /**
* Point class creates points on image to be used
*
* @author Tyler Szeto
* @version 1.0
* @since 4-27-2017
*/
public class point {
// tracks x and y value for point
private int x;
private int y;
// String value for x added to y
private String distanceVal;
public point(int x, int y) {
this.x = x;
this.y = y;
// Tentative distance for compare to. Consider changing this to a hash
distanceVal = x + "" + y;
}
/**
* returns x position of point
*
* @return int x
*/
public int getX() {
return x;
}
/**
* sets x position of point
*
* @param int x
*/
public void setX(int x) {
this.x = x;
}
/**
* gets y position of point
*
* @return int y
*/
public int getY() {
return y;
}
/**
* sets y position for point
*
* @param int y
*/
public void setY(int y) {
this.y = y;
}
/**
* toString prints out x and y position of point
*/
public String toString() {
return ("x position: " + x + " y position: " + y);
}
/**
* equals method to check if two points are equal
*
* @param object being compared to
* @return boolean true if equal
*/
@Override
public boolean equals(Object object) {
// ArrayList is not properly computing equals for compareTo or something,
// repeat elements found in array
if (object == null || object.getClass() != getClass()) {
return false;
}
point other = (point) object;
return this.distanceVal.equals(other.getDistanceVal());
}
/**
* produces a hashCode for the point that is unique to this point
*
* @return int value for this point
*/
@Override
public int hashCode() {
return Integer.parseInt(distanceVal);
}
/**
* getDistanceVal will return distance value
*
* @return String for distance value
*/
public String getDistanceVal() {
return distanceVal;
}
/**
* setDistanceVal will set the distance value
*
* @param distanceVal the String value to set to
*/
public void setDistanceVal(String distanceVal) {
this.distanceVal = distanceVal;
}
} | Jonwlin/mst_2d_array_project | point.java | 575 | /**
* toString prints out x and y position of point
*/ | block_comment | en | false | 579 | 15 | 575 | 14 | 724 | 17 | 575 | 14 | 747 | 19 | false | false | false | false | false | true |
222806_3 | package org.apache.giraph.examples;
import java.util.HashMap;
import java.util.Map;
import org.apache.giraph.aggregators.matrix.dense.DoubleDenseVector;
import org.apache.giraph.examples.utils.DMIDMasterCompute;
import org.apache.giraph.examples.utils.DMIDVertexValue;
import org.apache.giraph.examples.utils.LongDoubleMessage;
import org.apache.giraph.graph.Vertex;
import org.apache.hadoop.io.BooleanWritable;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.LongWritable;
/**
* Implements the leadership variant of DMID. Differs from the basic
* implementation only in the cascading behavior. Profitability depends on
* leadership values and is not uniform.
* */
@Algorithm(name = "DMID leadership variant")
public class LeadershipDMIDComputation extends DMIDComputation {
/**
* SUPERSTEP RW_IT+10: Third iteration point of the cascading behavior
* phase.
**/
@Override
public void superstep10(
Vertex<LongWritable, DMIDVertexValue, DoubleWritable> vertex,
Iterable<LongDoubleMessage> messages) {
long vertexID = vertex.getId().get();
/** Is this vertex a global leader? */
if (!vertex.getValue().getMembershipDegree().containsKey(vertexID)) {
/** counts per communities the number of successors which are member */
HashMap<Long, Double> membershipCounter = new HashMap<Long, Double>();
double previousCount = 0.0;
for (LongDoubleMessage msg : messages) {
/**
* the msg value is the index of the community the sender is a
* member of
*/
Long leaderID = ((long) msg.getValue());
if (membershipCounter.containsKey(leaderID)) {
/** increase count by 1 */
previousCount = membershipCounter.get(leaderID);
membershipCounter.put(leaderID, previousCount + 1);
} else {
membershipCounter.put(leaderID, 1.0);
}
}
DoubleDenseVector vecLS = getAggregatedValue(LS_AGG);
LongWritable numCascadings = getAggregatedValue(DMIDMasterCompute.RESTART_COUNTER_AGG);
/** profitability threshold */
double threshold = vecLS.get((int) vertex.getId().get())
- (numCascadings.get() * DMIDMasterCompute.PROFTIABILITY_DELTA);
LongWritable iterationCounter = getAggregatedValue(ITERATION_AGG);
for (Map.Entry<Long, Double> entry : membershipCounter.entrySet()) {
if ((entry.getValue() / vertex.getNumEdges()) > threshold) {
/** its profitable to become a member, set value */
vertex.getValue()
.getMembershipDegree()
.put(entry.getKey(),
(1.0 / Math.pow(iterationCounter.get() / 3,
2)));
aggregate(NEW_MEMBER_AGG, new BooleanWritable(true));
}
}
boolean isPartOfAnyCommunity = false;
for (Map.Entry<Long, Double> entry : vertex.getValue()
.getMembershipDegree().entrySet()) {
if (entry.getValue() != 0.0) {
isPartOfAnyCommunity = true;
}
}
if (!isPartOfAnyCommunity) {
aggregate(NOT_ALL_ASSIGNED_AGG, new BooleanWritable(true));
}
}
}
}
| rwth-acis/DMID-Pregel-Implementation | DMID/LeadershipDMIDComputation.java | 851 | /** counts per communities the number of successors which are member */ | block_comment | en | false | 730 | 12 | 851 | 13 | 840 | 12 | 851 | 13 | 1,108 | 13 | false | false | false | false | false | true |
223155_1 | /*
* Copyright (C) 2020 Grakn Labs
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
package grakn.core.server;
import com.google.common.base.Stopwatch;
import grakn.core.common.config.SystemProperty;
import grakn.core.common.exception.ErrorMessage;
import grakn.core.server.util.PIDManager;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* The main class of the 'grakn' command. This class is not a class responsible
* for booting up the real command, but rather the command itself.
*
* Please keep the class name "Grakn" as it is what will be displayed to the user.
*/
public class Grakn {
private static final Logger LOG = LoggerFactory.getLogger(Grakn.class);
public static void main(String[] args) {
Thread.setDefaultUncaughtExceptionHandler((Thread t, Throwable e) ->
LOG.error(ErrorMessage.UNCAUGHT_EXCEPTION.getMessage(t.getName()), e));
try {
String graknPidFileProperty = Optional.ofNullable(SystemProperty.GRAKN_PID_FILE.value())
.orElseThrow(() -> new RuntimeException(ErrorMessage.GRAKN_PIDFILE_SYSTEM_PROPERTY_UNDEFINED.getMessage()));
Path pidfile = Paths.get(graknPidFileProperty);
PIDManager pidManager = new PIDManager(pidfile);
pidManager.trackGraknPid();
// Start Server with timer
Stopwatch timer = Stopwatch.createStarted();
Server server = ServerFactory.createServer(new Arguments(args));
server.start();
LOG.info("Grakn started in {}", timer.stop());
try {
server.awaitTermination();
} catch (InterruptedException e) {
// grakn server stop is called
server.close();
Thread.currentThread().interrupt();
}
} catch (RuntimeException | IOException e) {
LOG.error(ErrorMessage.UNCAUGHT_EXCEPTION.getMessage(e.getMessage()), e);
System.err.println(ErrorMessage.UNCAUGHT_EXCEPTION.getMessage(e.getMessage()));
}
}
public static class Arguments {
private final Tracing grablTracing;
private Arguments(String[] args) {
Options options = new Options();
options.addOption(Option.builder("t")
.longOpt("tracing-enabled")
.desc("Enable grabl tracing")
.required(false)
.type(Boolean.class)
.build());
options.addOption(Option.builder()
.longOpt("tracing-uri")
.hasArg()
.desc("Grabl tracing URI")
.required(false)
.type(String.class)
.build());
options.addOption(Option.builder()
.longOpt("tracing-username")
.hasArg()
.desc("Grabl tracing username")
.required(false)
.type(String.class)
.build());
options.addOption(Option.builder()
.longOpt("tracing-access-token")
.hasArg()
.desc("Grabl tracing access-token")
.required(false)
.type(String.class)
.build());
CommandLineParser parser = new DefaultParser();
CommandLine arguments;
try {
arguments = parser.parse(options, args);
} catch (ParseException e) {
(new HelpFormatter()).printHelp("Grakn options", options);
throw new RuntimeException(e.getMessage());
}
if (arguments.hasOption("tracing-enabled")) {
grablTracing = new Tracing(
arguments.getOptionValue("tracing-uri"),
arguments.getOptionValue("tracing-username"),
arguments.getOptionValue("tracing-access-token")
);
} else {
grablTracing = null;
}
}
public boolean isGrablTracing() {
return grablTracing != null;
}
public Tracing getGrablTracing() {
return grablTracing;
}
public static class Tracing {
private final String uri;
private final String username;
private final String accessToken;
private Tracing(String uri, String username, String accessToken) {
this.uri = uri;
this.username = username;
this.accessToken = accessToken;
}
public String getUri() {
return uri;
}
public String getUsername() {
return username;
}
public String getAccessToken() {
return accessToken;
}
public boolean isSecureMode() {
return username != null;
}
}
}
}
| stjordanis/grakn | server/Grakn.java | 1,321 | /**
* The main class of the 'grakn' command. This class is not a class responsible
* for booting up the real command, but rather the command itself.
*
* Please keep the class name "Grakn" as it is what will be displayed to the user.
*/ | block_comment | en | false | 1,133 | 61 | 1,321 | 65 | 1,401 | 62 | 1,321 | 65 | 1,623 | 64 | false | false | false | false | false | true |
223752_36 | import java.util.Random;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.awt.Color;
/**
* A simple predator-prey simulator, based on a rectangular field
* containing various animals and some plants.
*
* @author Daniel Ratiu and Michael Jacob
* @version 22/02/2018
*/
public class Simulator
{
// Constants representing configuration information for the simulation.
// The default depth of the grid.
private static final int DEFAULT_DEPTH = 200;
// The default width for the grid.
private static final int DEFAULT_WIDTH = 250;
// The coefficient that a fox will be created in any given grid position.
private static final double FOX_CREATION_COEFFICIENT = 0.06;
// The coefficient that a rabbit will be created in any given grid position.
private static final double RABBIT_CREATION_COEFFICIENT = 0.11;
// The coefficient that an eagle will be created in any given grid position.
private static final double EAGLE_CREATION_COEFFICIENT = 0.05;
// The coefficient that a cow will be created in any given grid position.
private static final double COW_CREATION_COEFFICIENT = 0.07;
// The coefficient that an elephant will be created in any given grid position.
// This is split evenly between male and female elephants.
private static final double ELEPHANT_CREATION_COEFFICIENT = 0.1;
// The coefficient that a plant will be created in any given grid position.
private static final double PLANT_CREATION_COEFFICIENT = 0.15;
// A shared random number generator.
private static final Random rand = Randomizer.getRandom();
// The probability that some animal will catch a disease on each step.
private static final double DISEASE_PROBABILITY = 0.07;
// List of animals in the field.
private List<Animal> animals;
// The current state of the field.
private Field field;
// The number of completed steps of the simulation.
private int step;
// A graphical view of the simulation.
private SimulatorView view;
// List of plants in the field.
private List<Plant> plants;
// The weather conditions for the next step.
private Weather currentWeather;
/**
* Construct a simulation field with default size.
*/
public Simulator()
{
this(DEFAULT_DEPTH, DEFAULT_WIDTH);
}
/**
* Create a simulation field with the given size.
* @param depth Depth of the field. Must be greater than zero.
* @param width Width of the field. Must be greater than zero.
*/
public Simulator(int depth, int width)
{
if(width <= 0 || depth <= 0) {
System.out.println("The dimensions must be greater than zero.");
System.out.println("Using default values.");
depth = DEFAULT_DEPTH;
width = DEFAULT_WIDTH;
}
animals = new ArrayList<>();
plants = new ArrayList<>();
field = new Field(depth, width);
// Randomises weather in accordance with their probabilties.
currentWeather = Weather.randomWeightedWeather();
// Create a view of the state of each location in the field.
view = new SimulatorView(depth, width);
view.setColor(Rabbit.class, Color.ORANGE);
view.setColor(Fox.class, Color.BLUE);
view.setColor(Cow.class, Color.BLACK);
view.setColor(MaleElephant.class, Color.MAGENTA);
view.setColor(FemaleElephant.class, Color.MAGENTA);
view.setColor(Eagles.class, Color.RED);
view.setColor(Plant.class, Color.GREEN);
// Setup a valid starting point.
reset();
}
/**
* Run the simulation from its current state for a reasonably long period,
* (4000 steps).
*/
public void runLongSimulation()
{
simulate(4000);
}
/**
* Run the simulation from its current state for the given number of steps.
* Stop before the given number of steps if it ceases to be viable.
* @param numSteps The number of steps to run for.
*/
public void simulate(int numSteps)
{
for(int step = 1; step <= numSteps && view.isViable(field); step++) {
simulateOneStep();
delay(60); // uncomment this to run more slowly
}
}
/**
* Run the simulation from its current state for a single step.
* Iterate over the whole field updating the state of each
* organism.
*/
public void simulateOneStep()
{
// Run the effects of weather conditions.
processWeather();
// See if an animal becomes infected.
checkDisease();
// Provide space for newborn animals.
List<Animal> newAnimals = new ArrayList<>();
// Provide space for new plants.
List<Plant> newPlants = new ArrayList<>();
// Let all animals act.
for(Iterator<Animal> it = animals.iterator(); it.hasNext(); ) {
Animal animal = it.next();
if (isNight()){
animal.nightAct(newAnimals);
}
else{
animal.dayAct(newAnimals);
}
if(! animal.isAlive()) {
it.remove();
}
}
// Let all plants act.
for(Iterator<Plant> it = plants.iterator(); it.hasNext(); ) {
Plant plant = it.next();
plant.act(newPlants);
if(! plant.isAlive()) {
it.remove();
}
}
// Add the newly born organisms to the main lists.
animals.addAll(newAnimals);
plants.addAll(newPlants);
step++;
// Randomise the weather again for the next step.
currentWeather = Weather.randomWeightedWeather();
showInfo();
view.showStatus(step, field);
}
/**
* Reset the simulation to a starting position.
*/
public void reset()
{
step = 0;
animals.clear();
plants.clear();
populate();
// Show the starting state in the view.
view.showStatus(step, field);
showInfo();
}
/**
* Randomly populate the field with organisms.
*/
private void populate()
{
field.clear();
for(int row = 0; row < field.getDepth(); row++) {
for(int col = 0; col < field.getWidth(); col++) {
if(rand.nextDouble() <= FOX_CREATION_COEFFICIENT) {
Location location = new Location(row, col);
Fox fox = new Fox(true, field, location);
animals.add(fox);
}
else if(rand.nextDouble() <= RABBIT_CREATION_COEFFICIENT) {
Location location = new Location(row, col);
Rabbit rabbit = new Rabbit(true, field, location);
animals.add(rabbit);
}
else if(rand.nextDouble() <= EAGLE_CREATION_COEFFICIENT) {
Location location = new Location(row, col);
Eagles eagle = new Eagles(true, field, location);
animals.add(eagle);
}
else if(rand.nextDouble() <= COW_CREATION_COEFFICIENT) {
Location location = new Location(row, col);
Cow cow = new Cow(true, field, location);
animals.add(cow);
}
else if(rand.nextDouble() <= PLANT_CREATION_COEFFICIENT) {
Location location = new Location(row, col);
Plant plant = new Plant( field, location);
plants.add(plant);
}
else if(rand.nextDouble() <= ELEPHANT_CREATION_COEFFICIENT) {
Location location = new Location(row, col);
int genderDecider = rand.nextInt(2);
if (genderDecider == 0){
FemaleElephant elephant = new FemaleElephant (true, field, location);
animals.add(elephant);
}
else{
MaleElephant elephant = new MaleElephant(true, field, location);
animals.add(elephant);
}
}
// else leave the location empty.
}
}
}
/**
* Process the effect of the current weather condition.
*/
private void processWeather()
{
switch(currentWeather){
case RAINING: raining();
break;
case SUNNY: sunny();
break;
case WINDY: windy();
break;
case SNOWING: snowing();
break;
}
}
/**
* Actions to take when raining.
*/
private void raining()
{
// Plants grow more.
for (Plant plant : plants){
plant.grow();
}
// Eagles struggle to find food in rain.
for (Animal animal : animals){
if( animal instanceof Eagles){
animal.incrementHunger();
}
}
}
/**
* Actions to take when sunny.
*/
private void sunny()
{
// Plants grow more when its sunny.
for (Plant plant : plants){
plant.grow();
}
}
/**
* Actions to take when windy.
*/
private void windy()
{
// Wind can destroy plants.
for (Plant plant : plants){
if(rand.nextDouble() > plant.calculateWindSurvivalProbability()) {
plant.setDead();
}
}
}
/**
* Actions to take when snowing.
*/
private void snowing()
{
// Plants and animals can be killed by snow.
for (Plant plant : plants){
if(rand.nextDouble() > plant.calculateSnowSurvivalProbability()) {
plant.setDead();
}
}
for (Animal animal: animals){
if(rand.nextDouble() > animal.calculateSnowSurvivalProbability()) {
animal.setDead();
}
}
}
/**
* Infect a random animal at the disease probability rate.
*/
private void checkDisease()
{
if(rand.nextDouble() <= DISEASE_PROBABILITY){
findRandomAnimal().infect();
}
}
/**
* Find a random animal in the field.
* @return A random animal in the field.
*/
private Animal findRandomAnimal()
{
return animals.get(rand.nextInt(animals.size()));
}
/**
* Check if it is night. Night occurs every four steps, first ocurring on the fourth step.
* @return True if it is night.
*/
private boolean isNight()
{
if((step % 4 ) == 3){
return true;
}
return false;
}
/**
* Show time of day and weather information for the next step to be executed.
*/
private void showInfo(){
String dayNight = "Time: ";
if (isNight()){
dayNight += "night";
}
else{
dayNight += "day";
}
String weatherString = "Weather: " + currentWeather.toString().toLowerCase();
view.setInfoText(dayNight + " " + weatherString);
}
/**
* Pause for a given time.
* @param millisec The time to pause for, in milliseconds
*/
private void delay(int millisec)
{
try {
Thread.sleep(millisec);
}
catch (InterruptedException ie) {
// wake up
}
}
}
| MichaelJacob21012/Ecosystem-Simulator | Simulator.java | 2,723 | /**
* Reset the simulation to a starting position.
*/ | block_comment | en | false | 2,426 | 13 | 2,723 | 13 | 2,866 | 15 | 2,723 | 13 | 3,241 | 16 | false | false | false | false | false | true |
224213_0 | package chapter4;
/* Exercise 14: Create a class with a static String field that is initialized
* at the point of definition, and another one that is initialized by the static block.
* Add a static method that prints both fields and demonstrates that they are both initialized before they are used.
*/
class Town{
static String streets = "a lot";
static String avenues;
static{
avenues = "even moar";
}
static void plan(){
System.out.println("There are " + Town.streets + " of streets and " + Town.avenues + " avenues in town");
}
}
public class Exercise14 {
public static void main(String[] args) {
Town.plan(); //Well, the Town.streets and Town.avenues variables must be initialized before they are used. It definitely cannot happen after :)
}
}
| daboyz/Eckel | src/chapter4/Exercise14.java | 224 | /* Exercise 14: Create a class with a static String field that is initialized
* at the point of definition, and another one that is initialized by the static block.
* Add a static method that prints both fields and demonstrates that they are both initialized before they are used.
*/ | block_comment | en | false | 182 | 60 | 224 | 61 | 207 | 63 | 224 | 61 | 223 | 66 | false | false | false | false | false | true |
224417_0 | package a5;
import java.util.Set;
import common.Util;
import common.types.Tuple1;
/** A instance represents a human and their health.
*
* @author Mshnik, revised by gries */
public final class Human extends Tuple1<String> {
/** The possible Covid-related states of a human. */
public enum State { // The names indicate the state.
HEALTHY,
ILL,
DEAD,
IMMUNE
}
/** The network to this human belongs. */
private final Network graph;
/** Amount of health this human has. >= 0.<br>
* 0 means dead, >0 means alive */
private int health;
/** State of this human. */
private State state;
/** Time step in which this human became ill (-1 if never been ill). */
private int stepGotIll= -1;
/** Time step in which this human became immune (-1 if not immune). */
private int stepGotImmune= -1;
/** Time step in which this human died (-1 if not dead). */
private int stepDied= -1;
/** Constructor: a healthy HUman with name n and health h, added to graph g. <br>
* Precondition: The new human is not in g, and their name is distinct from the name of <br>
* any other human in g. */
public Human(String n, int h, Network g) {
super(n);
health= h;
state= State.HEALTHY;
graph= g;
graph.addVertex(this);
}
/** Return a representation of this human. */
public @Override String toString() {
return super.toString() + " - " + state;
}
/** Return the name of this human. */
public String name() {
return _1;
}
/** Make this human ill during step currentStep. <br>
* Throw a RuntimeException if this human is not HEALTHY. */
public void getIll(int currentStep) {
if (state != State.HEALTHY) {
throw new RuntimeException(state + " human can't become ill");
}
state= State.ILL;
stepGotIll= currentStep;
}
/** Make this human immune during step currentStep. <br>
* Throw a RuntimeException if this human is immune or dead. */
public void getImmune(int currentStep) {
if (state == State.IMMUNE || state == State.DEAD) {
throw new RuntimeException(state + " human can't become immune");
}
state= State.IMMUNE;
stepGotImmune= currentStep;
}
/** Decrement the health of this human in step currentStep. <br>
* If its health becomes 0, the human dies. <br>
* Throw a RuntimeException if this human is not ill. */
public void reduceHealth(int currentStep) {
if (state != State.ILL) { throw new RuntimeException(state + " human can't lose health"); }
health-- ;
if (health == 0) {
state= State.DEAD;
stepDied= currentStep;
}
}
/** = the state of this human. */
public State state() {
return state;
}
/** = "This human is alive". */
public boolean isAlive() {
return state != State.DEAD;
}
/** = "This human is dead". */
public boolean isDead() {
return !isAlive();
}
/** = "This human is healthy. */
public boolean isHealthy() {
return state == State.HEALTHY;
}
/** = "This human is immune". */
public boolean isImmune() {
return state == State.IMMUNE;
}
/** = "This human is ill". */
public boolean isIll() {
return state == State.ILL;
}
/** = the time step in which this human got ill" (-1 if never been ill). */
public int frameGotIll() {
return stepGotIll;
}
/** = the time step in which this human got immune" (-1 if not immune). */
public int frameGotImmune() {
return stepGotImmune;
}
/** = the time step in which this human died" (-1 if not dead). */
public int frameDied() {
return stepDied;
}
/** = the neighbors of this human. */
public Set<Human> neighbors() {
return graph.neighborsOf(this);
}
/** = a random neighbor of this human */
public Human randomNeighbor() {
return Util.randomElement(graph.neighborsOf(this));
}
}
| pratyush1712/CS2110 | a5/src/a5/Human.java | 1,060 | /** A instance represents a human and their health.
*
* @author Mshnik, revised by gries */ | block_comment | en | false | 1,002 | 23 | 1,060 | 26 | 1,139 | 25 | 1,060 | 26 | 1,255 | 26 | false | false | false | false | false | true |
224717_8 | package com.company;
import java.util.*;
public class DataManager {
HashMap<Integer,Site> SiteMap;
public static final int sitenums = 10;
HashMap<Integer,Boolean> SiteFailure;
HashMap<Integer,List<Integer>> SiteFailTime;
public DataManager()
{
SiteMap = new HashMap<>();
SiteFailure = new HashMap<>();
SiteFailTime = new HashMap<>();
for(int i=0;i<sitenums;i++)
{
Site site = new Site(i+1);
SiteMap.put(i+1,site);
SiteFailure.put(i+1,false);
SiteFailTime.put(i+1,new LinkedList<>());
SiteFailTime.get(i+1).add(-1);
}
}
public Site get(int siteId)
{
return SiteMap.get(siteId);
}
/**
* get the last failure time of some site
* @param siteId
* @return
* @author jingshuai jiang
*/
public int GetLastFailTime(int siteId)
{
int size = SiteFailTime.get(siteId).size();
return SiteFailTime.get(siteId).get(size-1);
}
/**
* check the site's status
* @param siteId
* @return
* @author jingshuai jiang
*/
public boolean SiteFailed(int siteId)
{
return SiteFailure.get(siteId);
}
/**
*
* @param varId
* @param value
* @param siteId
* @param timestamp
*/
public void write (int varId, int value, int siteId, int timestamp) {
Site s = SiteMap.get(siteId);
s.write(varId, value, timestamp);
}
/**
*
* @param variableId
* @param timestamp
* @param siteId
* @return
* @author jingshuai jiang
*/
public int RONonRepRead(int variableId,int timestamp,int siteId)
{
Site site = get(siteId);
List<Variable> history = site.vartable.get(variableId);
for(int i=history.size()-1;i>=0;i--)
{
if(history.get(i).version<=timestamp)
{
return history.get(i).value;
}
}
return -1;
}
/**
* Read for replicated variables of RO transactions
* @param variableId
* @param timestamp
* @param siteId
* @return
* @author jingshuai jiang
*/
public String RORepRead(int variableId,int timestamp,int siteId)
{
Site site = get(siteId);
List<Variable> history = site.vartable.get(variableId);
for(int i=history.size()-1;i>=0;i--)
{
//looking for the version before ro start
if(history.get(i).version>timestamp)
continue;
//found
int lastcommitedtimebeforestart = history.get(i).version;
//check if it is always up during time range
if(AlwaysUp(lastcommitedtimebeforestart,timestamp,siteId))
return String.valueOf(history.get(i).value);
//if not, then this site can not trust.
break;
}
return "No";
}
/**
* check if site is up during two time range
* @param lastcommitedtimebeforestart
* @param starttime
* @param siteId
* @return
* @author jingshuai jiang
*/
public boolean AlwaysUp(int lastcommitedtimebeforestart, int starttime,int siteId)
{
List<Integer> failedtime = SiteFailTime.get(siteId);
for(int i=0;i<failedtime.size();i++)
{
int time = failedtime.get(i);
if(time<starttime&&time>lastcommitedtimebeforestart)
return false;
}
return true;
}
/**
* fail some site
* @param SiteId
* @param timestamp
* @author jingshuai jiang
*/
public void Fail(int SiteId,int timestamp) {
Site site = get(SiteId);
site.Sitefail();
SiteFailure.put(SiteId, true);
SiteFailTime.get(SiteId).add(timestamp);
}
/**
* recover some site
* @param SiteId
* @param timestamp
* @author jingshuai jiang
*/
public void Recover(int SiteId, int timestamp)
{
Site site = get(SiteId);
int size = SiteFailTime.get(SiteId).size();
site.SiteRecover(timestamp,SiteFailTime.get(SiteId).get(size-1));
SiteFailure.put(SiteId,false);
}
public int GetSiteVariableValue(int SiteId, int VariableId)
{
Site site = get(SiteId);
return site.GetValue(VariableId);
}
public int GetRecoverTime(int siteId)
{
return get(siteId).recoverytime;
}
public void ReleaseSiteLocks(int TransactionId,int siteid)
{
if(SiteFailed(siteid))
return;
Site site = get(siteid);
site.releaselock(TransactionId);
}
}
| jingshuaijiang/nyu_advanced_database_system | src/com/company/DataManager.java | 1,235 | //if not, then this site can not trust. | line_comment | en | false | 1,159 | 11 | 1,234 | 11 | 1,391 | 11 | 1,235 | 11 | 1,450 | 11 | false | false | false | false | false | true |