file_id
stringlengths 4
9
| content
stringlengths 41
35k
| repo
stringlengths 7
113
| path
stringlengths 5
90
| token_length
int64 15
4.07k
| original_comment
stringlengths 3
9.88k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | excluded
bool 2
classes |
---|---|---|---|---|---|---|---|---|
213965_0 | __________________________________________________________________________________________________
sample 1 ms submission
class Solution {
public int findMinMoves(int[] machines) {
if (machines == null || machines.length <= 1) {
return 0;
}
int sum = 0;
for (int machine : machines) {
sum += machine;
}
if (sum % machines.length != 0) {
return -1;
}
int target = sum / machines.length;
int cur = 0, max = 0;
for (int machine : machines) {
cur += machine - target; //load-avg is "gain/lose"
max = Math.max(Math.max(max, Math.abs(cur)), machine - target);
}
return max;
}
}
__________________________________________________________________________________________________
sample 34876 kb submission
class Solution {
public int findMinMoves(int[] machines) {
int sum = Arrays.stream(machines).sum(), n = machines.length;
if (sum % n != 0)
return -1;
int avg = sum / n, cn = 0, ans = 0;
for (int m : machines) {
cn += m - avg;
ans = Math.max(ans, Math.max(Math.abs(cn), m - avg));
}
return ans;
}
}
__________________________________________________________________________________________________
| strengthen/LeetCode | Java/517.java | 314 | //load-avg is "gain/lose" | line_comment | en | false |
214329_1 | import java.io.*;
import java.lang.*;
class zwapi {
public static void main(String[] args) {
int debug=0;
try {if (args.length > 0) {
String weather=args[0];
String destination=args[1];
File weatherf=new File(weather);
if(!weatherf.exists()){System.err.println("No weather!");System.exit(0);}
String weatherhtml=new String();
DataInputStream in = new DataInputStream(new FileInputStream(weather));
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) { weatherhtml=weatherhtml+(strLine); }
in.close();
if(debug==1)System.out.println("start");
/* StringBuffer returnMessage = new StringBuffer(weatherhtml);
int startPosition = 0; // encountered the first closing braces
int endPosition = 0; // encountered the first closing braces
startPosition = returnMessage.indexOf("<",0); // look for the next closing brace
endPosition = returnMessage.indexOf(">",0); // look for the next closing brace
while( (startPosition != -1) && (endPosition != 0)) {
if(debug==1)System.out.println(" x "+startPosition+" "+endPosition);
returnMessage.delete( startPosition, endPosition ); // remove the tag
startPosition = (returnMessage).indexOf("<",0); // look for the next closing brace
endPosition = (returnMessage).indexOf(">",0); // look for the next closing brace
}
*/
String tokens[];
String sparky=new String();
weatherhtml.replaceAll("\\<.*?>","");
if(debug==1)System.out.println(weatherhtml);
tokens = weatherhtml.split("Conditions");
if(tokens.length>1){
sparky=tokens[1];}
if(debug==1)System.out.println(sparky);
tokens = sparky.split("Visibility");
sparky=tokens[0];
if(debug==1)System.out.println(sparky);
weatherhtml=(weatherhtml).replaceAll(" ", "");
weatherhtml=(weatherhtml).replaceAll("°", "");
if(debug==1)System.out.println(weatherhtml);
tokens = weatherhtml.split("Temperature");
if(tokens.length>1){
weatherhtml=tokens[1];}
if(debug==1)System.out.println(weatherhtml);
tokens = weatherhtml.split("F");
String f=tokens[0].replaceAll("\\<.*?>","");
if(debug==1)System.out.println(f);
tokens = weatherhtml.split("Conditions");
if(tokens.length>1){
weatherhtml=tokens[1];}
if(debug==1)System.out.println(weatherhtml);
tokens = weatherhtml.split("Visibility");
weatherhtml=tokens[0];
if(debug==1)System.out.println(weatherhtml+" end");
int code=0;
/*
18,19,22,31 - sunny -
1 - sun w slight clouds -
3 - light snow -
4 - light rain w sun -
8 - snow w clouds
9 - drizzle
12 - overcast
13 - heavy clouds
16 - heavy snow
17 - sun and wind
20 - fog
21 - mostly cloudy
23 - light clouds
25 - partly cloudy
26 - smoke
36 - light cloud rain with haze
42 - thunderstorm
*/
if(weatherhtml.contains("SnowShowers")){code=3;
}else if(weatherhtml.contains("IcePelletShowers")){code=16;
}else if(weatherhtml.contains("HailShowers")){code=16;
}else if(weatherhtml.contains("SmallHailShowers")){code=16;
}else if(weatherhtml.contains("Thunderstorm")){code=42;
}else if(weatherhtml.contains("ThunderstormsandRain")){code=42;
}else if(weatherhtml.contains("ThunderstormsandSnow")){code=42;
}else if(weatherhtml.contains("ThunderstormsandIcePellets")){code=42;
}else if(weatherhtml.contains("ThunderstormswithHail")){code=42;
}else if(weatherhtml.contains("ThunderstormswithSmallHail")){code=42;
}else if(weatherhtml.contains("FreezingDrizzle")){code=9;
}else if(weatherhtml.contains("FreezingRain")){code=36;
}else if(weatherhtml.contains("FreezingFog")){code=12;
}else if(weatherhtml.contains("Overcast")){code=13;
}else if(weatherhtml.contains("Clear")){code=18;
}else if(weatherhtml.contains("PartlyCloudy")){code=1;
}else if(weatherhtml.contains("MostlyCloudy")){code=25;
}else if(weatherhtml.contains("ScatteredClouds")){code=17;
}else if(weatherhtml.contains("SnowGrains")){code=8;
}else if(weatherhtml.contains("IceCrystals")){code=8;
}else if(weatherhtml.contains("IcePellets")){code=8;
}else if(weatherhtml.contains("VolcanicAsh")){code=26;
}else if(weatherhtml.contains("WidespreadDust")){code=26;
}else if(weatherhtml.contains("DustWhirls")){code=26;
}else if(weatherhtml.contains("Sandstorm")){code=26;
}else if(weatherhtml.contains("LowDriftingSnow")){code=8;
}else if(weatherhtml.contains("LowDriftingWidespreadDust")){code=8;
}else if(weatherhtml.contains("LowDriftingSand")){code=26;
}else if(weatherhtml.contains("BlowingSnow")){code=16;
}else if(weatherhtml.contains("BlowingWidespreadDust")){code=8;
}else if(weatherhtml.contains("BlowingSand")){code=26;
}else if(weatherhtml.contains("RainMist")){code=9;
}else if(weatherhtml.contains("RainShowers")){code=4;
}else if(weatherhtml.contains("Rain")){code=4;
}else if(weatherhtml.contains("Snow")){code=16;
}else if(weatherhtml.contains("Sand")){code=20;
}else if(weatherhtml.contains("Haze")){code=21;
}else if(weatherhtml.contains("Spray")){code=21;
}else if(weatherhtml.contains("Hail")){code=36;
}else if(weatherhtml.contains("Mist")){code=21;
}else if(weatherhtml.contains("Fog")){code=20;
}else if(weatherhtml.contains("Smoke")){code=26;
}else if(weatherhtml.contains("Drizzle")){code=9;
}else{code=31;}
BufferedWriter out = new BufferedWriter(new FileWriter(destination,false));
out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?><weatheritems><weatheritem timestamp=\"2011-12-14T08:27:22-08:00\"><location><city name=\"Zurkville\"/><state short=\"ZA\" long=\"Zurkville\"/><country short=\"ZZ\" long=\"Zurkian Empire\" medium=\"Zurkian Empire\"/><postalcode value=\"ZZ\"/></location><current><station_id>ZZ</station_id><observation_Time>2011-12-14T07:55:00-08:00</observation_Time><temp_f>"+f+"</temp_f><temp_c>"+f+"</temp_c><humidity></humidity><wind_direction>North</wind_direction><wind_mph>0.0</wind_mph><barometer>30.12</barometer><dewpoint_f></dewpoint_f><dewpoint_c></dewpoint_c><visibility>10.00</visibility><condition_code>"+code+"</condition_code><condition>"+sparky+"</condition></current></weatheritem></weatheritems>");
out.close();
} else {System.out.println ("Zurkian Chumby Hack - zwapi [path of weather] [path of final]");}
}catch (Exception e) { System.err.println(e.toString()); }
}}
| JesseCake/zurks-offline-firmware-classic | www/zwapi.java | 2,037 | /*
18,19,22,31 - sunny -
1 - sun w slight clouds -
3 - light snow -
4 - light rain w sun -
8 - snow w clouds
9 - drizzle
12 - overcast
13 - heavy clouds
16 - heavy snow
17 - sun and wind
20 - fog
21 - mostly cloudy
23 - light clouds
25 - partly cloudy
26 - smoke
36 - light cloud rain with haze
42 - thunderstorm
*/ | block_comment | en | true |
214420_1 | /*
NAME: <Aimee Haas>
COS 161, Spring 2021, Prof. Amorelli
Project 03
File Name: MemoryCard.java
*/
import java.awt.Color;
public class MemoryCard {
private String shapeType;
private Color color;
private boolean isUncovered;
private String colorString;
//create Custom Colors
Color TEAL = new Color(15, 103, 158);
Color LILAC = new Color(108, 102, 155);
Color SPRUCE = new Color(78, 112, 73);
Color BURNTRED = new Color(145, 33, 33);
public MemoryCard (String shape, Color c, String cString, boolean uncover) {
shapeType = shape;
color = c;
isUncovered = uncover;
colorString = cString;
}
//Overloaded for Player Uncovered Set
public MemoryCard (String shape, String c) {
shapeType = shape;
colorString = c;
}
public String toString() {
String formatDisplay = " Color : " + colorString +" Shape : "+ shapeType ;
return formatDisplay;
}
public void setShape(String s) {
shapeType = s;
}
public void setColor (Color c) {
color = c;
}
public void setColorString(String c) {
colorString = c;
}
public String getColorString() {
return colorString;
}
public void setIsUncovered(boolean uncover) {
isUncovered = uncover;
}
public String getShape() {
return shapeType;
}
public Color getColor() {
return color;
}
public boolean getIsUncovered() {
return isUncovered;
}
}
| ahaas207/Concentration-64 | MemoryCard.java | 433 | //create Custom Colors | line_comment | en | true |
214474_0 | package backup;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.util.Random;
public class Pickup {
byte me;
public final int HEALTH = 0, AMMO = 1;
public final int RECOVERY = 25;
final String[] types = new String[] {"health", "ammo"};
private int currentPickupType = 0;
private int pW, pH, sX, sY;
Random rand;
private Rectangle rectContainingImage;
//private Point middleOfSprite;
public Pickup()
{
rand = new Random();
currentPickupType = rand.nextInt(1);
}
public Pickup(int type, int w, int h)
{
currentPickupType = type;
pW = w; pH = h;
rand = new Random();
//random position for new pickup
sX = rand.nextInt(pW);
sY = rand.nextInt(pH);
}
//the draw method
public void draw(Graphics g, BufferedImage bi)
{
setRectangle(bi);
g.drawImage(bi, sX, sY, null);
}
//sets and gets//
public void setType(int type)
{currentPickupType = type;}
public int getType()
{return currentPickupType;}
public String toString()
{return types[currentPickupType];}
public Rectangle getRectangle(){
return rectContainingImage;
}
public void setRectangle(BufferedImage bi){
rectContainingImage = new Rectangle(sX,sY,bi.getWidth(),bi.getHeight());
}
public int getRecovery()
{
return RECOVERY;
}
}
| j2kun/zmob | backup/Pickup.java | 443 | //private Point middleOfSprite;
| line_comment | en | true |
214493_5 | /**
* This is a java program that tries to recover crypto hashes using
* a dictionary aka wordlist (not included)
* @author Copyright 2007 rogeriopvl, <http://www.rogeriopvl.com>
* @version 0.2
*
* Changelog:
* v0.2 - minor code corrections, now with GUI hash prompt for better usability.
*
* 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/>.
*
* Instructions: Just compile it as a normal java class and run it. You will need
* a dictionary file not included with the source. The file must have each word in a new line.
*
* PERSONAL DISCLAIMER: This program was made exclusively for educational purposes, therefore
* I can't be held responsible for the actions of others using it.
*/
import java.util.Scanner;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.security.NoSuchAlgorithmException;
import javax.swing.JOptionPane;
public class HashRecovery {
private static final String PROGNAME = "HashRecovery";
private static final String VERSION = "v0.5";
private static final int MIN_HASH_LENGTH = 32;
private static final String EMPTY_HASH = "d41d8cd98f00b204e9800998ecf8427e";
/**
* Main method
* @param args command line arguments
* @throws FileNotFoundException
*/
public static void main (String [] args) throws FileNotFoundException {
String algo = null;
String dictionaryPath = null;
if (args.length < 1) {
usage();
}
else if (args[0].equals("-a")) {
if (args.length != 3) {
usage();
}
else {
algo = args[1];
dictionaryPath = args[2];
}
}
else {
usage();
}
if (algo.equals(null)) {
algo = "MD5";
}
//let's ask for the hash to recover in a fancy dialog :)
String hash = JOptionPane.showInputDialog(null, "Hash to recover: ", PROGNAME+" "+VERSION, 1);
if (hash.length() < MIN_HASH_LENGTH)
System.err.println ("Warning: probably not a valid hash, proceeding anyway...");
Scanner infile = new Scanner(new FileReader(dictionaryPath));
String line;
int count = 0;
while (infile.hasNext()) {
line = infile.nextLine();
count++;
//no need to spend CPU cycles calculating this one...
if (hash.equals(EMPTY_HASH)) {
System.out.println ("Done it! That's the hash of an empty string!");
System.exit(0);
}
try {
if (hash.equals(HashUtils.generateHash(line, algo))) {
System.out.println ("Houston, we've done it!: "+line);
System.out.println ("Sucess after "+count+" words.");
System.exit(0);
}
}
catch(NoSuchAlgorithmException e) {
System.err.println("Error: Unsupported algorithm - "+algo);
System.exit(1);
}
}
infile.close();
System.out.println ("Unable to recover hash. Try using a better dictionary file.");
}//end of main
/**
* Prints the usage example and exits the program
*/
private static void usage() {
System.err.println ("Usage: "+PROGNAME+" [-a <algo>] <dictionary file>");
System.exit(1);
}
}//end of class
| rogeriopvl/HashRecovery | HashRecovery.java | 1,013 | /**
* Prints the usage example and exits the program
*/ | block_comment | en | false |
214544_19 | /**
* Server.java
* author: Yukun Jiang
* Date: April 05, 2023
*
* This is the implementation for the Server instance
* in our Two Phase Commit distributed consensus protocol
*
* The Server acts as the single only coordinator for the system
* and initiate, make decisions on various transaction commits
*/
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
public class Server implements ProjectLib.CommitServing, ProjectLib.MessageHandling {
/**
* Wrapper class for an outgoing CoordinatorMsg
* it tracks when this is sent
* and thus can be tracked if it has timed out and needs to be resent
*/
static class OutboundMsg {
public CoordinatorMsg msg;
public Long sent_time;
public String dest;
public OutboundMsg(CoordinatorMsg msg, String dest) {
this.msg = msg;
this.dest = dest;
this.sent_time = System.currentTimeMillis();
}
public boolean isExpired() {
return (System.currentTimeMillis() - this.sent_time) > TIMEOUT;
}
}
/* big data structure for persistent storage */
private TxnMasterLog log;
public static ProjectLib PL;
private static final String SEP = ":";
private static final int PARTICIPANT_IDX = 0;
private static final int FILENAME_IDX = 1;
private static final String MODE = "rws";
private static final String LOG_NAME = "LOG_COORDINATOR";
/* how often to check if outbound message has timeout */
private static final Long INTERVAL = 1000L;
/* the timeout threshold for a message since one-way latency is at most 3 seconds as specified */
private static final Long TIMEOUT = 6000L;
private final ConcurrentLinkedDeque<OutboundMsg> outboundMsgs;
/* protect the recovery stage upon re-booting */
private boolean finish_recovery = false;
private void timeMsg(CoordinatorMsg msg, String dest) {
outboundMsgs.addLast(new OutboundMsg(msg, dest));
}
/*
Main Loop for checking timeout messages
if a message is in Phase I prepare and has not received feedback
Coordinator think it's an implicit Denial and immediately abort
if a message is in Phase II requiring an ACK from participant
it must be resent until ACKed
*/
@SuppressWarnings("unchecked")
public void inspectTimeout() {
ArrayList<OutboundMsg> expired_msgs = new ArrayList<>();
synchronized (outboundMsgs) {
// prune the timing queue
for (OutboundMsg msg : outboundMsgs) {
if (msg.isExpired()) {
expired_msgs.add(msg);
}
}
outboundMsgs.removeAll(expired_msgs);
}
// deal with expired msgs
for (OutboundMsg msg : expired_msgs) {
TxnMasterRecord record = log.retrieveRecord(msg.msg.txn_id);
if (msg.msg.phase == TxnPhase.PHASE_I && record.status == TxnMasterRecord.Status.PREPARE) {
// deemed as implicit DENIAL
System.out.println("Server's txn=" + msg.msg.txn_id + " to Node " + msg.dest
+ " in Phase I has expired, deemed as DENIAL");
record.decision = TxnDecision.ABORT;
record.status = TxnMasterRecord.Status.DECISION;
record.outstanding_participants = (HashSet<String>) record.participants.clone();
flushLog(); // FLUSH LOG
resumeTxnPhaseII(record);
}
if (msg.msg.phase == TxnPhase.PHASE_II && record.status == TxnMasterRecord.Status.DECISION) {
// must continue resending until ACKed
System.out.println("Server's txn=" + msg.msg.txn_id + " to Node " + msg.dest
+ " in Phase II has expired, RESEND");
msg.msg.sendMyselfTo(PL, msg.dest);
timeMsg(msg.msg, msg.dest);
}
}
}
/* persistent log */
private synchronized void flushLog() {
Long start = System.currentTimeMillis();
try (FileOutputStream f = new FileOutputStream(LOG_NAME, false);
BufferedOutputStream b = new BufferedOutputStream(f);
ObjectOutputStream o = new ObjectOutputStream(b)) {
o.writeObject(log);
o.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
PL.fsync();
}
}
/* Upon recovery */
private synchronized TxnMasterLog loadLog() {
TxnMasterLog disk_log = null;
try (FileInputStream f = new FileInputStream(LOG_NAME);
BufferedInputStream b = new BufferedInputStream(f);
ObjectInputStream o = new ObjectInputStream(b)) {
disk_log = (TxnMasterLog) o.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return disk_log;
}
/* Continue Phase I of a txn */
private void resumeTxnPhaseI(TxnMasterRecord record) {
assert (record.status == TxnMasterRecord.Status.PREPARE);
ConcurrentHashMap<String, ArrayList<String>> distributed_sources = new ConcurrentHashMap<>();
/* split the sources into mapping based by per destination UserNode */
for (String source_file : record.sources) {
String[] source_and_file = source_file.split(SEP);
String participant = source_and_file[PARTICIPANT_IDX];
String file = source_and_file[FILENAME_IDX];
if (!distributed_sources.containsKey(participant)) {
distributed_sources.put(participant, new ArrayList<>());
}
distributed_sources.get(participant).add(file);
}
/* send outstanding messages */
for (String outstanding_participant : record.outstanding_participants) {
ArrayList<String> single_sources = distributed_sources.get(outstanding_participant);
String[] outstanding_sources = single_sources.toArray(new String[0]);
CoordinatorMsg msg = CoordinatorMsg.GeneratePhaseIMsg(
record.id, record.filename, record.img, outstanding_sources);
msg.sendMyselfTo(PL, outstanding_participant);
timeMsg(msg, outstanding_participant); // Under Timeout monitor
}
}
/* Continue Phase II of a txn */
private void resumeTxnPhaseII(TxnMasterRecord record) {
assert (record.decision != TxnDecision.UNDECIDED
&& record.status == TxnMasterRecord.Status.DECISION);
// trim all the outbound Phase I message for this txn
ArrayList<OutboundMsg> useless = new ArrayList<>();
synchronized (outboundMsgs) {
for (OutboundMsg msg : outboundMsgs) {
CoordinatorMsg inner_msg = msg.msg;
if (inner_msg.txn_id == record.id && inner_msg.phase == TxnPhase.PHASE_I) {
useless.add(msg);
}
}
outboundMsgs.removeAll(useless);
}
CoordinatorMsg msg = CoordinatorMsg.GeneratePhaseIIMsg(record.id, record.decision);
for (String destination : record.outstanding_participants) {
msg.sendMyselfTo(PL, destination);
timeMsg(msg, destination);
}
}
@SuppressWarnings("unchecked")
private void dealVote(String from, ParticipantMsg msg) {
assert (msg.phase == TxnPhase.PHASE_I);
TxnMasterRecord record = log.retrieveRecord(msg.txn_id);
if (record.status == TxnMasterRecord.Status.END) {
return;
}
if (record.status == TxnMasterRecord.Status.DECISION) {
// already made a decision, inform
CoordinatorMsg decision_msg = CoordinatorMsg.GeneratePhaseIIMsg(record.id, record.decision);
decision_msg.sendMyselfTo(PL, from);
timeMsg(decision_msg, from);
return;
}
if (msg.vote == TxnVote.DENIAL) {
// this txn is aborted for sure, move to Phase II
System.out.println("Server Aborts txn " + record.id);
record.decision = TxnDecision.ABORT;
record.status = TxnMasterRecord.Status.DECISION;
record.outstanding_participants = (HashSet<String>) record.participants.clone();
flushLog(); // FLUSH LOG
resumeTxnPhaseII(record);
return;
}
record.outstanding_participants.remove(from);
if (record.outstanding_participants.isEmpty()) {
// every participant has voted
if (record.decision == TxnDecision.UNDECIDED) {
record.decision = TxnDecision.COMMIT;
}
record.status = TxnMasterRecord.Status.DECISION;
record.outstanding_participants = (HashSet<String>) record.participants.clone();
// commit point to outside world
// might have a race after flushLog and before outwrite the img to disk, IGNORE for now
if (record.decision == TxnDecision.COMMIT) {
System.out.println("Server commits and saves collage " + record.filename);
try {
RandomAccessFile f = new RandomAccessFile(record.filename, MODE);
f.write(record.img);
f.close();
} catch (Exception e) {
e.printStackTrace();
}
}
flushLog(); // FLUSH LOG
// move to Phase II to distribute decision and collect ACK
resumeTxnPhaseII(record);
}
}
private void dealACK(String from, ParticipantMsg msg) {
assert (msg.phase == TxnPhase.PHASE_II);
TxnMasterRecord record = log.retrieveRecord(msg.txn_id);
assert (record.status != TxnMasterRecord.Status.PREPARE);
if (record.status == TxnMasterRecord.Status.END) {
// no more need for ACKs
return;
}
record.outstanding_participants.remove(from);
// flushLog(); // FLUSH LOG
if (record.outstanding_participants.isEmpty()) {
// all ACKs collected, this txn is completed
System.out.println("Server: txn " + record.id + " is ENDED");
record.status = TxnMasterRecord.Status.END;
flushLog(); // FLUSH LOG
synchronized (outboundMsgs) {
// prune all outbound messages for this txn
ArrayList<OutboundMsg> useless = new ArrayList<>();
for (OutboundMsg outboundMsg : outboundMsgs) {
if (outboundMsg.msg.txn_id == record.id) {
useless.add(outboundMsg);
}
}
outboundMsgs.removeAll(useless);
}
}
}
@SuppressWarnings("unchecked")
public void recover() {
if (new File(LOG_NAME).exists()) {
System.out.println("Server comes online with DISK log");
this.log = loadLog();
for (TxnMasterRecord record : this.log.all_txns.values()) {
if (record.status == TxnMasterRecord.Status.PREPARE) {
// ABORT
System.out.println("Serer Abort ongoing txn " + record.id);
record.decision = TxnDecision.ABORT;
record.status = TxnMasterRecord.Status.DECISION;
record.outstanding_participants = (HashSet<String>) record.participants.clone();
flushLog(); // FLUSH LOG
resumeTxnPhaseII(record);
} else if (record.status == TxnMasterRecord.Status.DECISION) {
System.out.println("Serer continue committed txn " + record.id);
resumeTxnPhaseII(record);
}
}
} else {
System.out.println("Server comes online with FRESH log");
this.log = new TxnMasterLog();
}
finish_recovery = true;
}
public Server() {
this.outboundMsgs = new ConcurrentLinkedDeque<>();
}
@Override
public boolean deliverMessage(ProjectLib.Message msg) {
while (!this.finish_recovery) {
} // guard recovery
String from = msg.addr;
ParticipantMsg participantMsg = ParticipantMsg.deserialize(msg);
System.out.println(
"Server Got message from " + msg.addr + " about Msg: " + participantMsg.toString());
if (participantMsg.phase == TxnPhase.PHASE_I) {
dealVote(from, participantMsg);
}
if (participantMsg.phase == TxnPhase.PHASE_II) {
dealACK(from, participantMsg);
}
return true;
}
@Override
public void startCommit(String filename, byte[] img, String[] sources) {
System.out.println(
"Server: Got request to commit " + filename + " with sources " + Arrays.toString(sources));
TxnMasterRecord new_record = log.createRecord(filename, img, sources);
flushLog(); // FLUSH LOG
resumeTxnPhaseI(new_record);
}
public static void main(String args[]) throws Exception {
if (args.length != 1)
throw new Exception("Need 1 arg: <port>");
Server srv = new Server();
PL = new ProjectLib(Integer.parseInt(args[0]), srv, srv);
srv.recover();
// main loop for inspecting timeout messages
while (true) {
Thread.sleep(INTERVAL);
srv.inspectTimeout();
}
}
}
| YukunJ/Two-Phase-Commit | 2pc/Server.java | 3,065 | // trim all the outbound Phase I message for this txn | line_comment | en | false |
214557_0 | import java.lang.Math;
public class EasyJoe {
public static void main(String[] args) {
long num = Long.parseLong(args[0]);
long multiple;
double answer = 0;
multiple = (long) (Math.log10(num) / Math.log10(2));
System.out.println(multiple);
answer = num - Math.pow(2, multiple);
System.out.println((long) answer);
answer = answer * 2 + 1;
/*
for (int n = 0; n < 100000; n++){
if (Math.pow(2, n) > num){
multiple = n - 1;
answer = num - Math.pow(2, multiple) ;
n = 100001;
}
}
*/
System.out.println("Soldier #" + (long) answer + " survives");
}
}
| Pingry-DS/josephus-problem-sun | EasyJoe.java | 220 | /*
for (int n = 0; n < 100000; n++){
if (Math.pow(2, n) > num){
multiple = n - 1;
answer = num - Math.pow(2, multiple) ;
n = 100001;
}
}
*/ | block_comment | en | true |
214682_15 | package poepassiveskilltreeoptimizer.Genetic;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
public class Genetic {
public static int popSize = 200; // 1000 builds
public static int stableGenerationToRestart = 2000;
public static int localGeneration = 300;
public static double crossoverProba = 0.85; // 80% chance when selecting 2 parents to generate 2 childs.
// If not (20%), keep the parents.
public static double mutationProba = 0.1; // 10% mutate (100)
public static double mutationMaxPropSize = 0.1; // They're mutating between 1 and 20% of nPoints : 1-10 [50]
public static double elitismProp = 0.04; // 3% elitism, i.e. we keep the best 3%
public static double newRandomGuysProp = 0.1; // 10% new random guys, i.e. we randomly create 10 builds
// public static int popSize = 100; // 1000 builds
// public static int stableGenerationToRestart = 200;
// public static int localGeneration = 100;
// public static double crossoverProba = 0.95; // 80% chance when selecting 2 parents to generate 2 childs.
// // If not (20%), keep the parents.
// public static double mutationProba = 0.05; // 10% mutate (100)
// public static double mutationMaxPropSize = 0.1; // They're mutating between 1 and 20% of nPoints : 1-10 [50]
// public static double elitismProp = 0.04; // 3% elitism, i.e. we keep the best 3%
// public static double newRandomGuysProp = 0.05; // 10% new random guys, i.e. we randomly create 10 builds
private static Random rand = new Random();
public static void optimalBuild(String poeClass, int level, int nPoints) {
int mutationMax = (int) (mutationMaxPropSize * nPoints);
int elitism = (int) (elitismProp * popSize);
int newRandGuys = (int) (newRandomGuysProp * popSize);
int crossovers = (popSize - elitism - newRandGuys) / 2;
Chromosome[] pop = new Chromosome[popSize];
for( int i=0 ; i<popSize ; i++ )
pop[i] = new Chromosome(poeClass, level, nPoints);
double globalmax = 0;
double max = 0;
int genMax = 0;
String toPrint = "";
// int nGen = 0;
// while( nGen++ < 1000 ){
while( true ){
Arrays.sort( pop );
if( max < pop[popSize-1].score ){
max = pop[popSize-1].score;
if( globalmax < max ){
globalmax = max;
toPrint = pop[popSize-1].build.toWrite + " [" + genMax + "] -> " + pop[popSize-1].build.getUrl();
System.out.println(toPrint);
// if( globalmax > 250 )
// System.exit(0);
}
genMax = 0;
pop[popSize-1] = pop[popSize-1].localOptimization( mutationMax, localGeneration );
} else if( genMax > stableGenerationToRestart ){
// System.out.println("Restart: " + toPrint);
genMax = 0;
max = 0;
for( int i=0 ; i<popSize ; i++ )
pop[i] = new Chromosome(poeClass, level, nPoints);
continue;
}
genMax++;
List<Chromosome> newPop = new ArrayList<>( popSize );
for( int i =0 ; i < elitism ; i++ )
newPop.add( pop[popSize-i-1] );
int totalScore = 0;
for( Chromosome c : pop )
totalScore += c.score;
for( int i=0 ; i < crossovers ; i++ ){
Chromosome c1 = selectionOne(pop, totalScore);
Chromosome c2 = selectionOne(pop, totalScore);
if( rand.nextDouble() > crossoverProba ){
newPop.add(c1);
newPop.add(c2);
} else {
Chromosome d1 = new Chromosome(c1, c2);
Chromosome d2 = new Chromosome(c1, c2);
if( rand.nextDouble() < mutationProba )
d1.mutation( rand.nextInt( mutationMax ) );
if( rand.nextDouble() < mutationProba )
d2.mutation( rand.nextInt( mutationMax ) );
newPop.add(d1);
newPop.add(d2);
}
}
while( newPop.size() != popSize )
newPop.add( new Chromosome(poeClass, level, nPoints) );
newPop.toArray( pop );
}
}
private static Chromosome selectionOne( Chromosome[] pop, int totalScore ){
int r = 1 + rand.nextInt(totalScore);
int a = 0;
for( Chromosome c : pop ){
a += c.score;
if( a >= r )
return c;
}
return null;
}
}
| jbigalet/POE-skill-tree-optimizer | Genetic/Genetic.java | 1,372 | // public static double newRandomGuysProp = 0.05; // 10% new random guys, i.e. we randomly create 10 builds | line_comment | en | true |
214713_3 | package comms;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
//done, untested --SecondThread
/**
* A class that handles the reading from and writing to SmartDashboard. <br>
* <br>
*
* Hope you guys like the comments<br>
* --SecondThread
*/
public class SmartWriter {
/**
* We usually only would want to print the first error that occurred, as
* that tends to cause other ones. Once an error is printed, the rest won't
* be so that the first one can be fixed.
*/
private static boolean stopPrintingErrors=false;
/**
* The maximum DebugMode for which messages are printed to SmartDashboard.
*/
private static DebugMode debugMode=DebugMode.DEBUG;
/**
* Sets the field with name <i>name</i> on the SmartDashboard to
* <i>value</i>. <br>
* <br>
* Preconditions: <i>debugMode</i> is at least as general as the debug mode
* that has been set. If this is not the case, nothing will be printed. <br>
*
* Postconditions: The value of the field with the name <i>name</i> on the
* SmartDashboard will be set to <i>value</i>.
*
* @param name
* The name of the field (the black bold text to the field's
* left)
* @param value
* The value of the field (the text in the text box for that
* field)
* @param debugMode
* The least general debug mode that this message should be
* displayed on.
*/
public static void putS(String name, String value, DebugMode debugMode) {
if (SmartWriter.debugMode.compareTo(debugMode) >= 0)
SmartDashboard.putString(name, value);
}
/**
* Sets the field with name <i>name</i> on the SmartDashboard to
* <i>value</i>. <br>
* <br>
* Preconditions: <i>debugMode</i> is at least as general as the debug mode
* that has been set. If this is not the case, nothing will be printed. <br>
*
* Postconditions: The value of the field with the name <i>name</i> on the
* SmartDashboard will be set to <i>value</i>.
*
* @param name
* The name of the field (the black bold text to the field's
* left)
* @param value
* The value of the field (the text in the text box for that
* field)
* @param debugMode
* The least general debug mode that this message should be
* displayed on
*/
public static void putB(String name, boolean value, DebugMode debugMode) {
if (SmartWriter.debugMode.compareTo(debugMode) >= 0)
SmartDashboard.putBoolean(name, value);
}
/**
* Sets the field with name <i>name</i> on the SmartDashboard to
* <i>value</i>. <br>
* <br>
* Preconditions: <i>debugMode</i> is at least as general as the debug mode
* that has been set. If this is not the case, nothing will be printed. <br>
*
* Postconditions: The value of the field with the name <i>name</i> on the
* SmartDashboard will be set to <i>value</i>.
*
* @param name
* The name of the field (the black bold text to the field's
* left)
* @param value
* The value of the field (the text in the text box for that
* field)
* @param debugMode
* The least general debug mode that this message should be
* displayed on.
*/
public static void putD(String name, double value, DebugMode debugMode) {
if (SmartWriter.debugMode.compareTo(debugMode) >= 0)
SmartDashboard.putNumber(name, value);
}
/**
* Sets the field with name <i>name</i> on the SmartDashboard to
* <i>value</i>. <br>
* <br>
* Preconditions: <i>debugMode</i> is at least as general as the debug mode
* that has been set. If this is not the case, nothing will be printed. <br>
*
* Postconditions: The value of the field with the name <i>name</i> on the
* SmartDashboard will be set to <i>value</i>.
*
* @param name
* The name of the field (the black bold text to the field's
* left)
* @param value
* The value of the field (the text in the text box for that
* field)
* @param debugMode
* The least general debug mode that this message should be
* displayed on.
*/
public static void putS(String name, String value) {
putS(name,value,DebugMode.DEBUG);
}
/**
* Sets the field with name <i>name</i> on the SmartDashboard to
* <i>value</i>. <br>
* <br>
* Preconditions: <i>debugMode</i> is at least as general as the debug mode
* that has been set. If this is not the case, nothing will be printed. <br>
*
* Postconditions: The value of the field with the name <i>name</i> on the
* SmartDashboard will be set to <i>value</i>.
*
* @param name
* The name of the field (the black bold text to the field's
* left)
* @param value
* The value of the field (the text in the text box for that
* field)
* @param debugMode
* The least general debug mode that this message should be
* displayed on
*/
public static void putB(String name, boolean value) {
putB(name,value,DebugMode.DEBUG);
}
/**
* Sets the field with name <i>name</i> on the SmartDashboard to
* <i>value</i>. <br>
* <br>
* Preconditions: <i>debugMode</i> is at least as general as the debug mode
* that has been set. If this is not the case, nothing will be printed. <br>
*
* Postconditions: The value of the field with the name <i>name</i> on the
* SmartDashboard will be set to <i>value</i>.
*
* @param name
* The name of the field (the black bold text to the field's
* left)
* @param value
* The value of the field (the text in the text box for that
* field)
* @param debugMode
* The least general debug mode that this message should be
* displayed on.
*/
public static void putD(String name, double value) {
putD(name,value,DebugMode.DEBUG);
}
/**
* Gets and returns the value in the text box on SmartDashboard with the
* given name.<br>
* <br>
* Preconditions: Exactly one text box with the the name <i>name</i> exists
* on SmartDashboard.<br>
*
* PostConditions: The value of the text box will be returned and nothing
* else will have been changed. <br>
*
* @param name
* The name of the text box of which the value should be returned
* @return The value in the text box with the name <i>name</i>
*/
public static String getS(String name) {
return SmartDashboard.getString(name, "");
}
/**
* Gets and returns the value in the text box on SmartDashboard with the
* given name.<br>
* <br>
* Preconditions: Exactly one text box with the the name <i>name</i> exists
* on SmartDashboard.<br>
*
* PostConditions: The value of the text box will be returned and nothing
* else will have been changed. <br>
*
* @param name
* The name of the text box of which the value should be returned
* @return The value in the text box with the name <i>name</i>
*/
public static boolean getB(String name) {
return SmartDashboard.getBoolean(name, false);
}
/**
* Gets and returns the value in the text box on SmartDashboard with the
* given name.<br>
* <br>
* Preconditions: Exactly one text box with the the name <i>name</i> exists
* on SmartDashboard.<br>
*
* PostConditions: The value of the text box will be returned and nothing
* else will have been changed. <br>
*
* @param name
* The name of the text box of which the value should be returned
* @return The value in the text box with the name <i>name</i>
*/
public static double getD(String name) {
return SmartDashboard.getNumber(name, 0);
}
/**
* Prints the error to standard output so it can be identified and debugged
*
* @param The
* exception that occurred
* @param The
* name of the time period that the exception occurred (i. e.
* Auto init) as a string to be printed
*/
public static void outputError(Exception e, String timeOccured) {
// We are going to try to print to Stdout, but I think this isn't going
// to work.
// If this doesn't work, then we can try:
// -printing to System.out instead of System.err
// -printing to using SmartWriter (This would be more difficult because
// Excetion.StackTrace would have to be converted to Strings)
if (!stopPrintingErrors) {
System.err.println("Exception occured in: "+timeOccured+".");
e.printStackTrace(System.err);
stopPrintingErrors=false;
}
}
} | 2202Programming/LogN | src/comms/SmartWriter.java | 2,375 | /**
* The maximum DebugMode for which messages are printed to SmartDashboard.
*/ | block_comment | en | true |
214853_0 | package garageSystem;
import java.util.Scanner;
import java.time.*;
import java.util.ArrayList;
public class Garage implements GarageInterface{
public Slot[] slotArray;
private int slotCount;
private String Configuration;
private boolean gate;
private int vehicleCount=0;
private static int totalIncome=0;
//public Vehicle[] vehiclesList;
Registration AuthenObject;
//private Authentication AuthenObject;
public Garage(int count){
slotCount = count;
}
public Garage(){
AuthenObject = new Registration();
AuthenObject.Authenticate();
slotCount = AuthenObject.getSlotCount();
slotArray = new Slot[slotCount];
for (int i=0; i<slotCount ; i+=1){
slotArray[i] = new Slot();
}
AuthenObject.setSlotDimensions(slotArray);
//slotArray = temp.slotArray;
Configuration = AuthenObject.setConfiguration();
}
public Slot getSlot(int i)
{
return slotArray[i];
}
public int getSlotCount(){
return slotCount;
}
public void SetConfiguration (String config){
Configuration = config;
}
public void setSlotCount(int count){
slotCount = count;
}
public String getConfiguration(){
return Configuration;
}
public int getVehicleCount(){
return vehicleCount;
}
public int getTotalIncome(){
return totalIncome;
}
public void setTotalIncome(int fees){
totalIncome += fees;
}
public void incrementVehiclesCount(){
vehicleCount += 1;
}
public void decrementVehiclesCount(){
vehicleCount -= 1;
}
}
| HoorAhmed1/Parking-Payment-System | Garage.java | 441 | //public Vehicle[] vehiclesList; | line_comment | en | true |
215012_3 | import java.util.*;
public class Cocktail {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int potions = sc.nextInt(); //num of potions
int t = sc.nextInt(); //time to drink each potion
int[] potionTimes = new int[potions];
for(int i=0; i<potions; i++){
potionTimes[i] = sc.nextInt();//each time duration of the potions
}
Arrays.sort(potionTimes);
int minimumTime = (potions-1)*t; //minimum time it requires for all potions to be in efect
boolean isCorrect = true; //if it passes or not
for(int i=potions-1; i>0; i--){
if(potionTimes[i] <= minimumTime){
isCorrect = false;
break;
}
else{
minimumTime -= t;
}
}
if(isCorrect)
System.out.println("YES");
else
System.out.println("NO");
}
}
| KalebCole/Kattis-Problems | Solved/Cocktail.java | 248 | //minimum time it requires for all potions to be in efect | line_comment | en | true |
215155_1 | /**
* Created by chrisnavy on 11/24/16.
*/
import javax.swing.*;
import java.awt.*;
import java.util.*;
/**
* Comprehensive Receipt that implements the Receipt Strategy
*/
public class ComprehensiveReceipt implements ReceiptStrategy {
private JFrame receiptFrame;
private JPanel namePanel;
private JPanel userIDPanel;
private JPanel reservedRoomsPanel;
private JPanel totalDuesPanel;
private int totalDue;
private ArrayList<Reservation> rooms;
private ArrayList<Integer> reserved;
/**
<<<<<<< HEAD
* Creates a new Comprehensive Receipt
* @param info information to be displayed on the receipt
=======
* Constructor to print the Receipt
* @param info Receipt information ArrayList
>>>>>>> d81bcc23db20cf4ff24ebf58d3b7dc653c9c0f23
*/
ComprehensiveReceipt(ArrayList info){
receiptFrame = new JFrame("Simple Receipt");
namePanel = new JPanel();
userIDPanel = new JPanel();
reservedRoomsPanel = new JPanel();
totalDuesPanel = new JPanel();
reservedRoomsPanel.setLayout(new GridLayout(0,1));
userIDPanel.add(new JLabel("User ID: "));
JTextArea userID = new JTextArea(info.get(0).toString());
userID.setEditable(false);
userIDPanel.add(userID);
reservedRoomsPanel.add(new JLabel("Rooms reserved: "));
reserved = (ArrayList<Integer>) info.get(2);
rooms = (ArrayList<Reservation>) info.get(1);
/**
* Reserved Room Text
*/
for(int i = 0; i < reserved.size(); i++){
JTextArea rm = new JTextArea(Integer.toString(reserved.get(i) + 1) + ": " + rooms.get(i).toString() );
rm.setEditable(false);
reservedRoomsPanel.add(rm);
}
/**
* total dues
*/
totalDuesPanel.add(new JLabel("Total Dues: "));
this.getTotalDues();
totalDuesPanel.add(new JLabel("$" + Integer.toString(totalDue)));
this.printReceipt();
}
/**
* Pop ups receipt of all the reservations.
*/
@Override
public void printReceipt() {
receiptFrame.setLayout(new BoxLayout(receiptFrame.getContentPane(), BoxLayout.Y_AXIS));
receiptFrame.add(namePanel);
receiptFrame.add(userIDPanel);
receiptFrame.add(reservedRoomsPanel);
receiptFrame.add(totalDuesPanel);
receiptFrame.pack();
receiptFrame.setVisible(true);
}
/**
* Updates the total price in field 'totalDue'
*/
@Override
public void getTotalDues() {
for(int i = 0; i < reserved.size(); i++){
int temp = reserved.get(i);
if(temp >= 10){
int add = 80 * rooms.get(i).getNumberOfDays(rooms.get(i).getStartDate(), rooms.get(i).getEndDate());
totalDue += add;
} else if(temp < 10){
int add = 200 * rooms.get(i).getNumberOfDays(rooms.get(i).getStartDate(), rooms.get(i).getEndDate());
totalDue += add;
}
}
}
}
| jonlikesapples/hotel-project | src/ComprehensiveReceipt.java | 778 | /**
* Comprehensive Receipt that implements the Receipt Strategy
*/ | block_comment | en | true |
215252_32 | import java.awt.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
///Interface to represent a shape
interface Shape {
void paint(Graphics g);
}
/// Concrete class representing a circle shape
class Circle implements Shape {
private int x, y, radius;
public Circle(int x, int y, int radius) {
this.x = x;
this.y = y;
this.radius = radius;
}
@Override
public void paint(Graphics g) {
// Set the color to blue
g.setColor(Color.blue);
// Draw a circle with center at (x,y) and r = radius
g.drawOval(x - radius, y - radius, 2 * radius, 2 * radius);
}
}
/// Conrete class representing a box shape
class Box implements Shape {
private int x, y, width, height;
public Box(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
@Override
public void paint(Graphics g) {
// Set the color to blue
g.setColor(Color.blue);
/// Draw a rectangle
g.drawRect(x, y, width, height);
}
}
/// Expert interface for creating shapes
interface Expert {
Shape creatShape(int x, int y, int size);
}
/// Concrete expert class for creating circles
class CircleExpert implements Expert {
@Override
public Shape creatShape(int x, int y, int size) {
return new Circle(x, y, size);
}
}
/// Concrete expert class for creating boxes
class BoxExpert implements Expert {
@Override
public Shape creatShape(int x, int y, int size) {
return new Box(x, y, size, size);
}
}
/// Collection of Shapes (composite)
class CollectionOfShapes implements Shape {
private List<Shape> shapesList = new ArrayList<>();
/// Add shapes to the collection
public void addShape(Shape shape) {
shapesList.add(shape);
}
/// Iterator implementation
@Override
public void paint(Graphics g) {
Iterator<Shape> it = shapesList.iterator();
while (it.hasNext()) {
it.next().paint(g);
}
}
}
/// Controller class responsible for handling shape-related actions
class DrawShapeController {
private String selectedShapeType;
private CollectionOfShapes shapes;
public DrawShapeController(CollectionOfShapes shapes) {
this.shapes = shapes;
}
/// Set the selected shape type
public void setSelectedShapeType(String shapeType) {
this.selectedShapeType = shapeType;
}
/// Handle mouse click on the canvas. This method creates shapes and adds it to
/// the list.
public void handleCanvasClick(int x, int y) {
/// Delegate the task to create shapes to the appropriate experts.
Expert expert;
if (selectedShapeType.equals("Circles")) {
expert = new CircleExpert();
} else if (selectedShapeType.equals("Boxes")) {
expert = new BoxExpert();
} else {
throw new IllegalArgumentException("Invalid shape type");
}
/// Create the shape using the expert and add it to the list
shapes.addShape(expert.creatShape(x, y, 30));
}
}
/// Canvas class to display shapes
class Canvas extends JPanel {
private CollectionOfShapes collectionOfShapes;
private DrawShapeController controller;
public Canvas(CollectionOfShapes collectionOfShapes, DrawShapeController controller) {
this.collectionOfShapes = collectionOfShapes;
this.controller = controller;
setupMouseListener();
}
private void setupMouseListener() {
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
/// When canvas is clicked, add a shape (either circle or box)
/// e.getX() and e.getY() gives the x-coordinate and y-coordinate of the mouse
/// click relative to the source component (Canvas).
controller.handleCanvasClick(e.getX(), e.getY());
repaint(); /// This method in Swing triggers call to paintComponent method.
}
});
}
/// Overriding the default paintComponent method from JPanel
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
/// Customize paint
collectionOfShapes.paint(g);
}
}
public class DrawShapeApp {
public static void main(String[] args) {
/// Using this utility function for thread-safe allowing components to be
/// synchronized while updating the GUI. It helps to avoid freezing or lagging
/// the GUI.
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Shape Drawer App");
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
CollectionOfShapes shapes = new CollectionOfShapes();
DrawShapeController controller = new DrawShapeController(shapes);
Canvas canvas = new Canvas(shapes, controller);
JButton circleButton = new JButton("Circle");
JButton boxButton = new JButton("Boxes");
circleButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
/// Set the selected shape type to "Circles"
controller.setSelectedShapeType("Circles");
}
});
boxButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
/// Set the selected shape type to "Circles"
controller.setSelectedShapeType("Boxes");
}
});
///// Creating buttons panel
JPanel buttonPanel = new JPanel();
buttonPanel.add(circleButton);
buttonPanel.add(boxButton);
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));
buttonPanel.setBackground(Color.white);
buttonPanel.setSize(300, 600);
/// Adding margin top - not needed but complements GUI.
buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
/// Adding components to the frame.
frame.setLayout(new BorderLayout());
frame.add(buttonPanel, BorderLayout.WEST);
frame.add(canvas, BorderLayout.CENTER);
frame.setVisible(true);
});
}
}
| anamolkhadka/DrawShapeEditor | DrawShapeApp.java | 1,517 | /// Adding margin top - not needed but complements GUI. | line_comment | en | true |
215267_2 | import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
/** JMenBar that shows options in the BorderFrame
* @author Jared Moore
* @version Nov 16, 2012
*/
public class MenuBar extends JMenuBar {
BorderFrame frame;
JMenuItem beginner = new JMenuItem("Beginner"), intermediate = new JMenuItem("Intermediate"), expert = new JMenuItem("Expert"),
custom = new JMenuItem("Custom"), scores = new JMenuItem("Scores"), hint = new JMenuItem("Hint");
/** Constructor for MenuBar
*/
public MenuBar(BorderFrame frame) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // changes the look a little, my system is themed so this looks pretty sweet
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException e) {
System.err.println("You have an issue"); // if one of these comes up, just comment out this block, your system has issues or does not have a look and feel (so no UI?)
e.printStackTrace();
System.exit(1);
}
this.frame = frame;
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic('F');
JMenu newGame = new JMenu("New");
newGame.setMnemonic('N');
Action l = new Action();
beginner.addActionListener(l);
beginner.setMnemonic('B');
intermediate.addActionListener(l);
intermediate.setMnemonic('I');
expert.addActionListener(l);
expert.setMnemonic('E');
custom.addActionListener(l);
custom.setMnemonic('C');
newGame.add(beginner);
newGame.add(intermediate);
newGame.add(expert);
newGame.add(custom);
fileMenu.add(newGame);
scores.setMnemonic('S');
scores.addActionListener(l);
fileMenu.add(scores);
add(fileMenu);
JMenu helpMenu = new JMenu("Help");
helpMenu.setMnemonic('H');
hint.addActionListener(l);
hint.setMnemonic('I');
helpMenu.add(hint);
add(helpMenu);
setVisible(true);
}
/** ActionListener for the menu items
* @author Jared Moore
* @version Nov 19, 2012
*/
private class Action implements ActionListener {
/* (non-Javadoc)
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(beginner)) {
frame.setVisible(false);
BorderFrame newGame = new BorderFrame(8, 8, 10); // set the old frame to invisible and make a new one
}
else if (e.getSource().equals(intermediate)) {
frame.setVisible(false);
BorderFrame newGame = new BorderFrame(16, 16, 40);
}
else if (e.getSource().equals(expert)) {
frame.setVisible(false);
BorderFrame newGame = new BorderFrame(30, 16, 99);
}
else if (e.getSource().equals(custom)) {
frame.setVisible(false);
String text = JOptionPane.showInputDialog("Enter the number of rows, columns, and mines, separated by spaces");
if (text == null)
return;
Scanner input = new Scanner(text);
BorderFrame newGame = new BorderFrame(Integer.parseInt(input.next()), Integer.parseInt(input.next()), Integer.parseInt(input.next()));
input.close();
}
else if (e.getSource().equals(hint))
frame.getPanel().showHint();
else if (e.getSource().equals(scores))
frame.getPanel().displayScores();
}
}
}
| jmoney4769/MineSweeper | src/MenuBar.java | 1,029 | // changes the look a little, my system is themed so this looks pretty sweet | line_comment | en | false |
215377_4 | package world;
/**
* Movable is an interface which assures that any object capable of moving from
* room to room has certain commands. It also acts as a marker for both Player
* and Mobile objects. It extends the DatabaseItem and GearList interfaces, as
* movables are database items and gear holders and share much in common with
* GearContainers. The are a GearList, in that respect as well as have a
* GearList instance variables.
*/
public interface Movable extends DatabaseItem, GearList {
/**
* sendToPlayer() is used to send text to the client of the player's
* controller directly if the movable is a player or send text to the mob if
* the movable is a mobile. If a mobile, the mobile can react the the text.
*
* @param message
* The message to be sent to the Player's console or the mob.
*/
public void sendToPlayer(String message);
/**
* Attack is the method called when a Mobile's turn comes up in a combat. A
* Mobile looks to it's strategy in order to determine an appropriate
* response - For many mobs, this response is to call resolveAttack, and
* deal damage to another Movable.
*
* @enemy - The Movable to attack.
*/
public void attack(Movable enemy);
/**
* The moveToRoom command handles the upkeep of a room movement by shiftign
* the Mobile object from one room to another, and then forms the String to
* be given to the Mobile after changing rooms. Mobiles need this less than
* players, but other behavior might depend on keywords in room
* descriptions, or a reaction to other DatabaseObjects in the room.
*
* @param destination
* This is a room reference for the destination of the move.
*/
public void moveToRoom(Room destination);
/**
* setStat is a universal setter. It accepts an integer and a Trait enum,
* which it then uses to change the appropriate private variable
* representing the requested stat to be changed. This cuts down on the
* number of methods required to set all instance variables.
*
* @param value
* The integer value one wishes to set.
* @param stat
* The enum member representing the stat the caller wishes
* modified.
*/
public void setStat(int value, Trait stat);
/**
* getStat is a universal getter. It accepts a Trait enum, which it then
* uses to get the appropriate private variable representing the requested
* stat requested. This cuts down on the number of methods required to get
* all instance variables.
*
* @return int - An int that represents the value of the requested stat.
*/
public int getStat(Trait stat);
/**
* use will be called whenever the movable wants to an item that they
* currently have. If a player does attempt to use something that they
* currently don't have the method will not do anything.
*
* @param itemName
* The name of the gear to be used
*/
public void use(String itemName);
/**
* This method insures the correct roomId of the movable, in case there is a
* synch or serialization issue.
*
* @return An int that represents the movables object reference id in the
* database.
*/
public int getRoomId();
/**
* getFighting is a small method that is used to prevent a player from
* getting into more than one fight at once. A MOB, however, can be attacked
* by multiple human players.
*
* @return True if fighting, false otherwise
*/
public boolean getFighting();
/**
* setFighting will be used once a player enters combat. It pass in a true
* value to set to the player's isFighting variable.
*
* @param fighting
* Ture if entering a fight, false if ending combat
*/
public void setFighting(boolean fighting);
}
| thezboe/Wasteland-MUD | world/Movable.java | 924 | /**
* setStat is a universal setter. It accepts an integer and a Trait enum,
* which it then uses to change the appropriate private variable
* representing the requested stat to be changed. This cuts down on the
* number of methods required to set all instance variables.
*
* @param value
* The integer value one wishes to set.
* @param stat
* The enum member representing the stat the caller wishes
* modified.
*/ | block_comment | en | false |
215382_4 | interface I1 {
void sum();
}
class I2 {
void sum() {
System.out.println("Class");
}
}
public class newWorld extends I2 implements I1 {
newWorld() {
super();
}
public void sum() {
System.out.println("Interfface");
}
public static int simpleInterest() {
int res = 1;
java.util.Scanner sc = new java.util.Scanner(System.in);
for (int i = 0; i < 3; i++) {
res *= (sc.nextInt());
}
return res / 100;
}
public static double areaCircle() {
java.util.Scanner sc = new java.util.Scanner(System.in);
int r = sc.nextInt();
return (r * 3.14 * r);
}
public static String checkEvenOdd() {
java.util.Scanner sc = new java.util.Scanner(System.in);
int r = sc.nextInt();
if (r % 2 == 0) {
return "Even";
}
return "Odd";
}
public static void universalTable() {
java.util.Scanner sc = new java.util.Scanner(System.in);
int r = sc.nextInt();
for (int i = 1; i < 11; i++) {
System.out.println(r + " x " + i + " = " + (r * i));
}
}
public static void vowel(char c) {
switch (c) {
case 'A':
case 'a':
case 'E':
case 'e':
case 'i':
case 'I':
case 'O':
case 'o':
case 'U':
case 'u':
System.out.println("Vowel");
break;
default:
System.out.println("Consonant");
}
}
// System.out.println(simpleInterest());
// System.out.println(areaCircle());
// System.out.println(checkEvenOdd());
// universalTable();
// vowel(args[0].charAt(0)); System.out.println((int) 'A');
public static void main(String args[]) {
newWorld n = new newWorld();
super.sum();
}
}
| jaymn-init/Wipro-Java-Full-Stack-Training | newWorld.java | 534 | // vowel(args[0].charAt(0)); System.out.println((int) 'A');
| line_comment | en | true |
215452_0 | import java.util.Objects;
public final class agk<T> implements Comparable<agk<?>> {
private final agl<T> a;
private final int b;
private final T c;
private long d;
protected agk(agl<T> $$0, int $$1, T $$2) {
this.a = $$0;
this.b = $$1;
this.c = $$2;
}
public int a(agk<?> $$0) {
int $$1 = Integer.compare(this.b, $$0.b);
if ($$1 != 0) {
return $$1;
} else {
int $$2 = Integer.compare(System.identityHashCode(this.a), System.identityHashCode($$0.a));
return $$2 != 0 ? $$2 : this.a.a().compare(this.c, $$0.c);
}
}
public boolean equals(Object $$0) {
if (this == $$0) {
return true;
} else if (!($$0 instanceof agk)) {
return false;
} else {
agk<?> $$1 = (agk)$$0;
return this.b == $$1.b && Objects.equals(this.a, $$1.a) && Objects.equals(this.c, $$1.c);
}
}
public int hashCode() {
return Objects.hash(new Object[]{this.a, this.b, this.c});
}
public String toString() {
return "Ticket[" + this.a + " " + this.b + " (" + this.c + ")] at " + this.d;
}
public agl<T> a() {
return this.a;
}
public int b() {
return this.b;
}
protected void a(long $$0) {
this.d = $$0;
}
protected boolean b(long $$0) {
long $$1 = this.a.b();
return $$1 != 0L && $$0 - this.d > $$1;
}
// $FF: synthetic method
public int compareTo(Object var1) {
return this.a((agk)var1);
}
}
| m-riss/Minecraft-Java-Reverse-Engineering | agk.java | 507 | // $FF: synthetic method | line_comment | en | true |
215656_5 | import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/food")
public class food extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// read form fields
int foodcost=0;
String foodId = request.getParameter("id");
if(foodId.equals("food1")){
foodcost=100;
}
else if(foodId.equals("food2")){
foodcost=150;
}
else if(foodId.equals("food3")){
foodcost=200;
}
// do some processing here...
try
{
int total= foodcost+book.cost;
PrintWriter writer = response.getWriter();
String htmlRespone = "<html>";
htmlRespone += "<center><div style='border:1px solid black; border-radius:3px; width:400px;'><h2>BILL</h2><hr><br/><h3>Tickets: " + book.cost + "</h3><h3>Food Combo: " + foodcost + "</h3><hr><h3>Total: " + total + "</h3><br></div></center>";
// htmlRespone += "<h2>Bill</h2><br/>";
// htmlRespone += "<h2>Tickets: "+ book.cost +"</h2><br/>";
// htmlRespone += "<h2>Food: "+ foodcost +"</h2><br/>";
// htmlRespone += "<h2>Total: "+ total +"</h2><br/>";
htmlRespone+="</html>";
writer.println(htmlRespone);
htmlRespone="<br><center><br><a href='user.jsp'><button>Back</button></a></center>";
writer.println(htmlRespone);
}
catch (Exception e)
{
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
}
} | karantatiwala/Online-Movie-Ticket-Booking-Portal | src/food.java | 521 | // htmlRespone += "<h2>Total: "+ total +"</h2><br/>"; | line_comment | en | true |
215924_1 | <action name="radioButton" class="br.com.projeto.action.RadioButtonAction" method="display">
<result name="none"> radioButton.jsp </result>
</action>
<action name="inputRadioButton" class="br.com.projeto.action.RadioButtonAction">
<result name="success">resultRadioButton.jsp </result>
</action>
//radioButton backend controller
package br.com.projeto.action;
public class RadioButtonAction extends ActionSupport {
private List<String> answer;
private String<Language> languages; // language list do tipo languages
private List<String> genders; // genders array list do tipo String
public RadioButtonAction() {
answer = new ArrayList<String>();
answer.add("Yes");
answer.add("No");
genders = new ArrayList<String>();
genders.add("Masculino");
genders.add("Feminino");
genders.add("Não Binário");
}
public String display () {
return NONE;
}
public String execute throws Exception() {
System.out.println("Executou Radio Button");
return "success";
}
}
//radioButton.jsp
<title>Radio Button </title>
<h1> Radio Button </h1>
<s:form action="inputRadioButton">
<s:radio label ="" name="answer" value="answe" list="answer"/>
<s:radio name="
<s:submit name="submit" key="submit"/>
</s:form>
//resultRadioButton
<title>Result Radio Button </title>
<h1> Result Radio Button </h1>
<h2>
<s:property value="youGender"/>
<s:property value="youLanguage"/>
<s:property value="youAnswer"/> </h2>
//Language.java
package br.com.projeto.model;
public class Language {
private String LanguageCode;
private String LanguageDisplay;
//ggas
private Language(String LanguageCode , String LanguageDisplay) {
LanguageCode = this.LanguageCode;
LanguagueDisplay = this.LanguageDisplay;
}
}
| rafaelfranco1/APACHESTRUTSIN2020JAVA | new 68.java | 537 | // language list do tipo languages
| line_comment | en | true |
216020_0 | import java.util.Comparator;
@FunctionalInterface
public interface FI extends ParentInterface{
int add(int a, int b, int c);
// int subtract(int a, int b, int c); // it became abstract
}
| piyush5807/JBDL-59 | L4_Streams/src/FI.java | 57 | // int subtract(int a, int b, int c); // it became abstract | line_comment | en | true |
216050_9 | import java.util.*;
/**
* FlipSolver.
*/
public class Solver {
/**
* Return the minimum number of indexes you have to flip to find the solution.
*
* @param values the game values.
* @return the indexes you have to flip to find the solution.
*/
public int[] solve(boolean[] values) {
/*
The algorithm tries all the possible solutions and chooses the one with the minimum answer.
It tries all the possible combinations of the cells to be flipped in the first row.
After flipping these cells we will have some another grid with different values than the
one given in the input. For this grid, we iterate over the rows from the second to the last one.
For each row, we iterate over the columns. For each column, we flip a cell if the cell above it
has a value true. This guarantees us that all cells in the above rows will be false after iterating
over all the columns in the current row. After iterating over all the rows we check if the last row
has all values of false, if yes, it means that this's a possible solution (because we already know
that the cells above the last row have values false). Then, we compare all the possible solutions, and
we chose the one with the minimum number of flips needed.
*/
// find the length/width of the grid by finding the square root of number of elements
int n = (int) Math.sqrt(values.length);
// create an array of booleans that will be modified in the while flipping the cells
boolean[] temp = new boolean[n * n];
// cost variable represents the optimal solution found so far
// maskAns variable represents the mask of the optimal solution found so far
int maskAns = 0, cost = 36, tempCost;
// try all possible combinations of the cells to be flipped from the first all
// a combination of cells indexes is called a mask
for (int mask = 0; mask < (1 << n); mask++) {
// initialize array temp to have the same values as the given input
System.arraycopy(values, 0, temp, 0, n * n);
// play a game according to the current mask
tempCost = play(temp, n, mask, cost);
// save the mask if it leads to a correct solution (all cells are false) with a
// less number of cells to be flipped
if (cost > tempCost && check(temp, n)) {
maskAns = mask;
cost = tempCost;
}
}
// create an array of integers to be returned
int ret[] = new int[cost];
// repeat the steps of playing a game for a specific mask but with saving the indexes of flipped cells in array ret
int index = 0;
System.arraycopy(values, 0, temp, 0, n * n);
for (int j = 0; j < n; j++) {
if ((maskAns & (1 << j)) > 0) {
flip(temp, j, n);
ret[index] = j;
index++;
}
}
for (int i = 1; i < n; i++) {
for (int j = 0; j < n; j++) {
if (temp[((i - 1) * n) + j]) {
flip(temp, (i * n) + j, n);
ret[index] = (i * n) + j;
index++;
}
}
}
// return the answer
return ret;
}
/**
* @param values the game values
* @param n the length/width of the square grid
* @param mask the combination of indexes from the first row to be flipped
* @param curCost the optimal solution found so far
* @return number of cells needed to be flipped
*/
private int play(boolean[] values, int n, int mask, int curCost) {
// number of cells needed to be flipped for the given arguments
int cost = 0;
// flip the cells of the first row according to the give mask
// break if the cost of this mask became more or equal to the optimal solution found so far
for (int j = 0; curCost >= cost && j < n; j++) {
// flip the index j if it exists in the given mask
if ((mask & (1 << j)) > 0) {
flip(values, j, n);
// increase number of flips needed
cost++;
}
}
// iterate over all cells between second and last row, and between first and last column
// break if the cost of this mask became more or equal to the optimal solution found so far
for (int i = 1; curCost >= cost && i < n; i++) {
for (int j = 0; curCost >= cost && j < n; j++) {
// flip the cell if the value of the cell above it is true
if (values[((i - 1) * n) + j]) {
// flip the cell in row i and column j (its index is ((i*n) + j))
flip(values, (i * n) + j, n);
// increase number of flips needed
cost++;
}
}
}
// return the number of cells needed to be flipped
return cost;
}
/**
* Check if all the cells in the last row of the grid are false
*
* @return true if all cells are false
*/
private boolean check(boolean[] values, int n) {
for (int i = 0; i < n; i++) {
// return false if at least one cell has a value true
if (values[(n * (n - 1)) + i])
return false;
}
return true;
}
/**
* In the given matrix, flip the value at the given index, and at the neighbours' indexes
* (up, down, left and right).
*
* @param matrix the matrix.
* @param index the index.
* @param cols the number of columns.
*/
public void flip(boolean[] matrix, int index, int cols) {
// first flip the index itself
matrix[index] = !matrix[index];
// next its neighbours
int[] neighbours = MatrixUtil.neighbours4(matrix.length, index, cols);
for (int neighbourIndex : neighbours) {
matrix[neighbourIndex] = !matrix[neighbourIndex];
}
}
/**
* Returns random, unique ints in the given range (inclusive).
*
* @param min minimum value.
* @param max maximum value.
* @return random, unique ints in the given range (inclusive).
*/
public static int[] randomIntegers(int min, int max, int num) {
List<Integer> list = new ArrayList<>();
for (int i = min; i <= max; i++) {
list.add(i);
}
Collections.shuffle(list);
int[] result = new int[num];
for (int i = 0; i < num; i++) {
result[i] = list.get(i);
}
return result;
}
} | epfl-dojo/flipsolver | src/main/java/Solver.java | 1,619 | // initialize array temp to have the same values as the given input | line_comment | en | false |
216082_0 | /*
Task from:
http://codeforces.com/problemset/problem/733/A?locale=en
"Grasshopper And the String"
One day, the Grasshopper was jumping on the lawn and found a piece of paper with a string.
Grasshopper became interested what is the minimum jump ability he should have in order to
be able to reach the far end of the string, jumping only on vowels of the English alphabet.
Jump ability is the maximum possible length of his jump.
Formally, consider that at the begginning the Grasshopper is located directly in front of
the leftmost character of the string. His goal is to reach the position right after the
rightmost character of the string. In one jump the Grasshopper could jump to the right any
distance from 1 to the value of his jump ability.
The following letters are vowels: 'A', 'E', 'I', 'O', 'U' and 'Y'.
Input
The first line contains non-empty string consisting of capital English letters.
It is guaranteed that the length of the string does not exceed 100.
Output
Print single integer a — the minimum jump ability of the Grasshopper (in the number of
symbols) that is needed to overcome the given string, jumping only on vowels.
Examples
input ABABBBACFEYUKOTT
output 4
input AAA
output 1
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String input = reader.readLine();
// A', 'E', 'I', 'O', 'U' и 'Y'.
int count = 1;
int maxCount = 1;
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == 'A'
|| input.charAt(i) == 'E'
|| input.charAt(i) == 'I'
|| input.charAt(i) == 'O'
|| input.charAt(i) == 'U'
|| input.charAt(i) == 'Y'){
count = 1;
} else {
count++;
}
if (maxCount < count){
maxCount = count;
}
}
if (!input.contains("A") && !input.contains("E") && !input.contains("I")
&& !input.contains("O") && !input.contains("U") && !input.contains("Y")){
System.out.println(input.length() + 1);
return;
}
System.out.println(maxCount);
}
}
| DanyloStasenko/IDEA_projects | codeforces_87/src/Main.java | 645 | /*
Task from:
http://codeforces.com/problemset/problem/733/A?locale=en
"Grasshopper And the String"
One day, the Grasshopper was jumping on the lawn and found a piece of paper with a string.
Grasshopper became interested what is the minimum jump ability he should have in order to
be able to reach the far end of the string, jumping only on vowels of the English alphabet.
Jump ability is the maximum possible length of his jump.
Formally, consider that at the begginning the Grasshopper is located directly in front of
the leftmost character of the string. His goal is to reach the position right after the
rightmost character of the string. In one jump the Grasshopper could jump to the right any
distance from 1 to the value of his jump ability.
The following letters are vowels: 'A', 'E', 'I', 'O', 'U' and 'Y'.
Input
The first line contains non-empty string consisting of capital English letters.
It is guaranteed that the length of the string does not exceed 100.
Output
Print single integer a — the minimum jump ability of the Grasshopper (in the number of
symbols) that is needed to overcome the given string, jumping only on vowels.
Examples
input ABABBBACFEYUKOTT
output 4
input AAA
output 1
*/ | block_comment | en | true |
216215_4 | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
*/
/* Small Finite Field arithmetic */
/* AMCL mod p functions */
public final class FP {
private final BIG x;
private static BIG p=new BIG(ROM.Modulus);
/* Constructors */
public FP(int a)
{
x=new BIG(a);
nres();
}
public FP()
{
x=new BIG(0);
}
public FP(BIG a)
{
x=new BIG(a);
nres();
}
public FP(FP a)
{
x=new BIG(a.x);
}
/* convert to string */
public String toString()
{
String s=redc().toString();
return s;
}
public String toRawString()
{
String s=x.toRawString();
return s;
}
/* convert to Montgomery n-residue form */
public void nres()
{
if (ROM.MODTYPE!=ROM.PSEUDO_MERSENNE)
{
DBIG d=new DBIG(x);
d.shl(ROM.NLEN*ROM.BASEBITS);
x.copy(d.mod(p));
}
}
/* convert back to regular form */
public BIG redc()
{
if (ROM.MODTYPE!=ROM.PSEUDO_MERSENNE)
{
DBIG d=new DBIG(x);
return BIG.mod(d);
}
else
{
BIG r=new BIG(x);
return r;
}
}
/* test this=0? */
public boolean iszilch() {
reduce();
return x.iszilch();
}
/* copy from FP b */
public void copy(FP b)
{
x.copy(b.x);
}
/* set this=0 */
public void zero()
{
x.zero();
}
/* set this=1 */
public void one()
{
x.one(); nres();
}
/* normalise this */
public void norm()
{
x.norm();
}
/* swap FPs depending on d */
public void cswap(FP b,int d)
{
x.cswap(b.x,d);
}
/* copy FPs depending on d */
public void cmove(FP b,int d)
{
x.cmove(b.x,d);
}
/* this*=b mod Modulus */
public void mul(FP b)
{
int ea=BIG.EXCESS(x);
int eb=BIG.EXCESS(b.x);
if ((ea+1)*(eb+1)+1>=ROM.FEXCESS) reduce();
DBIG d=BIG.mul(x,b.x);
x.copy(BIG.mod(d));
}
/* this*=c mod Modulus, where c is a small int */
public void imul(int c)
{
norm();
boolean s=false;
if (c<0)
{
c=-c;
s=true;
}
int afx=(BIG.EXCESS(x)+1)*(c+1)+1;
if (c<ROM.NEXCESS && afx<ROM.FEXCESS)
{
x.imul(c);
}
else
{
if (afx<ROM.FEXCESS) x.pmul(c);
else
{
DBIG d=x.pxmul(c);
x.copy(d.mod(p));
}
}
if (s) neg();
norm();
}
/* this*=this mod Modulus */
public void sqr()
{
DBIG d;
int ea=BIG.EXCESS(x);
if ((ea+1)*(ea+1)+1>=ROM.FEXCESS)
reduce();
d=BIG.sqr(x);
x.copy(BIG.mod(d));
}
/* this+=b */
public void add(FP b) {
x.add(b.x);
if (BIG.EXCESS(x)+2>=ROM.FEXCESS) reduce();
}
/* this = -this mod Modulus */
public void neg()
{
int sb,ov;
BIG m=new BIG(p);
norm();
ov=BIG.EXCESS(x);
sb=1; while(ov!=0) {sb++;ov>>=1;}
m.fshl(sb);
x.rsub(m);
if (BIG.EXCESS(x)>=ROM.FEXCESS) reduce();
}
/* this-=b */
public void sub(FP b)
{
FP n=new FP(b);
n.neg();
this.add(n);
}
/* this/=2 mod Modulus */
public void div2()
{
x.norm();
if (x.parity()==0)
x.fshr(1);
else
{
x.add(p);
x.norm();
x.fshr(1);
}
}
/* this=1/this mod Modulus */
public void inverse()
{
BIG r=redc();
r.invmodp(p);
x.copy(r);
nres();
}
/* return TRUE if this==a */
public boolean equals(FP a)
{
a.reduce();
reduce();
if (BIG.comp(a.x,x)==0) return true;
return false;
}
/* reduce this mod Modulus */
public void reduce()
{
x.mod(p);
}
/* return this^e mod Modulus */
public FP pow(BIG e)
{
int bt;
FP r=new FP(1);
e.norm();
x.norm();
FP m=new FP(this);
while (true)
{
bt=e.parity();
e.fshr(1);
if (bt==1) r.mul(m);
if (e.iszilch()) break;
m.sqr();
}
r.x.mod(p);
return r;
}
/* return sqrt(this) mod Modulus */
public FP sqrt()
{
reduce();
BIG b=new BIG(p);
if (ROM.MOD8==5)
{
b.dec(5); b.norm(); b.shr(3);
FP i=new FP(this); i.x.shl(1);
FP v=i.pow(b);
i.mul(v); i.mul(v);
i.x.dec(1);
FP r=new FP(this);
r.mul(v); r.mul(i);
r.reduce();
return r;
}
else
{
b.inc(1); b.norm(); b.shr(2);
return pow(b);
}
}
/* return jacobi symbol (this/Modulus) */
public int jacobi()
{
BIG w=redc();
return w.jacobi(p);
}
/*
public static void main(String[] args) {
BIG m=new BIG(ROM.Modulus);
BIG x=new BIG(3);
BIG e=new BIG(m);
e.dec(1);
System.out.println("m= "+m.nbits());
BIG r=x.powmod(e,m);
System.out.println("m= "+m.toString());
System.out.println("r= "+r.toString());
BIG.cswap(m,r,0);
System.out.println("m= "+m.toString());
System.out.println("r= "+r.toString());
// FP y=new FP(3);
// FP s=y.pow(e);
// System.out.println("s= "+s.toString());
} */
}
| brentzundel/incubator-milagro-crypto | java/FP.java | 2,229 | /* convert to string */ | block_comment | en | false |
216320_13 | import java.util.ArrayList;
import java.util.Collections;
public class Member {
private String username;
private String password;
private int status;
private String address;
private ArrayList<String> vehicles;
private int preference; //multiple preferences can be bits
private String firstName;
private String lastName;
private String cellNumber;
private String licenseNumber;
private String Email;
public Member(){
}
/**
* @return the username
*/
public String getUsername() {
return username;
}
/**
* @param username the username to set
*/
public void setUsername(String username) {
this.username = username;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* @return the firstName
*/
public String getFirstName() {
return firstName;
}
/**
* @param firstName the firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* @return the lastName
*/
public String getLastName() {
return lastName;
}
/**
* @param lastName the lastName to set
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* @return the cellNumber
*/
public String getCellNumber() {
return cellNumber;
}
/**
* @param cellNumber the cellNumber to set
*/
public void setCellNumber(String cellNumber) {
this.cellNumber = cellNumber;
}
/**
* Set Status of Member
* @param status 0 none, 1 passenger, 2 driver, 3 both
*/
public void setStatus(int status){
this.status = status;
}
/**
* Set Address of member
* @param addr Address of member
*/
public void setAddress(String addr){
this.address = addr;
}
/**
* Copy vehicles over into list of vehicles
* @param vehicles Initialize Vehicles
*/
public void setVehicles(ArrayList<String> vehicles){
Collections.copy(this.vehicles, vehicles);
}
/**
* Member's preference set
* @param preference
*/
public void setPreference(int preference){
this.preference = preference;
}
/**
* Get Status of member
* @return status
*/
public int getStatus(){
return this.status;
}
/**
* Get address of member
* @return member's address
*/
public String getAddress(){
return address;
}
/**
* List of vehicles owned by member
* @return a list of vehicles
*/
public ArrayList<String> getVehicles(){
return vehicles;
}
/**
* Preference of member
* @return member's preference
*/
public int getPreference(){
return this.preference;
}
/**
* Add new vehicle to list
* @param vehicle vehicle to be added
*/
public void addVehicle(String vehicle){
this.vehicles.add(vehicle);
}
/**
* @return the licenseNumber
*/
public String getLicenseNumber() {
return licenseNumber;
}
/**
* @param licenseNumber the licenseNumber to set
*/
public void setLicenseNumber(String licenseNumber) {
this.licenseNumber = licenseNumber;
}
public void setEmail(String email ) {
// TODO Auto-generated method stub
this.Email = email;
}
}
| jakubkalinowski/SJSU_SE133 | src/Member.java | 901 | /**
* Copy vehicles over into list of vehicles
* @param vehicles Initialize Vehicles
*/ | block_comment | en | false |
216347_5 | import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Floor1 implements Floor{
/** This floor is to park all non-electric 4 wheelers
* Has 200 parking spots, out of which the first 20 are reserved for handicapped
*/
final int MAX_SPOTS = 200;
// Creating a list of objects of class Parking Spot, which contains details of each spot.
List<ParkingSpot> spots = new ArrayList<>(MAX_SPOTS);
// Creating a boolean array to check if a given spot is vacant or not.
boolean[] spots_available =new boolean[MAX_SPOTS];
//Initially, marking all spots in the floor as available.
private void initialize_spots_available(){
for(int i=0; i<MAX_SPOTS; ++i){
spots_available[i] = true;
}
}
//Initializing the array list.
private void initialize_array_list(){
for(int i=0; i<MAX_SPOTS; ++i){
spots.add(i, null);
}
}
//Constructor initializes both the array and the list.
public Floor1() {
initialize_spots_available();
initialize_array_list();
}
@Override
public boolean isFull() {
boolean k = true;
for(int i=0; i<MAX_SPOTS; ++i){
if(spots_available[i]){
k = false;
break;
}
}
return k;
}
@Override
public void slotsAvailable() {
System.out.println("GENERAL PARKING SLOTS");
int cnt = 0;
for(int i=20; i<MAX_SPOTS; ++i){
if(spots_available[i]){
++cnt;
System.out.print(i+1 + " ");
}
if(cnt > 20) {
cnt = 0;
System.out.println();
}
}
}
@Override
public void display_entry_points() {
System.out.println("1. Handicapped Road");
System.out.println("2. South Gate Road");
System.out.println("3. North Gate Road");
System.out.println("4. East Gate Road");
}
@Override
public void display_exit_points() {
System.out.println("1. Handicapped Road");
System.out.println("2. South Gate Road");
System.out.println("3. North Gate Road");
System.out.println("4. East Gate Road");
}
@Override
public void display_reserved_spots() {
System.out.println("\nRESERVED FOR HANDICAPPED");
for(int i=0; i<20; ++i){
if(spots_available[i]){
System.out.print(i+1 + " ");
}
}
}
@Override
public Vehicle findVehicle(int slotno) {
return null;
}
@Override
public Date findDate(int slotno) {
return spots.get(slotno-1).getEntry();
}
@Override
public void clearSpots(int slotno) {
spots_available[slotno - 1] = true;
}
@Override
public void add_vehicle(ParkingSpot p) {
int slotno = p.getSlotNo();
if(spots_available[slotno-1]){
spots_available[slotno-1] = false;
spots.set(slotno-1,p);
}
}
@Override
public void vehicle_exit(int slotno) {
if(!spots_available[slotno-1]){
spots_available[slotno-1] = true;
spots.set(slotno-1,null);
}
}
@Override
public void display_vehicles_details() {
boolean isempty = false;
for(int i=0; i<MAX_SPOTS; ++i){
if(!spots_available[i]){
isempty = true;
Vehicle v = spots.get(i).getVehicle();
System.out.println(v.getName() + " - " + v.getLicenseNumber() + " - " + v.getColor() + " - " + spots.get(i).getEntry());
}
}
if(!isempty){
System.out.println("No vehicles parked yet!");
}
}
}
| CS21B043/PM-Team-8-Parking-Lot | Floor1.java | 1,049 | //Constructor initializes both the array and the list.
| line_comment | en | false |
216353_1 | public class Road {
private final Vehicle[] vehicles;
private int head = 0;
private int tail = 0;
private int count = 0;
public Road(int capacity)
{
vehicles = new Vehicle[capacity];
}
public synchronized boolean addVehicle(Vehicle vehicle)
{
boolean added = false;
if (count < vehicles.length)
{
vehicles[tail] = vehicle;
tail = (tail + 1) % vehicles.length;
count++;
added = true;
if (added)
{
//System.out.println("Vehicle added to road. Current road count: " + count);
}
}
return added;
}
public synchronized Vehicle consumeVehicle()
{
if (count > 0)
{
Vehicle vehicle = vehicles[head];
if (vehicle != null)
{
//System.out.println("Vehicle removed from road. Current road count: " + count);
}
head = (head + 1) % vehicles.length;
count--;
return vehicle;
}
return null;
}
public synchronized int getCount()
{
return count;
}
public synchronized boolean hasSpace()
{
return count < vehicles.length;
}
}
| hamzaehsan03/Road-Traffic-Concurrency-Assignment-Lite | Road.java | 276 | //System.out.println("Vehicle removed from road. Current road count: " + count); | line_comment | en | true |
216386_6 | // Kelas untuk showroom
public class Showroom {
private Vehicle[] vehicles; // Array kendaraan yang tersedia di showroom
private Seller seller; // Informasi penjual
// Konstruktor untuk menginisialisasi array kendaraan dan penjual
public Showroom(Vehicle[] vehicles, Seller seller) {
this.vehicles = vehicles;
this.seller = seller;
}
// Metode untuk menampilkan inventory showroom
public void displayInventory() {
for (Vehicle vehicle : vehicles) {
vehicle.displayDetails(); // Menampilkan detail kendaraan
System.out.println("--------------------");
}
}
// Metode untuk menampilkan informasi penjual
public void displaySellerInfo() {
System.out.println("Seller Name: " + seller.getName()); // Menampilkan nama penjual
System.out.println("Seller Contact: " + seller.getContactInfo()); // Menampilkan kontak penjual
}
// Metode untuk mendapatkan kendaraan berdasarkan indeks
public Vehicle getVehicle(int index) {
if (index >= 0 && index < vehicles.length) {
return vehicles[index]; // Mengembalikan kendaraan jika indeks valid
} else {
return null; // Mengembalikan null jika indeks tidak valid
}
}
}
| aryaintrn09/showroom | src/Showroom.java | 324 | // Metode untuk menampilkan informasi penjual | line_comment | en | true |
216551_1 | /*******************************************************************************
* @author Reika Kalseki
*
* Copyright 2017
*
* All rights reserved.
* Distribution of the software in any form is only allowed with
* explicit, prior permission from the owner.
******************************************************************************/
package Reika.GeoStrata;
import net.minecraft.world.World;
import Reika.DragonAPI.Instantiable.IO.SingleSound;
import Reika.DragonAPI.Instantiable.IO.SoundLoader;
public class GeoCommon {
public static final SingleSound iceWormTheme = new SingleSound("iceworm", "Reika/GeoStrata/iceworm.ogg");
protected static final SoundLoader sounds = new SoundLoader(iceWormTheme);
/**
* Client side only register stuff...
*/
public void registerRenderers()
{
//unused server side. -- see ClientProxy for implementation
}
public void addArmorRenders() {}
public World getClientWorld() {
return null;
}
public void registerRenderInformation() {
}
public void registerSounds() {
}
}
| ReikaKalseki/GeoStrata | GeoCommon.java | 258 | /**
* Client side only register stuff...
*/ | block_comment | en | true |
216953_4 | package com.company;
public class Ship {
//All ship types as enums
//BATTLESHIP (7, 9, 1, "Battleship"),
//CRUISER (5, 4, 1, "Cruiser"),
//DESTROYER (3, 1, 1, "Destroyer"),
//SUBMARINE (1, 1, 1, "Submarine");
//properties for ships
public final int length; //ship length
public final int damage; //ship damage
public final int points; //points for ship
public final String name; //name of ship
public boolean hit; //if the ship is hit or not
//constructor for the enum class
public Ship(int length, int damage, int points, String name){
this.length = length;
this.damage = damage;
this.points = points;
this.name = name;
this.hit = false;
}
}
class BattleShip extends Ship{
BattleShip(){
super(7, 9, 1, "Battleship");
}
}
class Cruiser extends Ship{
Cruiser(){
super(5, 4, 1, "Cruiser");
}
}
class Destroyer extends Ship{
Destroyer(){
super(3, 1, 1, "Destroyer");
}
}
class Submarine extends Ship{
Submarine(){
super(1, 1, 1, "Submarine");
}
} | RynBen31/Bataille-navale | Ship.java | 346 | //SUBMARINE (1, 1, 1, "Submarine");
| line_comment | en | true |
217271_6 |
public class GuitarHero {
public static String keyboard = "q2we4r5ty7u8i9op-[=zxdcfvgbnjmk,.;/' "; // String ends with a space
public static GuitarString[] ta;
public static char key;
public static void main(String[] args) {
ta = new GuitarString[keyboard.length()];
for(int i = 0; i<keyboard.length(); i++) {
ta[i] = new GuitarString(440*Math.pow(1.05956, i-25));
}
// Create two guitar strings, for concert A and C
/*double CONCERT_A = 440.0;
double CONCERT_C = CONCERT_A * Math.pow(2, 3.0/12.0);
GuitarString stringA = new GuitarString(CONCERT_A);
GuitarString stringC = new GuitarString(CONCERT_C);
*/
final double TEXT_POS_X = .2;
final double TEXT_POS_Y = .5;
StdDraw.text(TEXT_POS_X, TEXT_POS_Y, "Yay!");
play(ta);
}
private static void play(GuitarString[] t) { // the main input loop
while (true) {
int temp = 0;
// check if the user has typed a key, and, if so, process it
if (StdDraw.hasNextKeyTyped()) {
// the user types this character
key = StdDraw.nextKeyTyped();
if(keyboard.indexOf(String.valueOf(key))!=-1) {
temp = keyboard.indexOf(String.valueOf(key));
System.out.println(temp);
t[temp].pluck();
}
}
double sample = 0;
// compute the superposition of the samples
for(int i = 0; i<keyboard.length(); i++){
sample+=t[i].sample();
}
// send the result to standard audio
StdAudio.play(sample);
// advance the simulation of each guitar string by one step
for(int i = 0; i<keyboard.length(); i++){
t[i].tic();
}
}
}
}
| UnintentionalConsequences/Guitar-Hero | src/GuitarHero.java | 542 | // compute the superposition of the samples | line_comment | en | true |
217666_0 | import java.util.ArrayList;
import java.util.Scanner;
import java.util.Random;
public class Animales {
Scanner leer = new Scanner(System.in);
Random ran = new Random();
ArrayList<Animales> listaAnimales = new ArrayList<>();
private String tipoDeAnimal;
private String fechaDeNacimiento;
private String fechaLlegada;
private float peso;
private String frecuenciaDeAlimentacion;
private String tiposDeAlimentacion;
private ArrayList<String> enfermedades;
private int id;
private boolean vacunas;
public Animales(String tipoDeAnimal, int id, String fechaDeNacimiento, String fechaLlegada, float peso, String frecuenciaDeAlimentacion, String tiposDeAlimentacion, boolean vacunas) {
this.tipoDeAnimal = tipoDeAnimal;
this.id = id;
this.fechaDeNacimiento = fechaDeNacimiento;
this.fechaLlegada = fechaLlegada;
this.peso = peso;
this.frecuenciaDeAlimentacion = frecuenciaDeAlimentacion;
this.tiposDeAlimentacion = tiposDeAlimentacion;
this.vacunas = vacunas;
this.enfermedades = new ArrayList<>();
}
public Animales() {
//Este lo use para poder crear el objeto en main sin tener que mandar ningun atributo
}
public String getTipoDeAnimal() {
return tipoDeAnimal;
}
public int getId() {
return id;
}
public String getFechaDeNacimiento() {
return fechaDeNacimiento;
}
public String getFechaLlegada() {
return fechaLlegada;
}
public float getPeso() {
return peso;
}
public String getFrecuenciaDeAlimentacion() {
return frecuenciaDeAlimentacion;
}
public String getTiposDeAlimentacion() {
return tiposDeAlimentacion;
}
public boolean getVacunas() {
return vacunas;
}
public ArrayList<String> getEnfermedades() {
return enfermedades;
}
public void setEnfermedades(ArrayList<String> enfermedades) {
this.enfermedades = enfermedades;
}
public void RegistrarAnimal() {
System.out.print("Ingrese tipo de Animal:");
String tipoDeAnimal = leer.nextLine();
int id = ran.nextInt(200) + 1;
ValidarId(id);
System.out.print("\nIngrese fecha de nacimiento con el formato Dia/Mes/Año:");
String fechaDeNacimiento = leer.nextLine();
System.out.print("\nIngrese Fecha de llegada con el formato Dia/Mes/Año:");
String fechaLlegada = leer.nextLine();
System.out.print("\nIngrese peso:");
float peso = leer.nextFloat();
leer.nextLine();
System.out.print("\nIngrese Frecuencia de alimentacion:");
String frecuenciaDeAlimentacion = leer.nextLine();
System.out.print("\nIngrese tipos de alimentacion:");
String tiposDeAlimentacion = leer.nextLine();
System.out.print("\nTiene vacunas 'Si' No tiene vacunas 'No':");
String vac = leer.nextLine();
boolean vacunas = false;
if(vac.equals("Si")){
vacunas = true;
}
ArrayList<String> enfermedades = new ArrayList<>();
System.out.print("\nIngrese enfermedades, cuando acabe ingrese Fin:");
String enfermedad = leer.nextLine();
while (!enfermedad.equals("Fin")) {
enfermedades.add(enfermedad);
System.out.print("Ingrese enfermedad:");
enfermedad = leer.nextLine();
}
Animales animal = new Animales(tipoDeAnimal, id, fechaDeNacimiento, fechaLlegada, peso, frecuenciaDeAlimentacion, tiposDeAlimentacion, vacunas);
animal.setEnfermedades(enfermedades);
listaAnimales.add(animal);
}
public void MostrarAnimales() {
for (int i = 0; i < listaAnimales.size(); i++) {
Animales animal = listaAnimales.get(i);
System.out.printf("Tipo de animal:%s\nSu id:%d\nFecha de nacimiento:%s\nFecha de llegada:%s\nPeso:%.2fKg\nFrecuencia de alimentacion:%s\nTipos de alimentacion:%s\nVacunas:%b\n", animal.getTipoDeAnimal(), animal.getId(), animal.getFechaDeNacimiento(), animal.getFechaLlegada(), animal.getPeso(), animal.getFrecuenciaDeAlimentacion(), animal.getTiposDeAlimentacion(), animal.getVacunas());
ArrayList<String> enfermedades = animal.getEnfermedades();
for (int j = 0; j < enfermedades.size(); j++) {
System.out.printf("Enfermedad %d: %s\n", j + 1, enfermedades.get(j));
}
}
}
public void ValidarId(int id) {
for (int i = 0; i < listaAnimales.size(); i++) {
if (listaAnimales.get(i).getId() == id) {
id = ran.nextInt(200) + 1;
i = 0;
}
}
}
public void EliminarAnimal() {
for (int i = 0; i < listaAnimales.size(); i++) {
System.out.printf("\n%d Animal:%s\n ", i+1,listaAnimales.get(i).getTipoDeAnimal());
}
System.out.println("Ingrese el numero del animal a eliminar:");
int opcion = leer.nextInt();
listaAnimales.remove(opcion-1);
}
public void BuscarAnimalPorID(){
System.out.print("Ingrese el id del animal:");
int ID = leer.nextInt();
System.out.println();
for (int i = 0; i < listaAnimales.size(); i++) {
if(ID==listaAnimales.get(i).getId()){
System.out.printf("Tipo de animal:%s\nSu id:%d\nFecha de nacimiento:%s\nFecha de llegada:%s\nPeso:%.2fKg\nFrecuencia de alimentacion:%s\nTipos de alimentacion:%s\nVacunas:%b\n", listaAnimales.get(i).getTipoDeAnimal(), listaAnimales.get(i).getId(), listaAnimales.get(i).getFechaDeNacimiento(), listaAnimales.get(i).getFechaLlegada(), listaAnimales.get(i).getPeso(), listaAnimales.get(i).getFrecuenciaDeAlimentacion(), listaAnimales.get(i).getTiposDeAlimentacion(), listaAnimales.get(i).getVacunas());
Animales animal = listaAnimales.get(i);
ArrayList<String> enfermedades = animal.getEnfermedades();
for (int j = 0; j < enfermedades.size(); j++) {
System.out.printf("Enfermedad %d: %s\n", j + 1,enfermedades.get(j));
}
}
}
}
}
| Ar1sAlan1s/Zoologico | Animales.java | 1,809 | //Este lo use para poder crear el objeto en main sin tener que mandar ningun atributo | line_comment | en | true |
217738_1 | package oneWordOneLiner_Concept_DB;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter One Small One Liner Related to Sysnset.");
Random rand = new Random();
File file = new File(
"/home/tigerit/Desktop/OneWordLinerConcept_DB/senticnet5.txt");
File file_out = new File(
"/home/tigerit/Desktop/OneWordLinerConcept_DB/out.txt");
FileWriter fileWriter = new FileWriter(file_out);
Scanner scanner = null;
String userInputString = "";
String synDetected = "";
int randomNum;
while (true) {
// userInputString = "every year";
System.out.println("Enter a Small One Liner: ( _quit to exit. )");
scanner = new Scanner(System.in);
userInputString = scanner.nextLine();
userInputString = userInputString.toLowerCase();
if (userInputString.equals("_quit")) {
break;
}
String temp = "";
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String lineFromFile = scanner.nextLine();
// System.out.println("NextLine: " + lineFromFile );
String[] splitted_lineFromFile = lineFromFile.split("\\s*,\\s*");
for (int i = 0; i < splitted_lineFromFile.length; i++) {
// System.out.println(splitted_lineFromFile[i]);
}
for (int i = 0; i < splitted_lineFromFile.length; i++) {
if (userInputString.equals(splitted_lineFromFile[i])) {
temp += lineFromFile;
break;
}
}
}
String[] splitted = temp.split("\\s*,\\s*");
String[] synset = new String[splitted.length];
int cnt = 0;
for (int i = 0; i < splitted.length; i++) {
if (!userInputString.equals(splitted[i]) && splitted[i] != "") {
synset[cnt] = splitted[i];
cnt++;
}
}
if (cnt > 0) { /// If synset exists
// getting a synonymous representation other than query term
randomNum = rand.nextInt(cnt + 1);
synDetected = synset[randomNum];
// Impression Design Section
randomNum = rand.nextInt(8);
switch (randomNum) {
case 1:
System.out.println("I think its similar to " + synDetected);
break;
case 2:
System.out.println("You can also say " + synDetected);
break;
case 3:
System.out.println("I guess its comparable to " + synDetected);
break;
case 4:
System.out.println("Probably its much the same as " + synDetected);
break;
case 5:
System.out.println("Other related saying you can say " + synDetected);
break;
case 6:
System.out.println("Frog is thinking that its comparable to " + synDetected);
break;
case 7:
System.out.println("Frog's mind crossed with a similar idea " + synDetected);
break;
case 0:
System.out.println("Frog knows it you can also speak " + synDetected);
break;
}
} else {
System.out.println("UNDETECTED");
}
} /// While Loop: Session
scanner.close();
fileWriter.flush();
fileWriter.close();
System.out.println("\n\n\n\nPROGRAM ENDED");
}
}
| ShihabYasin/ImportantCodes | chat-bot/driver.java | 1,061 | // userInputString = "every year"; | line_comment | en | true |
218287_0 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ejercicio;
/**
*
* @author Sebestian
*/
public class Motorola {
private String Color;
private String Serial;
public String getColor() {
return Color;
}
public void setColor(String Color) {
this.Color = Color;
}
public String getSerial() {
return Serial;
}
public void setSerial(String Serial) {
this.Serial = Serial;
}
}
| adrian159/TrabajoGrupal | Ejercicio/src/ejercicio/Motorola.java | 147 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/ | block_comment | en | true |
218369_2 | /*
* Copyright (c) 2008-2009, Motorola, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* - Neither the name of the Motorola, Inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package javax.obex;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* The <code>Operation</code> interface provides ways to manipulate a single
* OBEX PUT or GET operation. The implementation of this interface sends OBEX
* packets as they are built. If during the operation the peer in the operation
* ends the operation, an <code>IOException</code> is thrown on the next read
* from the input stream, write to the output stream, or call to
* <code>sendHeaders()</code>.
* <P>
* <STRONG>Definition of methods inherited from <code>ContentConnection</code>
* </STRONG>
* <P>
* <code>getEncoding()</code> will always return <code>null</code>. <BR>
* <code>getLength()</code> will return the length specified by the OBEX Length
* header or -1 if the OBEX Length header was not included. <BR>
* <code>getType()</code> will return the value specified in the OBEX Type
* header or <code>null</code> if the OBEX Type header was not included.<BR>
* <P>
* <STRONG>How Headers are Handled</STRONG>
* <P>
* As headers are received, they may be retrieved through the
* <code>getReceivedHeaders()</code> method. If new headers are set during the
* operation, the new headers will be sent during the next packet exchange.
* <P>
* <STRONG>PUT example</STRONG>
* <P>
* <PRE>
* void putObjectViaOBEX(ClientSession conn, HeaderSet head, byte[] obj) throws IOException {
* // Include the length header
* head.setHeader(head.LENGTH, new Long(obj.length));
* // Initiate the PUT request
* Operation op = conn.put(head);
* // Open the output stream to put the object to it
* DataOutputStream out = op.openDataOutputStream();
* // Send the object to the server
* out.write(obj);
* // End the transaction
* out.close();
* op.close();
* }
* </PRE>
* <P>
* <STRONG>GET example</STRONG>
* <P>
* <PRE>
* byte[] getObjectViaOBEX(ClientSession conn, HeaderSet head) throws IOException {
* // Send the initial GET request to the server
* Operation op = conn.get(head);
* // Retrieve the length of the object being sent back
* int length = op.getLength();
* // Create space for the object
* byte[] obj = new byte[length];
* // Get the object from the input stream
* DataInputStream in = trans.openDataInputStream();
* in.read(obj);
* // End the transaction
* in.close();
* op.close();
* return obj;
* }
* </PRE>
*
* <H3>Client PUT Operation Flow</H3> For PUT operations, a call to
* <code>close()</code> the <code>OutputStream</code> returned from
* <code>openOutputStream()</code> or <code>openDataOutputStream()</code> will
* signal that the request is done. (In OBEX terms, the End-Of-Body header
* should be sent and the final bit in the request will be set.) At this point,
* the reply from the server may begin to be processed. A call to
* <code>getResponseCode()</code> will do an implicit close on the
* <code>OutputStream</code> and therefore signal that the request is done.
* <H3>Client GET Operation Flow</H3> For GET operation, a call to
* <code>openInputStream()</code> or <code>openDataInputStream()</code> will
* signal that the request is done. (In OBEX terms, the final bit in the request
* will be set.) A call to <code>getResponseCode()</code> will cause an implicit
* close on the <code>InputStream</code>. No further data may be read at this
* point.
* @hide
*/
public interface Operation {
/**
* Sends an ABORT message to the server. By calling this method, the
* corresponding input and output streams will be closed along with this
* object. No headers are sent in the abort request. This will end the
* operation since <code>close()</code> will be called by this method.
* @throws IOException if the transaction has already ended or if an OBEX
* server calls this method
*/
void abort() throws IOException;
/**
* Returns the headers that have been received during the operation.
* Modifying the object returned has no effect on the headers that are sent
* or retrieved.
* @return the headers received during this <code>Operation</code>
* @throws IOException if this <code>Operation</code> has been closed
*/
HeaderSet getReceivedHeader() throws IOException;
/**
* Specifies the headers that should be sent in the next OBEX message that
* is sent.
* @param headers the headers to send in the next message
* @throws IOException if this <code>Operation</code> has been closed or the
* transaction has ended and no further messages will be exchanged
* @throws IllegalArgumentException if <code>headers</code> was not created
* by a call to <code>ServerRequestHandler.createHeaderSet()</code>
* or <code>ClientSession.createHeaderSet()</code>
* @throws NullPointerException if <code>headers</code> if <code>null</code>
*/
void sendHeaders(HeaderSet headers) throws IOException;
/**
* Returns the response code received from the server. Response codes are
* defined in the <code>ResponseCodes</code> class.
* @see ResponseCodes
* @return the response code retrieved from the server
* @throws IOException if an error occurred in the transport layer during
* the transaction; if this object was created by an OBEX server
*/
int getResponseCode() throws IOException;
String getEncoding();
long getLength();
int getHeaderLength();
String getType();
InputStream openInputStream() throws IOException;
DataInputStream openDataInputStream() throws IOException;
OutputStream openOutputStream() throws IOException;
DataOutputStream openDataOutputStream() throws IOException;
void close() throws IOException;
void noEndofBody();
int getMaxPacketSize();
}
| gp-b2g/frameworks_base | obex/javax/obex/Operation.java | 1,829 | /**
* Sends an ABORT message to the server. By calling this method, the
* corresponding input and output streams will be closed along with this
* object. No headers are sent in the abort request. This will end the
* operation since <code>close()</code> will be called by this method.
* @throws IOException if the transaction has already ended or if an OBEX
* server calls this method
*/ | block_comment | en | false |
218373_3 | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package org.nfx.bluradw;
public final class R {
public static final class array {
public static final int dock_pack=0x7f050000;
public static final int icon_pack=0x7f050001;
}
public static final class attr {
}
public static final class bool {
public static final int config_desktop_indicator=0x7f090005;
public static final int config_drawerLabels=0x7f090003;
public static final int config_fadeDrawerLabels=0x7f090004;
public static final int config_new_selectors=0x7f090002;
/** ADWSettings theme config
*/
public static final int config_uiABBg=0x7f090001;
public static final int use_drawer_icons_bg=0x7f090000;
}
public static final class color {
/** Theme specific appearance settings
*/
public static final int bubble_color=0x7f070000;
public static final int bubble_text_color=0x7f070001;
public static final int desktop_indicator_color=0x7f070004;
public static final int drawer_text_color=0x7f070002;
public static final int folder_title_color=0x7f070003;
}
public static final class drawable {
public static final int all_apps_button=0x7f020000;
public static final int box_launcher_bottom=0x7f020001;
public static final int box_launcher_top=0x7f020002;
public static final int box_launcher_top_normal=0x7f020003;
public static final int box_launcher_top_pressed=0x7f020004;
public static final int box_launcher_top_selected=0x7f020005;
public static final int btn_search_dialog_voice=0x7f020006;
public static final int btn_search_dialog_voice_default=0x7f020007;
public static final int btn_search_dialog_voice_pressed=0x7f020008;
public static final int btn_search_dialog_voice_selected=0x7f020009;
public static final int com_android_browser_browseractivity=0x7f02000a;
public static final int com_android_calculator2_calculator=0x7f02000b;
public static final int com_android_contacts_dialtacts_activity=0x7f02000c;
public static final int com_android_vending_assetbrowseractivity=0x7f02000d;
public static final int com_android_vending_carrierchannelactivity=0x7f02000e;
public static final int com_android_vending_categorieswithappslistactivity=0x7f02000f;
public static final int com_android_vending_mydownloadsactivity=0x7f020010;
public static final int com_android_vending_tosactivity=0x7f020011;
public static final int com_google_android_apps_plus_phone_homeactivity=0x7f020012;
public static final int com_google_android_gm_conversationlistactivitygmail=0x7f020013;
public static final int com_google_android_music_com_android_music_activitymanagement_toplevelactivity=0x7f020014;
public static final int com_google_android_talk_signinginactivity=0x7f020015;
public static final int com_motorola_blur_alarmclock_alarmclock=0x7f020016;
public static final int com_motorola_camera_camcorder=0x7f020017;
public static final int com_motorola_camera_camera=0x7f020018;
public static final int com_motorola_cmp_homelistactivity=0x7f020019;
public static final int com_motorola_gallery=0x7f02001a;
public static final int com_twitter_android_hometabactivity=0x7f02001b;
public static final int delete_zone_selector=0x7f02001c;
public static final int dockbar=0x7f02001d;
public static final int dockbar_bg=0x7f02001e;
public static final int dockbar_selector=0x7f02001f;
public static final int dot_big=0x7f020020;
public static final int dot_small=0x7f020021;
public static final int focused_application_background=0x7f020022;
public static final int folder=0x7f020023;
public static final int folder_open=0x7f020024;
public static final int grid_selector=0x7f020025;
public static final int home_arrows_left=0x7f020026;
public static final int home_arrows_right=0x7f020027;
public static final int ic_delete=0x7f020028;
public static final int ic_launcher_folder=0x7f020029;
public static final int ic_launcher_folder_open=0x7f02002a;
public static final int lab2_bg=0x7f02002b;
public static final int lab_bg=0x7f02002c;
public static final int mab_bg=0x7f02002d;
public static final int org_adwfreak_launcher_launcher=0x7f02002e;
public static final int pager_dots=0x7f02002f;
public static final int pressed_application_background=0x7f020030;
public static final int rab2_bg=0x7f020031;
public static final int rab_bg=0x7f020032;
public static final int search_button_voice=0x7f020033;
public static final int shortcut_selector=0x7f020034;
public static final int square_normal=0x7f020035;
public static final int square_over=0x7f020036;
public static final int textfield_searchwidget=0x7f020037;
public static final int textfield_searchwidget_default=0x7f020038;
public static final int textfield_searchwidget_pressed=0x7f020039;
public static final int textfield_searchwidget_selected=0x7f02003a;
public static final int theme_icon=0x7f02003b;
public static final int theme_preview=0x7f02003c;
public static final int theme_wallpaper=0x7f02003d;
public static final int trash=0x7f02003e;
}
public static final class id {
public static final int icon_grid=0x7f0a0000;
}
public static final class integer {
public static final int bubble_radius=0x7f080000;
/** config_ab_scalefactor is a float value between 0.1 and 0.8. Set here the default .X (-1, 6 will become 7)
*/
public static final int config_ab_scale_factor=0x7f080004;
public static final int config_drawer_color=0x7f080003;
public static final int config_highlights_color=0x7f080001;
public static final int config_highlights_color_focus=0x7f080002;
}
public static final class layout {
public static final int main=0x7f030000;
}
public static final class string {
/** 1=top dots, 2=top slider, 3=bottom slider
*/
public static final int config_desktop_indicator_type=0x7f060002;
/** Force the theme to use an specific dock style
0=None, 1=3buttons, 2=5buttons, 3=1button
*/
public static final int main_dock_style=0x7f060003;
/** To devs, read here on howto format/style your descriptions
http://developer.android.com/intl/de/guide/topics/resources/string-resource.html#FormattingAndStyling
*/
public static final int theme_description=0x7f060001;
/** Theme properties
*/
public static final int theme_title=0x7f060000;
}
public static final class xml {
public static final int noshader=0x7f040000;
}
}
| wijee/blur-adw-theme | gen/org/nfx/bluradw/R.java | 2,348 | /** config_ab_scalefactor is a float value between 0.1 and 0.8. Set here the default .X (-1, 6 will become 7)
*/ | block_comment | en | true |
218464_0 | /* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* Project Info: http://plantuml.com
*
* If you like this project or if you find it useful, you can support us at:
*
* http://plantuml.com/patreon (only 1$ per month!)
* http://plantuml.com/paypal
*
* This file is part of Smetana.
* Smetana is a partial translation of Graphviz/Dot sources from C to Java.
*
* (C) Copyright 2009-2017, Arnaud Roques
*
* This translation is distributed under the same Licence as the original C program:
*
*************************************************************************
* Copyright (c) 2011 AT&T Intellectual Property
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: See CVS logs. Details at http://www.graphviz.org/
*************************************************************************
*
* THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC
* LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0]
*
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
*
* You may obtain a copy of the License at
*
* http://www.eclipse.org/legal/epl-v10.html
*
* 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 h;
import java.util.Arrays;
import java.util.List;
//2 bfyeakqg0xg9gqt8ssajorir5
public interface Agtag_t extends Agtag_s {
public static List<String> DEFINITION = Arrays.asList(
"typedef struct Agtag_s Agtag_t");
}
// typedef struct Agtag_s Agtag_t; | simonrw/plantuml-custom | src/h/Agtag_t.java | 563 | /* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* Project Info: http://plantuml.com
*
* If you like this project or if you find it useful, you can support us at:
*
* http://plantuml.com/patreon (only 1$ per month!)
* http://plantuml.com/paypal
*
* This file is part of Smetana.
* Smetana is a partial translation of Graphviz/Dot sources from C to Java.
*
* (C) Copyright 2009-2017, Arnaud Roques
*
* This translation is distributed under the same Licence as the original C program:
*
*************************************************************************
* Copyright (c) 2011 AT&T Intellectual Property
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: See CVS logs. Details at http://www.graphviz.org/
*************************************************************************
*
* THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC
* LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0]
*
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
*
* You may obtain a copy of the License at
*
* http://www.eclipse.org/legal/epl-v10.html
*
* 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.
*
*/ | block_comment | en | true |
218479_0 | /* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2020, Arnaud Roques
*
* Project Info: http://plantuml.com
*
* If you like this project or if you find it useful, you can support us at:
*
* http://plantuml.com/patreon (only 1$ per month!)
* http://plantuml.com/paypal
*
* This file is part of PlantUML.
*
* PlantUML is free software; you can redistribute it and/or modify it
* under the terms of the Eclipse Public License.
*
* THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC
* LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0]
*
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
*
* You may obtain a copy of the License at
*
* http://www.eclipse.org/legal/epl-v10.html
*
* 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.
*
*************************************************************************
* Copyright (c) 2011 AT&T Intellectual Property
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: See CVS logs. Details at http://www.graphviz.org/
*************************************************************************
*
*/
package h;
import java.util.Arrays;
import java.util.List;
import smetana.core.__ptr__;
//2 67szzzwvgx8wjittlg7atd5zm
public interface list_t extends __ptr__ {
public static List<String> DEFINITION = Arrays.asList(
"typedef struct list_s",
"{",
"item *first",
"item *last",
"}",
"list_t");
}
// typedef struct list_s { /* maintain head and tail ptrs for fast append */
// item *first;
// item *last;
// } list_t; | curtcox/plantuml | src/h/list_t.java | 613 | /* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2020, Arnaud Roques
*
* Project Info: http://plantuml.com
*
* If you like this project or if you find it useful, you can support us at:
*
* http://plantuml.com/patreon (only 1$ per month!)
* http://plantuml.com/paypal
*
* This file is part of PlantUML.
*
* PlantUML is free software; you can redistribute it and/or modify it
* under the terms of the Eclipse Public License.
*
* THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC
* LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0]
*
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
*
* You may obtain a copy of the License at
*
* http://www.eclipse.org/legal/epl-v10.html
*
* 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.
*
*************************************************************************
* Copyright (c) 2011 AT&T Intellectual Property
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: See CVS logs. Details at http://www.graphviz.org/
*************************************************************************
*
*/ | block_comment | en | true |
218741_0 | import java.util.Random;
import java.util.Scanner;
import java.time.Instant;
import java.time.Duration;
public class Lab02 {
public static String[] letterCode = {"A", "R", "N", "D", "C", "Q", "E", "G", "H", "I",
"L", "K", "M", "F", "P", "S", "T", "W", "Y", "V"};
public static String[] aminoAcids = {"alanine", "arginine", "asparagine", "aspartic acid", "cysteine",
"glutamine", "glutamic acid", "glycine", "histidine", "isoleucine",
"leucine", "lysine", "methionine", "phenylalanine", "proline",
"serine", "threonine", "tryptophan", "tyrosine", "valine"};
public static void main(String[] args) {
int score = 0;
Instant startTime = Instant.now();
while (Duration.between(startTime, Instant.now()).getSeconds() < 30) {
int randomIndex = getRandomIndex();
String aminoAcid = aminoAcids[randomIndex];
System.out.println("What is the one-letter code for the amino acid: " + aminoAcid + "?");
Scanner scanner = new Scanner(System.in);
String userInput = scanner.nextLine().trim().toUpperCase();
if (userInput.equals(letterCode[randomIndex])) {
System.out.println("That's correct!\n");
score++;
} else {
System.out.println("That's incorrect! The one letter code for " + aminoAcid + " is " + letterCode[randomIndex] + "\n");
break;
}
scanner.close();
}
System.out.println("Your score: " + score + "/" + aminoAcids.length);
}
static int getRandomIndex() {
Random random = new Random();
return random.nextInt(aminoAcids.length);
}
}
/*
* Discussion: I ran out of time before being able to dig into the extra credit tasks but just looking at my code
* vs ChatGPT's (AminoAcidQuiz.java), it looks like chatGPT actually over-complicated both the code and the underlying logic
* and employs a constant countdown method that is very distracting when taking the quiz. It did seem to meet all
* specifications for the assignment as far as I can tell but I can't say that I understand everything that its doing
* to achieve a similar result.
* The benefit that this countdown has over my code is that it immediately ends the quiz at the 30 second mark instead of
* checking for time after each new response.
*/ | AlexandraTew/HelloWorld | Lab02.java | 654 | /*
* Discussion: I ran out of time before being able to dig into the extra credit tasks but just looking at my code
* vs ChatGPT's (AminoAcidQuiz.java), it looks like chatGPT actually over-complicated both the code and the underlying logic
* and employs a constant countdown method that is very distracting when taking the quiz. It did seem to meet all
* specifications for the assignment as far as I can tell but I can't say that I understand everything that its doing
* to achieve a similar result.
* The benefit that this countdown has over my code is that it immediately ends the quiz at the 30 second mark instead of
* checking for time after each new response.
*/ | block_comment | en | false |
218807_6 | package com.lgren.rxsg.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author Lgren
* @since 2019-05-24
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class RankHero extends Model<RankHero> {
private static final long serialVersionUID = 1L;
/**
* 排名
*/
@TableId(value = "rank", type = IdType.AUTO)
private Integer rank;
/**
* 武将的ID
*/
private Integer hid;
/**
* 武将名
*/
private String name;
private String user;
/**
* 等级
*/
private Integer level;
/**
* 内政
*/
private Integer affairs;
/**
* 勇武
*/
private Integer bravery;
/**
* 智谋
*/
private Integer wisdom;
private Integer uid;
/**
* 统率
*/
private Integer command;
@Override
protected Serializable pkVal() {
return this.rank;
}
}
| ObservedObserver/rxsg-1 | src/main/java/com/lgren/rxsg/entity/RankHero.java | 342 | /**
* 勇武
*/ | block_comment | en | true |
218834_6 | package src.lab3_4.Zadanie_1;
import java.util.Random;
public class Dekker extends Thread {
private static final boolean[] desire = new boolean[2];
private static volatile int whosGoing = 0;
private final int nr;
private final int iterationCount;
private final char[] symbols = {'+', '-'};
private final boolean synchronizedMode;
Random random = new Random();
public Dekker(int nr, int iterationCount, boolean synchronizedMode) {
this.nr = nr;
this.iterationCount = iterationCount;
this.synchronizedMode = synchronizedMode;
}
private void personalAffairs() throws InterruptedException {
int sleepTime = random.nextInt(10) + 1; // Random time in range 1-10 ms
Thread.sleep(sleepTime);
}
void printSeparator() {
for (int i = 0; i < 100; i++) {
System.out.print(symbols[nr]);
}
System.out.println("\n");
}
private void criticalSection(int repetition) throws InterruptedException {
// System.out.println("Critical Section of thread " + (nr + 1) + ", nr powt. = " + repetition);
System.out.printf("Critical Section of thread %d, nr powt. = %d\n", nr + 1, repetition);
// var sb = new StringBuffer();
// sb.append("Critical Section of thread");
// sb.append(nr + 1);
// var result = sb.toString();
// System.out.print(STR."Critical Section of thread \{nr+1}, nr powt. = \{repetition}");
printSeparator();
}
private void notSynchronized() throws InterruptedException {
for (int i = 0; i < iterationCount; i++) {
personalAffairs();
criticalSection(i);
}
}
private void Synchronized() throws InterruptedException {
for (int i = 0; i < iterationCount; i++) {
personalAffairs();
desire[nr] = true;
while (desire[1 - nr]) {
if (whosGoing == 1 - nr) {
desire[nr] = false;
while (whosGoing == 1 - nr) {
// Active waiting
}
desire[nr] = true;
}
}
criticalSection(i);
whosGoing = 1 - nr;
desire[nr] = false;
}
}
@Override
public void run() {
try {
if (synchronizedMode) {
Synchronized();
} else {
notSynchronized();
}
} catch (InterruptedException e) {
System.out.println("Error caught: " + e);
}
}
}
| Floressek/concurrentLab_algorythms | lab_src/src/lab3_4/Zadanie_1/Dekker.java | 635 | // System.out.print(STR."Critical Section of thread \{nr+1}, nr powt. = \{repetition}"); | line_comment | en | true |
218870_2 | package com.lgren.rxsg.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author Lgren
* @since 2019-05-24
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class SysCityHero extends Model<SysCityHero> {
private static final long serialVersionUID = 1L;
/**
* 英雄ID
*/
@TableId(value = "hid", type = IdType.AUTO)
private Integer hid;
/**
* 归属哪个玩家,如果是NPC的话,为0
*/
private Integer uid;
/**
* 名字
*/
private String name;
private Integer npcid;
private Integer sex;
private Integer face;
/**
* 所属城池
*/
private Integer cid;
/**
* 状态:0,空闲;1,城守;2,出征,3,战斗,4,驻守,5,俘虏
*/
private Integer state;
/**
* 级别
*/
private Integer level;
/**
* 经验值
*/
private Integer exp;
/**
* 领将的统率
*/
private Integer commandBase;
/**
* 率统加成
*/
private Integer commandAddOn;
/**
* 内政
*/
private Integer affairsBase;
/**
* 勇武
*/
private Integer braveryBase;
/**
* 智谋
*/
private Integer wisdomBase;
private Integer affairsAdd;
private Integer braveryAdd;
private Integer wisdomAdd;
/**
* 政内加成
*/
private Integer affairsAddOn;
/**
* 勇武加成
*/
private Integer braveryAddOn;
/**
* 智谋加成
*/
private Integer wisdomAddOn;
/**
* 体力加成
*/
private Integer forceMaxAddOn;
/**
* 精力加成
*/
private Integer energyMaxAddOn;
/**
* 速度加成
*/
private Integer speedAddOn;
/**
* 攻击加成
*/
private Integer attackAddOn;
/**
* 防御加成
*/
private Integer defenceAddOn;
/**
* 忠诚
*/
private Integer loyalty;
/**
* 将领类型,0普通武将,1黄巾活动武将,2聚贤包开出武将,3-9圣诞武将
*/
private Integer herotype;
/**
* 状态:0,健康;1,重伤;2,修养
*/
private Integer heroHealth;
@Override
protected Serializable pkVal() {
return this.hid;
}
}
| ObservedObserver/rxsg-1 | src/main/java/com/lgren/rxsg/entity/SysCityHero.java | 739 | /**
* 归属哪个玩家,如果是NPC的话,为0
*/ | block_comment | en | true |
218876_8 | /*
* $Id: PDFXref.java,v 1.4 2009/02/12 13:53:56 tomoke Exp $
*
* Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle,
* Santa Clara, California 95054, U.S.A. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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 library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.sun.pdfview;
import net.sf.andpdf.refs.SoftReference;
/**
* a cross reference representing a line in the PDF cross referencing
* table.
* <p>
* There are two forms of the PDFXref, destinguished by absolutely nothing.
* The first type of PDFXref is used as indirect references in a PDFObject.
* In this type, the id is an index number into the object cross reference
* table. The id will range from 0 to the size of the cross reference
* table.
* <p>
* The second form is used in the Java representation of the cross reference
* table. In this form, the id is the file position of the start of the
* object in the PDF file. See the use of both of these in the
* PDFFile.dereference() method, which takes a PDFXref of the first form,
* and uses (internally) a PDFXref of the second form.
* <p>
* This is an unhappy state of affairs, and should be fixed. Fortunatly,
* the two uses have already been factored out as two different methods.
*
* @author Mike Wessler
*/
public class PDFXref {
private int id;
private int generation;
private boolean compressed;
// this field is only used in PDFFile.objIdx
private SoftReference<PDFObject> reference = null;
/**
* create a new PDFXref, given a parsed id and generation.
*/
public PDFXref(int id, int gen) {
this.id = id;
this.generation = gen;
this.compressed = false;
}
/**
* create a new PDFXref, given a parsed id, compressedObjId and index
*/
public PDFXref(int id, int gen, boolean compressed) {
this.id = id;
this.generation = gen;
this.compressed = compressed;
}
/**
* create a new PDFXref, given a sequence of bytes representing the
* fixed-width cross reference table line
*/
public PDFXref(byte[] line) {
if (line == null) {
id = -1;
generation = -1;
} else {
id = Integer.parseInt(new String(line, 0, 10));
generation = Integer.parseInt(new String(line, 11, 5));
}
compressed = false;
}
/**
* get the character index into the file of the start of this object
*/
public int getFilePos() {
return id;
}
/**
* get the generation of this object
*/
public int getGeneration() {
return generation;
}
/**
* get the generation of this object
*/
public int getIndex() {
return generation;
}
/**
* get the object number of this object
*/
public int getID() {
return id;
}
/**
* get compressed flag of this object
*/
public boolean getCompressed() {
return compressed;
}
/**
* Get the object this reference refers to, or null if it hasn't been
* set.
* @return the object if it exists, or null if not
*/
public PDFObject getObject() {
if (reference != null) {
return (PDFObject) reference.get();
}
return null;
}
/**
* Set the object this reference refers to.
*/
public void setObject(PDFObject obj) {
this.reference = new SoftReference<PDFObject>(obj);
}
}
| StEaLtHmAn/AndroidPDFViewerLibrary | src/com/sun/pdfview/PDFXref.java | 1,078 | /**
* get the generation of this object
*/ | block_comment | en | false |
219175_0 | /*In a game of Geekland there are there are N (N>1) robots standing in a straight line each one holding a gun and having some health. At time t = 0, all the robots start firing bullets from their gun at a rate of one bullet per second towards their right. Bullets are designed in such a way that they can travel any distance in one second.
You are also given a power array, power[i] denotes the power of each bullet of ith robot. Basically, if any robot j is hit by ith robot then j's power decreases by power[i]. If health of any robot becomes less than one then that robot dies and vanishes from that point and the next robot (if present) becomes the neighbour the of previous robot.
Given health and power of bullets of each robot, you need to tell minimum time in which N-1 robots will die (obviously the first robot will never die). */
class Main {
public static void main(String[] args) {
int[] health = { 4, 5, 2, 6};
int[] power = {1,3,2,3};
int n = health.length;
int[] time = new int[n];
int max = 0;
for (int i = 0; i < n; i++) {
time[i] = (int) Math.ceil((double) health[i] / power[i]);
if (time[i] > max) {
max = time[i];
}
}
System.out.println(max);
}
} | Annihilator544/bug-free-robot | Main.java | 359 | /*In a game of Geekland there are there are N (N>1) robots standing in a straight line each one holding a gun and having some health. At time t = 0, all the robots start firing bullets from their gun at a rate of one bullet per second towards their right. Bullets are designed in such a way that they can travel any distance in one second.
You are also given a power array, power[i] denotes the power of each bullet of ith robot. Basically, if any robot j is hit by ith robot then j's power decreases by power[i]. If health of any robot becomes less than one then that robot dies and vanishes from that point and the next robot (if present) becomes the neighbour the of previous robot.
Given health and power of bullets of each robot, you need to tell minimum time in which N-1 robots will die (obviously the first robot will never die). */ | block_comment | en | true |
220022_3 | /*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package java.util;
/**
* A collection that contains no duplicate elements. More formally, sets
* contain no pair of elements <code>e1</code> and <code>e2</code> such that
* <code>e1.equals(e2)</code>, and at most one null element. As implied by
* its name, this interface models the mathematical <i>set</i> abstraction.
*
* <p>The <tt>Set</tt> interface places additional stipulations, beyond those
* inherited from the <tt>Collection</tt> interface, on the contracts of all
* constructors and on the contracts of the <tt>add</tt>, <tt>equals</tt> and
* <tt>hashCode</tt> methods. Declarations for other inherited methods are
* also included here for convenience. (The specifications accompanying these
* declarations have been tailored to the <tt>Set</tt> interface, but they do
* not contain any additional stipulations.)
*
* <p>The additional stipulation on constructors is, not surprisingly,
* that all constructors must create a set that contains no duplicate elements
* (as defined above).
*
* <p>Note: Great care must be exercised if mutable objects are used as set
* elements. The behavior of a set is not specified if the value of an object
* is changed in a manner that affects <tt>equals</tt> comparisons while the
* object is an element in the set. A special case of this prohibition is
* that it is not permissible for a set to contain itself as an element.
*
* <p>Some set implementations have restrictions on the elements that
* they may contain. For example, some implementations prohibit null elements,
* and some have restrictions on the types of their elements. Attempting to
* add an ineligible element throws an unchecked exception, typically
* <tt>NullPointerException</tt> or <tt>ClassCastException</tt>. Attempting
* to query the presence of an ineligible element may throw an exception,
* or it may simply return false; some implementations will exhibit the former
* behavior and some will exhibit the latter. More generally, attempting an
* operation on an ineligible element whose completion would not result in
* the insertion of an ineligible element into the set may throw an
* exception or it may succeed, at the option of the implementation.
* Such exceptions are marked as "optional" in the specification for this
* interface.
*
* <p>This interface is a member of the
* <a href="{@docRoot}/../technotes/guides/collections/index.html">
* Java Collections Framework</a>.
*
* @param <E> the type of elements maintained by this set
*
* @author Josh Bloch
* @author Neal Gafter
* @see Collection
* @see List
* @see SortedSet
* @see HashSet
* @see TreeSet
* @see AbstractSet
* @see Collections#singleton(java.lang.Object)
* @see Collections#EMPTY_SET
* @since 1.2
*
* Set标准接口
*/
public interface Set<E> extends Collection<E> {
// Query Operations
/**
* Returns the number of elements in this set (its cardinality). If this
* set contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
* <tt>Integer.MAX_VALUE</tt>.
*
* @return the number of elements in this set (its cardinality)
*/
int size();
/**
* Returns <tt>true</tt> if this set contains no elements.
*
* @return <tt>true</tt> if this set contains no elements
*/
boolean isEmpty();
/**
* Returns <tt>true</tt> if this set contains the specified element.
* More formally, returns <tt>true</tt> if and only if this set
* contains an element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>.
*
* @param o element whose presence in this set is to be tested
* @return <tt>true</tt> if this set contains the specified element
* @throws ClassCastException if the type of the specified element
* is incompatible with this set
* (<a href="Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if the specified element is null and this
* set does not permit null elements
* (<a href="Collection.html#optional-restrictions">optional</a>)
*/
boolean contains(Object o);
/**
* Returns an iterator over the elements in this set. The elements are
* returned in no particular order (unless this set is an instance of some
* class that provides a guarantee).
*
* @return an iterator over the elements in this set
*/
Iterator<E> iterator();
/**
* Returns an array containing all of the elements in this set.
* If this set makes any guarantees as to what order its elements
* are returned by its iterator, this method must return the
* elements in the same order.
*
* <p>The returned array will be "safe" in that no references to it
* are maintained by this set. (In other words, this method must
* allocate a new array even if this set is backed by an array).
* The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all the elements in this set
*/
Object[] toArray();
/**
* Returns an array containing all of the elements in this set; the
* runtime type of the returned array is that of the specified array.
* If the set fits in the specified array, it is returned therein.
* Otherwise, a new array is allocated with the runtime type of the
* specified array and the size of this set.
*
* <p>If this set fits in the specified array with room to spare
* (i.e., the array has more elements than this set), the element in
* the array immediately following the end of the set is set to
* <tt>null</tt>. (This is useful in determining the length of this
* set <i>only</i> if the caller knows that this set does not contain
* any null elements.)
*
* <p>If this set makes any guarantees as to what order its elements
* are returned by its iterator, this method must return the elements
* in the same order.
*
* <p>Like the {@link #toArray()} method, this method acts as bridge between
* array-based and collection-based APIs. Further, this method allows
* precise control over the runtime type of the output array, and may,
* under certain circumstances, be used to save allocation costs.
*
* <p>Suppose <tt>x</tt> is a set known to contain only strings.
* The following code can be used to dump the set into a newly allocated
* array of <tt>String</tt>:
*
* <pre>
* String[] y = x.toArray(new String[0]);</pre>
*
* Note that <tt>toArray(new Object[0])</tt> is identical in function to
* <tt>toArray()</tt>.
*
* @param a the array into which the elements of this set are to be
* stored, if it is big enough; otherwise, a new array of the same
* runtime type is allocated for this purpose.
* @return an array containing all the elements in this set
* @throws ArrayStoreException if the runtime type of the specified array
* is not a supertype of the runtime type of every element in this
* set
* @throws NullPointerException if the specified array is null
*/
<T> T[] toArray(T[] a);
// Modification Operations
/**
* Adds the specified element to this set if it is not already present
* (optional operation). More formally, adds the specified element
* <tt>e</tt> to this set if the set contains no element <tt>e2</tt>
* such that
* <tt>(e==null ? e2==null : e.equals(e2))</tt>.
* If this set already contains the element, the call leaves the set
* unchanged and returns <tt>false</tt>. In combination with the
* restriction on constructors, this ensures that sets never contain
* duplicate elements.
*
* <p>The stipulation above does not imply that sets must accept all
* elements; sets may refuse to add any particular element, including
* <tt>null</tt>, and throw an exception, as described in the
* specification for {@link Collection#add Collection.add}.
* Individual set implementations should clearly document any
* restrictions on the elements that they may contain.
*
* @param e element to be added to this set
* @return <tt>true</tt> if this set did not already contain the specified
* element
* @throws UnsupportedOperationException if the <tt>add</tt> operation
* is not supported by this set
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this set
* @throws NullPointerException if the specified element is null and this
* set does not permit null elements
* @throws IllegalArgumentException if some property of the specified element
* prevents it from being added to this set
*/
boolean add(E e);
/**
* Removes the specified element from this set if it is present
* (optional operation). More formally, removes an element <tt>e</tt>
* such that
* <tt>(o==null ? e==null : o.equals(e))</tt>, if
* this set contains such an element. Returns <tt>true</tt> if this set
* contained the element (or equivalently, if this set changed as a
* result of the call). (This set will not contain the element once the
* call returns.)
*
* @param o object to be removed from this set, if present
* @return <tt>true</tt> if this set contained the specified element
* @throws ClassCastException if the type of the specified element
* is incompatible with this set
* (<a href="Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if the specified element is null and this
* set does not permit null elements
* (<a href="Collection.html#optional-restrictions">optional</a>)
* @throws UnsupportedOperationException if the <tt>remove</tt> operation
* is not supported by this set
*/
boolean remove(Object o);
// Bulk Operations
/**
* Returns <tt>true</tt> if this set contains all of the elements of the
* specified collection. If the specified collection is also a set, this
* method returns <tt>true</tt> if it is a <i>subset</i> of this set.
*
* @param c collection to be checked for containment in this set
* @return <tt>true</tt> if this set contains all of the elements of the
* specified collection
* @throws ClassCastException if the types of one or more elements
* in the specified collection are incompatible with this
* set
* (<a href="Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if the specified collection contains one
* or more null elements and this set does not permit null
* elements
* (<a href="Collection.html#optional-restrictions">optional</a>),
* or if the specified collection is null
* @see #contains(Object)
*/
boolean containsAll(Collection<?> c);
/**
* Adds all of the elements in the specified collection to this set if
* they're not already present (optional operation). If the specified
* collection is also a set, the <tt>addAll</tt> operation effectively
* modifies this set so that its value is the <i>union</i> of the two
* sets. The behavior of this operation is undefined if the specified
* collection is modified while the operation is in progress.
*
* @param c collection containing elements to be added to this set
* @return <tt>true</tt> if this set changed as a result of the call
*
* @throws UnsupportedOperationException if the <tt>addAll</tt> operation
* is not supported by this set
* @throws ClassCastException if the class of an element of the
* specified collection prevents it from being added to this set
* @throws NullPointerException if the specified collection contains one
* or more null elements and this set does not permit null
* elements, or if the specified collection is null
* @throws IllegalArgumentException if some property of an element of the
* specified collection prevents it from being added to this set
* @see #add(Object)
*/
boolean addAll(Collection<? extends E> c);
/**
* Retains only the elements in this set that are contained in the
* specified collection (optional operation). In other words, removes
* from this set all of its elements that are not contained in the
* specified collection. If the specified collection is also a set, this
* operation effectively modifies this set so that its value is the
* <i>intersection</i> of the two sets.
*
* @param c collection containing elements to be retained in this set
* @return <tt>true</tt> if this set changed as a result of the call
* @throws UnsupportedOperationException if the <tt>retainAll</tt> operation
* is not supported by this set
* @throws ClassCastException if the class of an element of this set
* is incompatible with the specified collection
* (<a href="Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if this set contains a null element and the
* specified collection does not permit null elements
* (<a href="Collection.html#optional-restrictions">optional</a>),
* or if the specified collection is null
* @see #remove(Object)
*/
boolean retainAll(Collection<?> c);
/**
* Removes from this set all of its elements that are contained in the
* specified collection (optional operation). If the specified
* collection is also a set, this operation effectively modifies this
* set so that its value is the <i>asymmetric set difference</i> of
* the two sets.
*
* @param c collection containing elements to be removed from this set
* @return <tt>true</tt> if this set changed as a result of the call
* @throws UnsupportedOperationException if the <tt>removeAll</tt> operation
* is not supported by this set
* @throws ClassCastException if the class of an element of this set
* is incompatible with the specified collection
* (<a href="Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if this set contains a null element and the
* specified collection does not permit null elements
* (<a href="Collection.html#optional-restrictions">optional</a>),
* or if the specified collection is null
* @see #remove(Object)
* @see #contains(Object)
*/
boolean removeAll(Collection<?> c);
/**
* Removes all of the elements from this set (optional operation).
* The set will be empty after this call returns.
*
* @throws UnsupportedOperationException if the <tt>clear</tt> method
* is not supported by this set
*/
void clear();
// Comparison and hashing
/**
* Compares the specified object with this set for equality. Returns
* <tt>true</tt> if the specified object is also a set, the two sets
* have the same size, and every member of the specified set is
* contained in this set (or equivalently, every member of this set is
* contained in the specified set). This definition ensures that the
* equals method works properly across different implementations of the
* set interface.
*
* @param o object to be compared for equality with this set
* @return <tt>true</tt> if the specified object is equal to this set
*/
boolean equals(Object o);
/**
* Returns the hash code value for this set. The hash code of a set is
* defined to be the sum of the hash codes of the elements in the set,
* where the hash code of a <tt>null</tt> element is defined to be zero.
* This ensures that <tt>s1.equals(s2)</tt> implies that
* <tt>s1.hashCode()==s2.hashCode()</tt> for any two sets <tt>s1</tt>
* and <tt>s2</tt>, as required by the general contract of
* {@link Object#hashCode}.
*
* @return the hash code value for this set
* @see Object#equals(Object)
* @see Set#equals(Object)
*/
int hashCode();
}
| yuexiahandao/JDK-API-CODE | java/util/Set.java | 4,003 | /**
* Returns the number of elements in this set (its cardinality). If this
* set contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
* <tt>Integer.MAX_VALUE</tt>.
*
* @return the number of elements in this set (its cardinality)
*/ | block_comment | en | false |
220052_0 | /*******************************************************************************
* Copyright (c) 2017, 2018 Eurotech and/or its affiliates and others
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Eurotech
*
*******************************************************************************/
package org.eclipse.kura.internal.wire.fifo;
import static java.util.Objects.isNull;
import static java.util.Objects.requireNonNull;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import org.eclipse.kura.configuration.ConfigurableComponent;
import org.eclipse.kura.configuration.ConfigurationService;
import org.eclipse.kura.wire.WireComponent;
import org.eclipse.kura.wire.WireEmitter;
import org.eclipse.kura.wire.WireEnvelope;
import org.eclipse.kura.wire.WireHelperService;
import org.eclipse.kura.wire.WireReceiver;
import org.eclipse.kura.wire.WireSupport;
import org.osgi.framework.ServiceReference;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.wireadmin.Wire;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Fifo implements WireEmitter, WireReceiver, ConfigurableComponent {
private static final String DISCARD_ENVELOPES_PROP_NAME = "discard.envelopes";
private static final String QUEUE_CAPACITY_PROP_NAME = "queue.capacity";
private static final Logger logger = LoggerFactory.getLogger(Fifo.class);
private volatile WireHelperService wireHelperService;
private WireSupport wireSupport;
private FifoEmitterThread emitterThread;
public void bindWireHelperService(final WireHelperService wireHelperService) {
if (isNull(this.wireHelperService)) {
this.wireHelperService = wireHelperService;
}
}
public void unbindWireHelperService(final WireHelperService wireHelperService) {
if (this.wireHelperService == wireHelperService) {
this.wireHelperService = null;
}
}
public void activate(final Map<String, Object> properties, ComponentContext componentContext) {
logger.info("Activating Fifo...");
wireSupport = this.wireHelperService.newWireSupport(this,
(ServiceReference<WireComponent>) componentContext.getServiceReference());
updated(properties);
logger.info("Activating Fifo... Done");
}
public void deactivate() {
logger.info("Dectivating Fifo...");
stopEmitterThread();
logger.info("Dectivating Fifo... Done");
}
public void updated(final Map<String, Object> properties) {
logger.info("Updating Fifo...");
String threadName = (String) properties.getOrDefault(ConfigurationService.KURA_SERVICE_PID, "Fifo")
+ "-EmitterThread";
int queueCapacity = (Integer) properties.getOrDefault(QUEUE_CAPACITY_PROP_NAME, 50);
boolean discardEnvelopes = (Boolean) properties.getOrDefault(DISCARD_ENVELOPES_PROP_NAME, false);
restartEmitterThread(threadName, queueCapacity, discardEnvelopes);
logger.info("Updating Fifo... Done");
}
private synchronized void stopEmitterThread() {
if (emitterThread != null) {
emitterThread.shutdown();
emitterThread = null;
}
}
private synchronized void restartEmitterThread(String threadName, int queueCapacity, boolean discardEnvelopes) {
stopEmitterThread();
logger.debug("Creating new emitter thread: {}, queue capacity: {}, discard envelopes: {}", threadName,
queueCapacity, discardEnvelopes);
emitterThread = new FifoEmitterThread(threadName, queueCapacity, discardEnvelopes);
emitterThread.start();
}
@Override
public void onWireReceive(WireEnvelope wireEnvelope) {
requireNonNull(wireEnvelope, "Wire Envelope cannot be null");
if (emitterThread != null) {
emitterThread.submit(wireEnvelope);
}
}
@Override
public Object polled(Wire wire) {
return this.wireSupport.polled(wire);
}
@Override
public void consumersConnected(Wire[] wires) {
this.wireSupport.consumersConnected(wires);
}
@Override
public void updated(Wire wire, Object value) {
this.wireSupport.updated(wire, value);
}
@Override
public void producersConnected(Wire[] wires) {
this.wireSupport.producersConnected(wires);
}
private class FifoEmitterThread extends Thread {
private Lock lock = new ReentrantLock();
private Condition producer = lock.newCondition();
private Condition consumer = lock.newCondition();
private boolean run = true;
private ArrayList<WireEnvelope> queue;
private int queueCapacity;
private Consumer<WireEnvelope> submitter;
public FifoEmitterThread(String threadName, int queueCapacity, boolean discardEnvelopes) {
this.queue = new ArrayList<>();
this.queueCapacity = queueCapacity;
setName(threadName);
if (discardEnvelopes) {
submitter = getEnvelopeDiscardingSubmitter();
} else {
submitter = getEmitterBlockingSubmitter();
}
}
private Consumer<WireEnvelope> getEnvelopeDiscardingSubmitter() {
return (envelope) -> {
try {
lock.lock();
if (!run || queue.size() >= queueCapacity) {
logger.debug("envelope discarded");
return;
} else {
queue.add(envelope);
producer.signal();
logger.debug("envelope submitted");
}
} finally {
lock.unlock();
}
};
}
private Consumer<WireEnvelope> getEmitterBlockingSubmitter() {
return (envelope) -> {
try {
lock.lock();
while (run && queue.size() >= queueCapacity) {
consumer.await();
}
if (!run) {
return;
}
queue.add(envelope);
producer.signal();
logger.debug("envelope submitted");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
logger.warn("Interrupted while adding new envelope to queue", e);
} finally {
lock.unlock();
}
};
}
public void shutdown() {
try {
lock.lock();
run = false;
producer.signalAll();
consumer.signalAll();
} finally {
lock.unlock();
}
}
public void submit(WireEnvelope envelope) {
submitter.accept(envelope);
}
@Override
public void run() {
while (run) {
try {
WireEnvelope next = null;
try {
lock.lock();
while (run && queue.isEmpty()) {
producer.await();
}
if (!run) {
break;
}
next = queue.remove(0);
consumer.signal();
} finally {
lock.unlock();
}
wireSupport.emit(next.getRecords());
} catch (Exception e) {
logger.warn("Unexpected exception while dispatching envelope", e);
}
}
logger.debug("exiting");
}
}
}
| bellmit/bug_category | data5_6/Fifo.java | 1,704 | /*******************************************************************************
* Copyright (c) 2017, 2018 Eurotech and/or its affiliates and others
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Eurotech
*
*******************************************************************************/ | block_comment | en | true |
220092_7 | package edu.usca.acsc492l.flightplanner;
import java.util.ArrayList;
/**
* A helper class to hold information regarding each destination in the flight plan.
*
* @author Dylon Edwards
*/
public class Destination {
/** Holds the Vertex to be used as this destination */
protected final Vertex destination;
/** Holds the reasons for visiting this destination */
protected ArrayList<String> reasons;
/**
* Constructs a Desintation object with the given Vertex node
*
* @param destination The destination, either an Airport or NAVBeacon
* @throws NullPointerException When destination is null
*/
public Destination(Vertex destination) {
if (destination == null) {
throw new NullPointerException("destination may not be null");
}
this.destination = destination;
reasons = new ArrayList<String>();
}
/**
* Add a reason for stopping at the destination
*
* @param reason The reason for stopping at the destination
* @throws NullPointerException When reason is null
*/
public void addReason(String reason) {
if (reason == null) {
throw new NullPointerException("reason may not be null");
}
reasons.add(reason);
}
/**
* Returns the reasons for visiting this Destination
*
* @return The {@link #reasons} attribute
*/
public ArrayList<String> getReasons() {
return reasons;
}
/**
* Returns the Vertex serving as this Destination
*
* @return The {@link #destination} attribute
*/
public Vertex getDestination() {
return destination;
}
/**
* Overrides the toString() method of the Object class to return all the
* {@link #reasons} for visiting this Destination
*
* @return The String representation of this Destination
*/
@Override
public String toString() {
int counter = 1;
int max = reasons.size();
int longestLabelWidth = destination.getLongestLabelWidth();
String toString = "";
for (String reason : reasons.toArray(new String[0])) {
toString += String.format(" => %-" + longestLabelWidth + "s %s",
"Reason:", reason);
if (counter < max) {
toString += '\n';
}
counter ++;
}
return toString;
}
} | aczietlow/Flight-Planner-Java | Destination.java | 554 | /**
* Overrides the toString() method of the Object class to return all the
* {@link #reasons} for visiting this Destination
*
* @return The String representation of this Destination
*/ | block_comment | en | false |
220164_1 | package common;
import enums.Science;
import enums.Terrain;
public class Cell {
public int xPosition;
public int yPosition;
private Terrain terrain;
private Science science;
// For occupied status we will use hasRover boolean attribute
private boolean hasRover;
//constructor for setting x and y position
public Cell(int x, int y){
this.xPosition=x;
this.yPosition=y;
}
// default constructor
public Cell() {
terrain = Terrain.SOIL;
science = Science.NONE;
hasRover = false;
}
// Constructor for setting Terrain, science and occupied position
public Cell(Terrain terrain, Science science, boolean hasRover) {
this.terrain = terrain;
this.science = science;
this.hasRover = hasRover;
}
// getters
// we will not create any setters for security reasons. Attributes can be
// set using construcors if needed
public int getxPosition() {
return xPosition;
}
public int getyPosition() {
return yPosition;
}
public Terrain getTerrain() {
return terrain;
}
public Science getScience() {
return science;
}
public boolean isHasRover() {
return hasRover;
}
}
| CS-537-Spring-2016/ROVER_13 | src/common/Cell.java | 339 | //constructor for setting x and y position | line_comment | en | true |
220242_0 | import java.util.Random;
class Skill {
private Random rand = new Random();
private double acc = 100.0;
private boolean passive = false;
private boolean offense = true;
private boolean hurtSelf = false;
private Damage dam = null;
private final static int magic = 0, blunt = 1, sharp = 2;
enum Type {
MAGIC,
BLUNT,
SHARP,
NORMAL
}
private Type type = null;
// Called to create a skill instance
Skill(double acc, boolean passive, boolean offense, Type type, Damage dam) {
this.acc = acc;
this.passive = passive;
this.offense = offense;
this.type = type;
this.dam = dam;
if (this.dam.getSelfDam() > 0) {
hurtSelf = true;
}
}
public double getBase(){
return dam.getDam();
}
// Called to get the amount of damage this skill will note favor closer to 1
// means more liekly to hit max damage
public double getDam(double[] resistances, double favor, boolean notSelf) {
double accCheck = rand.nextDouble() * 100;
if (acc <= accCheck) {
return 0;
}
if (!this.getOffense()) {
return dam.getDam();
} else if (this.passive){
return dam.getDam();
}
double randNum = rand.nextDouble() + .5;
randNum = randNum + favor;
if (notSelf) {
if (randNum > 1.5) {
randNum = 1.5;
}
randNum = randNum * dam.getDam();
} else if (!notSelf) {
randNum = randNum * dam.getSelfDam();
}
switch (type) {
case MAGIC:
if (resistances[magic] > 0) {
randNum = randNum / resistances[magic];
}
case BLUNT:
if (resistances[blunt] > 0) {
randNum = randNum / resistances[blunt];
}
case SHARP:
if (resistances[sharp] > 0) {
randNum = randNum / resistances[sharp];
}
case NORMAL:
return randNum;
}
return randNum;
}
// Overloading method to call to get amount of damage without favor
public double getDam(double[] resistances, boolean notSelf) {
return this.getDam(resistances, 0.0, notSelf);
}
// Call to get wether or not this skill is a passive skill
public boolean getPassive() {
return passive;
}
// Call to get wether or not this skill is an offensive skill
public boolean getOffense() {
return offense;
}
// Call to see wether or not this skill hurts the mob using the skill
public boolean getHurtSelf() {
return hurtSelf;
}
// Call to get the type of the skill, see enum Type to see types
public Type getType() {
return type;
}
}
| jpang9431/Basic-Dungeon-Crawler-Game | Skill.java | 741 | // Called to create a skill instance
| line_comment | en | false |
220279_5 | /*
Item (9 tasks)
✅ - private instance vars for name, strength, description, MagicType magicType
✅ + NoArgsConstructor
✅ + Item(String _name, String _description)
✅ + MagicType getMagicType()
✅ + String getName()
✅ + int getStrength()
✅ + void setDescription(String d)
✅ + void setName(String _name)
✅ + isBroken() // returns true if the strength is zero or less, otherwise returns false
✅ + toString() // returns the description
✅ + void weaken() // sets strength to be strength divided by two
*/
public class Item
{
// instance variables go here
// private instance vars for name, strength, description, int magicType
/**
represents the item's name
*/
private String name;
/**
represents the item's strength
*/
private int strength;
/**
represents the item's description
*/
private String description;
/**
represents the item's magic type
*/
private MagicType magicType;
public Item()
{
// set magicType to a random number 1-3 (inclusive)
name = "item name";
strength = 50;
description = "item description";
magicType = MagicType.getRandomMagicType();
}
public Item(String _name, String _description)
{
name = _name;
strength = 50;
description = _description;
magicType = MagicType.FIRE;
}
// methods go down here
/**
Checks if an item is broken or not. Returns True if strength
is less than or equal to 0 otherwise it returns false.
@return Boolean True if strength is less than or equal to 0 Otherwise False
*/
public boolean isBroken()
{
if (strength <= 0)
{
return true;
}
else
{
return false;
}
}
/**
MagicType getMagicType()
returns the magical ability of the item either: fire, ice, or lightning
*/
public MagicType getMagicType(){
return magicType;
}
/** void setDescription()
returns the description of the item
*/
public void setDescription(String d){
description = d;
}
/** void weaken()
makes strength = strength divided byy2
*/
public void weaken(){
strength = strength/2;
}
/** String toString()
returns the description and replaces the pre made toString
*/
public String toString(){
return description;
}
/** String getName()
returns the name
*/
public String getName(){
return name;
}
/** sets the name
*/
public void setName(_name){
name = _name
}
/** gets the strength
*/
/**
*
*Function that gets item strength and returns it
*
*@return strength return item strength
*/
public int getStrength(){
return strength;
}
}
| BradleyCodeU/JavaAdventureGame2023 | Item.java | 645 | /**
represents the item's description
*/ | block_comment | en | true |
220501_8 | package task3;
/**
* Class Monitor To synchronize dining philosophers.
*
* @author Serguei A. Mokhov, [email protected]
*/
public class Monitor {
/*
* ------------ Data members ------------
*/
// *** TASK-2 ***
enum State {
thinking, hungry, eating, talking;
};
// *** TASK-3 ***
enum PriorityState {
hungry, eating, thinking;
}
State[] state;
PriorityState[] priorityState;
int[] priority;
int numOfPhil;
boolean talking;
/**
* Constructor
*/
public Monitor(int piNumberOfPhilosophers) {
// TODO: set appropriate number of chopsticks based on the # of philosophers
state = new State[piNumberOfPhilosophers];
priorityState = new PriorityState[piNumberOfPhilosophers];
priority = new int[piNumberOfPhilosophers];
numOfPhil = piNumberOfPhilosophers;
for (int i = 0; i < piNumberOfPhilosophers; i++) {
state[i] = State.thinking;
}
priority[0] = 3;
priority[1] = 2;
priority[2] = 0;
priority[3] = 5;
}
/*
* ------------------------------- User-defined monitor procedures
* -------------------------------
*/
/**
* Grants request (returns) to eat when both chopsticks/forks are available.
* Else forces the philosopher to wait()
*/
// *** Task-2 *** Implementing pickUp Method
public synchronized void pickUp(final int piTID) {
int id = piTID - 1;
state[id] = State.hungry;
// *** Task-2 *** If any neighbors are eating then wait.
while((state[(id + (numOfPhil - 1)) % numOfPhil] == State.eating)
|| (state[(id + 1) % numOfPhil] == State.eating)) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Checks priority before entering
enter(id);
// If none of the neighbors are eating then start eating
state[id] = State.eating;
}
// ***Task-3 *** This method waits if the priorities doesn't match
public synchronized void enter(int TID) {
priorityState[TID] = PriorityState.hungry;
while(isHigherPriority(TID) == false) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
priorityState[TID] = PriorityState.eating;
}
// ***Task-3*** This method exits
public synchronized void exit(int TID) {
priorityState[TID] = PriorityState.thinking;
notifyAll();
}
// ***Task-3*** This method checks the priority
public synchronized boolean isHigherPriority(int TID) {
boolean isHigherPriority = true;
for(int i = 0; i < numOfPhil; i++) {
if(TID == i || priorityState[i] == PriorityState.thinking) {
// do nothing
}
else {
if(priority[TID] > priority[i]) {
isHigherPriority = false;
}
}
}
return isHigherPriority;
}
/**
* When a given philosopher's done eating, they put the chopstiks/forks down and
* let others know they are available.
*/
// *** Task-2 *** Implementing putDown Method
public synchronized void putDown(final int piTID) {
int id = piTID - 1;
exit(id);
state[id] = State.thinking;
notifyAll();
}
/**
* Only one philopher at a time is allowed to philosophy (while she is not
* eating).
*/
// *** Task-2 *** Implementing requestTalk Method
public synchronized void requestTalk(int tid) {
int id = tid - 1;
// Wait if the philosopher is eating or others are talking
while((state[id] == State.eating) || (isTalking(id) == true) || talking) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
talking = true;
state[id] = State.talking;
}
// Public boolean isTalking()
// Checking if somebody is talking or not
public synchronized boolean isTalking(int id) {
boolean talking = false;
int i = id;
for(int j = 0; j < numOfPhil; j++) {
if(i == j) {
// do nothing
}
// Check if others are talking or not
else {
if (state[id] == State.talking) {
talking = true;
}
}
}
// Return if they are talking or not
return talking;
}
/**
* When one philosopher is done talking stuff, others can feel free to start
* talking.
*/
// *** Task-2 *** Implementing endTalk Method
public synchronized void endTalk(int id) {
int i = id-1;
talking = false;
state[i] = State.thinking;
notifyAll();
}
}
// EOF
| mushfiqur-anik/Dining-Philosopher-Problem | task3/Monitor.java | 1,409 | // *** Task-2 *** Implementing pickUp Method | line_comment | en | false |
220512_3 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.ArrayList;
/**
* textBox
*
* @author Anela
* @version 06/06/2023
*/
public class TextBox extends Actor
{
GreenfootImage textBox = new GreenfootImage("images/textBox.png");
GreenfootSound heal = new GreenfootSound("increaseHeartSound.mp3");
GreenfootSound click = new GreenfootSound("clickSound.mp3");
public Label text;
Label yes = new Label("Yes", 30);
Label no = new Label("No", 30);
Label notEnough = new Label("You don't have enough coins.", 30);
ArrayList<String> thornsOne = new ArrayList<String>();
ArrayList<String> thornsTwo = new ArrayList<String>();
int index = 0;
int heartVal;
boolean previousSpace = false;
boolean finishChoosing = false;
static boolean isTalking = false;
public void act()
{
isTalking = true;
presentText();
}
/**
* print the NPC's text on the screen and allow the player to make choices
*/
public void presentText(){
if (getWorld() instanceof GameTwo){
GameTwo world = (GameTwo) getWorld();
world.removeBubble();
if (index < thornsOne.size()){
text = new Label(thornsOne.get(index),30);
world.addText(text);
if (Greenfoot.isKeyDown("space") && previousSpace == false){
click.play();
previousSpace = true;
world.removeLabel();
index++;
}
if (!Greenfoot.isKeyDown("space")){
previousSpace = false;
}
if (index == thornsOne.size()){
world.addObject(yes, 250, 300);
world.addObject(no, 350, 300);
}
}
if (Greenfoot.mouseClicked(yes)){
click.play();
if (world.getCoin() >= 2){
heal.play();
world.decreaseCoin(2);
world.minusHeartVal(-2);
heartVal = world.getHeartVal();
world.removeObjects(world.getObjects(Heart.class));
world.setHeart(heartVal);
world.removeLabel();
world.addObject(new Label("Good luck.", 30), 300, 300);
}else{
world.removeLabel();
world.addObject(notEnough, 300, 300);
}
finishChoosing = true;
}else if (Greenfoot.mouseClicked(no)){
click.play();
world.removeLabel();
world.addObject(new Label("Good luck.", 30), 300, 300);
finishChoosing = true;
}
if (finishChoosing && Greenfoot.isKeyDown("space")){
click.play();
finishChoosing = false;
world.removeLabel();
world.removeTextBox(this);
world.removeCharacter();
isTalking = false;
}
}else{
Random world = (Random) getWorld();
world.removeBubble();
if (index < thornsTwo.size()){
text = new Label(thornsTwo.get(index),30);
world.addText(text);
if (Greenfoot.isKeyDown("space") && previousSpace == false){
click.play();
previousSpace = true;
world.removeLabel();
index++;
}
if (!Greenfoot.isKeyDown("space")){
previousSpace = false;
}
if (index == thornsTwo.size()){
world.addObject(yes, 250, 300);
world.addObject(no, 350, 300);
}
}
if (Greenfoot.mouseClicked(yes)){
click.play();
if (world.getCoin() >= 5){
heal.play();
world.decreaseCoin(5);
world.minusHeartVal(-2);
heartVal = world.getHeartVal();
world.removeObjects(world.getObjects(Heart.class));
world.setHeart(heartVal);
world.removeLabel();
world.addObject(new Label("Good luck.", 30), 300, 300);
}else{
world.removeLabel();
world.addObject(notEnough, 300, 300);
}
finishChoosing = true;
}else if (Greenfoot.mouseClicked(no)){
click.play();
world.removeLabel();
world.addObject(new Label("Good luck.", 30), 300, 300);
finishChoosing = true;
}
if (finishChoosing && Greenfoot.isKeyDown("space")){
click.play();
finishChoosing = false;
world.removeLabel();
world.removeTextBox(this);
world.removeCharacter();
isTalking = false;
}
}
}
public TextBox(){
addTextOne();
addTextTwo();
setImage(textBox);
}
/**
* NPC's words in the tutorial
*/
public void addTextOne(){
thornsOne.add("Hello, little warrior.");
thornsOne.add("I am Thorns and I will help you \n in your future advanture.");
thornsOne.add("You can pay me 5 coins to get 1 heart.");
thornsOne.add("You only need to pay me 2 coins this time.");
}
/**
* NPC's words in the random game mode
*/
public void addTextTwo(){
thornsTwo.add("Hello, nice to see you again. ");
thornsTwo.add("Do you want to pay 5 coins to get a heart?");
}
/**
* allow other actors to know if they need to stop when talking
*/
public static boolean getIsTalking(){
return isTalking;
}
}
| yrdsb-peths/final-greenfoot-project-Gao040701 | TextBox.java | 1,401 | /**
* NPC's words in the tutorial
*/ | block_comment | en | true |
220607_6 | package iocomms.subpos;
/* Android API for SubPos (http://www.subpos.org)
* Copyright (C) 2015 Blair Wyatt
*
* 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/>.
*
*/
import org.apache.commons.math3.fitting.leastsquares.LeastSquaresOptimizer;
import org.apache.commons.math3.fitting.leastsquares.LevenbergMarquardtOptimizer;
import org.apache.commons.math3.linear.RealVector;
import java.util.ArrayList;
import java.util.Date;
class ArrayLocations extends ArrayList<SPSData>
{
ArrayList<SPSData> locations = new ArrayList<SPSData>();
public ArrayLocations()
{
super();
}
@Override
public int size()
{
return locations.size();
}
@Override
public SPSData get(int index)
{
return locations.get(index);
}
@Override
public boolean add(SPSData x)
{
SPSData temp;
boolean averaged = false;
//Find node that already exists
for(int i=0; i<this.locations.size(); i++) {
if (x.compareTo(this.locations.get(i)) == 1) {
temp = this.locations.get(i);
if (temp.num_of_averages > 1) {
temp.updateAverage(x.distance, x.rx_pwr);
averaged = true;
} else {
this.locations.remove(x);
}
break;
}
}
if (!averaged) {
this.locations.add(x);
}
return true;
}
}
public class NodeLocations {
private int averages = 0; //number of averages for node distance calcs.
private ArrayLocations locations = new ArrayLocations();
Position currentNodePosition = null;
Position currentPosition = null;
private boolean calculated = false;
public ArrayList<SPSData> getLocations()
{
return locations.locations;
}
public void addLocation(char[] ssid, int rx_pwr, String bssid, int freq, long application_id,
boolean offset_mapping, boolean three_d_mapping)
{
SPSData location = new SPSData(averages);
location.decodeSSID(ssid, rx_pwr, freq, bssid);
if (location.app_id == application_id && location.off_map == offset_mapping &&
location.three_d_map == three_d_mapping) {
locations.add(location);
calculated = false;
}
}
public void setRollingAverage(int averages)
{
this.averages = averages;
}
public int size()
{
return locations.size();
}
public boolean isCalculated()
{
return calculated;
}
public void killAgedNodes(int secondsAge)
{
int i = 0;
while (i < this.locations.size()) {
if (((new Date()).getTime() - this.locations.get(i).seen.getTime())/1000 > secondsAge ) {
this.locations.locations.remove(i);
} else {
i++;
}
}
}
@Override
public String toString()
{
String build = new String();
if (currentNodePosition != null)
{
build = currentNodePosition.lat + ", " + currentNodePosition.lng + ", "
+ (currentNodePosition.altitude / 100); //Convert alt to meters
}
return build;
}
public void calculatePosition() {
if (locations.size() > 0) {
if (locations.size() == 1)
{
currentPosition = new Position(locations.get(0).lat, locations.get(0).lng,
locations.get(0).altitude, locations.get(0).distance);
}
else
{
currentPosition = trilaterate(locations);
}
calculated = true;
}
}
//Cannot debug a single node
private Position trilaterate(ArrayLocations locations) {
//Trilateration nonlinear weighted least squares
//https://github.com/lemmingapex/Trilateration - MIT Licence
//http://commons.apache.org/proper/commons-math/download_math.cgi
double[][] positions = new double[locations.size()][3];
double[] distances = new double[locations.size()];
int i = 0;
while (i < locations.size()) {
//Map projection is treated as Mercator for calcs
//Convert lat,lng to meters and then back again
//Altitude is in cm
positions[i] = new double[]{WebMercator.latitudeToY(locations.get(i).lat),
WebMercator.longitudeToX(locations.get(i).lng),locations.get(i).altitude};
distances[i] = locations.get(i).distance;
i++;
}
TrilaterationFunction trilaterationFunction = new TrilaterationFunction(positions, distances);
NonLinearLeastSquaresSolver solver = new NonLinearLeastSquaresSolver(trilaterationFunction, new LevenbergMarquardtOptimizer());
LeastSquaresOptimizer.Optimum optimum = solver.solve();
double[] centroid = optimum.getPoint().toArray();
double errorRadius = 0;
boolean errorCalc = false;
// Error and geometry information
try {
//Create new array without the altitude. Including altitude causes a
//SingularMatrixException as it cannot invert the matrix.
double[][] err_positions = new double[locations.size()][2];
i = 0;
while (i < locations.size()) {
err_positions[i] = new double[]{positions[i][0],
positions[i][1]};
i++;
}
trilaterationFunction = new TrilaterationFunction(err_positions, distances);
solver = new NonLinearLeastSquaresSolver(trilaterationFunction, new LevenbergMarquardtOptimizer());
optimum = solver.solve();
RealVector standardDeviation = optimum.getSigma(0);
//RealMatrix covarianceMatrix = optimum.getCovariances(0);
errorRadius = ((standardDeviation.getEntry(0) + standardDeviation.getEntry(1)) / 2) * 100;
errorCalc = true;
} catch (Exception ex) {
errorRadius = 0;
errorCalc = false;
}
return new Position(WebMercator.yToLatitude(optimum.getPoint().toArray()[0]),
WebMercator.xToLongitude(centroid[1]),centroid[2],
errorRadius, errorCalc);
}
}
| subpos/subpos_android_api | NodeLocations.java | 1,681 | //https://github.com/lemmingapex/Trilateration - MIT Licence | line_comment | en | true |
220642_0 | import java.util.Scanner;
public class switchs {
System.out.p
Scanner sc = new Scanner(System.in);
// Taking input from the user.
int button = sc.nextInt();
// If we have multiple cases the we wil use switch statement.
switch(button){
// Case 1, if user gave input 1.
case 1: System.out.println("Hello.");
// break.
break;
// case 2, if user gave input 2.
case 2: System.out.println("Namaste.");
// break.
break;
// case 3, if user gave input 3.
case 3: System.out.println("Bonjure.");
// break.
break;
// Using default if the user gave different input .
default: System.out.println("Invalid option.");
}
}
| Shivam-tamboli/Java-repository | switchs.java | 198 | // Taking input from the user. | line_comment | en | false |
221688_31 | // This file defines class "TimeSim". This class contains all the
// variables and methods needed to handle the passage of simulated time.
// Threads can call timeSim.doSleep(n) to "sleep" for n time units, or
// timeSim.doSleep(n,m) to "sleep" for k time units, where k is randomly
// chosen in the range n to m.
import java.util.concurrent.*;
public class TimeSim {
// Class "Event" represents an event that lies in the future. The event
// consists of a simulated time, as well as a semaphore that should
// receive a release() at that time.
class Event {
public int wakeupTime;
public Semaphore sem; // This semaphore should receive a
// release() when the simulated time
// is equal to wakeupTime
}
private int numThreads; // numThreads is the total number of threads
// that are making use of class TimeSim.
private int threadsComputing; // This is the number of threads that are
// still computing at the current time. Wait until all threads are done before
// advancing time. Threads are done when they are waiting at an acquire(); this
// happens because the thread calls acquire() or doSleep().
private int time; // time is the current simulated time. threadComputationDoneForNow()
// advances time when all threads are waiting for a semaphore. That wakes up
// those threads that are in the shortest sleep.
private final int MAX_EVENTS = 100;// this is the maximum number of threads
// that can be handled, since each
// thread produces at most one event.
// (An event is produced by calling
// timeSim.doSleep)
private Event[] events; // An array of events, in unsorted order.
// events[i].wakeupTime = -1 indicates that
// events[i] is currently unused.
private java.util.concurrent.Semaphore timeMutex; //This is a normal semaphore
// (as defined in the Java concurrency package) used only within
// TimeSim to ensure mutual exclusion
// ------------------- constructor ---------------
public TimeSim() {
numThreads = 0;
threadsComputing = 0;
time=0;
events = new Event[MAX_EVENTS];
for (int i=0; i<MAX_EVENTS; i++) {
events[i] = new Event();
events[i].wakeupTime = -1;
events[i].sem = new Semaphore(0, true);
}
timeMutex = new java.util.concurrent.Semaphore(1, true);
}
// ------------------- threadStart ---------------
public void threadStart() {
try{
timeMutex.acquire();
}
catch (Exception e){
System.out.println(e);
}
numThreads++;
threadsComputing++;
if (numThreads>MAX_EVENTS) {
System.out.println("You have called timeSim.threadStart more than "
+ MAX_EVENTS + " times. This overflows the events array. ");
System.out.println("If you need this many threads, then increase MAX_EVENTS in TimeSim.java.");
}
timeMutex.release();
}
// ------------------- threadEnd ---------------
public void threadEnd() {
try{
timeMutex.acquire();
}
catch (Exception e){
System.out.println(e);
}
if (numThreads==0)
System.out.println("Error: threadEnd called more often than threadStart!");
numThreads--;
threadsComputing--;
if (Synch.debug>=2)
System.out.println("A thread has ended. There are " + numThreads
+ " threads left, and " + threadsComputing
+ " of these are computing now, at time " + time);
if (threadsComputing==0)
advanceTime();
timeMutex.release();
}
// ------------------- curTime -----------------------------------
public int curTime() {
return time;
}
// ------------------- threadComputationDoneForNow ---------------
// This method is called by acquire. Once all threads are stuck at
// an acquire, advance time to the next simulated time at which a
// thread is supposed to wake up.
public void threadComputationDoneForNow() {
try{
timeMutex.acquire();
}
catch (Exception e){
System.out.println(e);
}
threadsComputing--;
if (Synch.debug>=2)
System.out.println("At time "+time+", a thread computation is done." + threadsComputing + " threads are still computing");
if (threadsComputing<0) {
System.out.println("Error in timeSim: inconsistent number of threads. ");
System.out.println("Maybe some threads forgot to call timeSim.threadStart");
}
if (threadsComputing==0)
advanceTime();
timeMutex.release();
}
// ------------------- threadComputationStarting ---------------
// This method is called by release. It indicates that another
// thread has code to execute at the current simulated time. We have
// to wait for all of these threads to finish, before advancing time.
public void threadComputationStarting() {
threadsComputing++;
if (Synch.debug>=2)
System.out.println("At time "+time+" a thread computation is starting. " + threadsComputing + " threads are now computing");
}
// ------------------- doSleep (two parameters) ------------------------
public void doSleep(int lower, int upper) {
if ((lower >=0) && (upper >= lower)) {
int n = (int)((upper-lower)*Math.random())+lower;
doSleep(n);
}
else
System.out.println("Invalid parameters to TimeSim.doRandomSleep()");
}
// ------------------- doSleep (one parameter) -------------------------
// This method is called when a thread wants to sleep. Create an
// event that records when we should wake up. Then acquire() a semaphore
// associated with the event. This semaphore will be released by advanceTime()
// once the simulated time has advanced up to the wake-up time for this thread.
public void doSleep(int n) {
try{
timeMutex.acquire();
}
catch (Exception e){
System.out.println(e);
}
int waketime = time+n;
// Look through events, to find an unused entry.
int eventIndex = 0;
while (events[eventIndex].wakeupTime != -1)
eventIndex++;
events[eventIndex].wakeupTime = waketime;
if (Synch.debug>=2) {
System.out.print("List of event wakeupTimes after doSleep("+n+"):");
for (int j=0; j<MAX_EVENTS; j++) {
if (events[j].wakeupTime!=-1)
System.out.print(" " + events[j].wakeupTime);
}
System.out.println(".");
}
// Release mutex before making this thread wait.
timeMutex.release();
events[eventIndex].sem.acquire();
}
// ------------------- advanceTime ------------------------------
// This is a private method that advances time to the wakeupTime of
// of the soonest event, which is stored in events[0]. Wake up all threads
// that have this event time.
// The caller already holds timeMutex.
private void advanceTime() {
if (Synch.debug>=3)
System.out.println("starting advanceTime");
// Find the smallest wakeupTime in events.
// If events[i].wakeupTime == -1, that event is unused.
int minTime=-1;
for (int i=0; i<MAX_EVENTS; i++)
if (events[i].wakeupTime != -1)
if ((minTime==-1) | (events[i].wakeupTime<minTime))
minTime = events[i].wakeupTime;
if (minTime==-1) {
// System.out.println("There are no more events.");
}
else {
time = minTime;
for (int i=0; i<MAX_EVENTS; i++) {
if (events[i].wakeupTime == time) {
events[i].wakeupTime = -1;
events[i].sem.release();
}
}
if (Synch.debug>=1) {
System.out.print("Advanced time to "+time+". Remaining wakeupTimes are:");
for (int j=0; j<MAX_EVENTS; j++) {
if (events[j].wakeupTime!=-1)
System.out.print(" " + events[j].wakeupTime);
}
System.out.println(".");
}
}
}
} // end of class "TimeSim"
| dunderjeep/cisc324lab4 | TimeSim.java | 1,998 | // ------------------- constructor --------------- | line_comment | en | true |
221834_53 | /////////////////////////////////////////////////////////////////////////////
// Copyright (c) 1999, COAS, Oregon State University
// ALL RIGHTS RESERVED. U.S. Government Sponsorship acknowledged.
//
// Please read the full copyright notice in the file COPYRIGHT
// in this directory.
//
// Author: Nathan Potter ([email protected])
//
// College of Oceanic and Atmospheric Scieneces
// Oregon State University
// 104 Ocean. Admin. Bldg.
// Corvallis, OR 97331-5503
//
/////////////////////////////////////////////////////////////////////////////
//
// Based on source code and instructions from the work of:
//
/////////////////////////////////////////////////////////////////////////////
// Copyright (c) 1998, California Institute of Technology.
// ALL RIGHTS RESERVED. U.S. Government Sponsorship acknowledged.
//
// Please read the full copyright notice in the file COPYRIGHT
// in this directory.
//
// Author: Jake Hamby, NASA/Jet Propulsion Laboratory
// [email protected]
/////////////////////////////////////////////////////////////////////////////
package dods.dap.Server;
import dods.dap.*;
import java.io.*;
import dods.dap.parser.ExprParserConstants;
/**
* Holds a DODS Server <code>Float64</code> value.
*
* @version $Revision: 1.23 $
* @author ndp
* @see BaseType
*/
public abstract class SDFloat64 extends DFloat64 implements ServerMethods, RelOps, ExprParserConstants {
private boolean Project;
private boolean Synthesized;
private boolean ReadMe;
/** Constructs a new <code>SDFloat64</code>. */
public SDFloat64() {
super();
Project = false;
Synthesized = false;
ReadMe = false;
}
/**
* Constructs a new <code>SDFloat64</code> with name <code>n</code>.
* @param n the name of the variable.
*/
public SDFloat64(String n) {
super(n);
Project = false;
Synthesized = false;
ReadMe = false;
}
/**
* Write the variable's declaration in a C-style syntax. This
* function is used to create textual representation of the Data
* Descriptor Structure (DDS). See <em>The DODS User Manual</em> for
* information about this structure.
*
* @param os The <code>PrintWriter</code> on which to print the
* declaration.
* @param space Each line of the declaration will begin with the
* characters in this string. Usually used for leading spaces.
* @param print_semi a boolean value indicating whether to print a
* semicolon at the end of the declaration.
* @param constrained a boolean value indicating whether to print
* the declartion dependent on the projection information. <b>This
* is only used by Server side code.</b>
* @see DDS
*/
public void printDecl(PrintWriter os, String space,
boolean print_semi, boolean constrained) {
if(constrained && !Project)
return;
// BEWARE! Since printDecl()is (multiple) overloaded in BaseType
// and all of the different signatures of printDecl() in BaseType
// lead to one signature, we must be careful to override that
// SAME signature here. That way all calls to printDecl() for
// this object lead to this implementation.
// Also, since printDecl()is (multiple) overloaded in BaseType
// and all of the different signatures of printDecl() in BaseType
// lead to the signature we are overriding here, we MUST call
// the printDecl with the SAME signature THROUGH the super class
// reference (assuming we want the super class functionality). If
// we do otherwise, we will create an infinte call loop. OOPS!
super.printDecl(os,space,print_semi,constrained);
}
/**
* Prints the value of the variable, with its declaration. This
* function is primarily intended for debugging DODS applications and
* text-based clients such as geturl.
*
* <h2> Important Note</h2>
* This method overrides the BaseType method of the same name and
* type signature and it significantly changes the behavior for all versions
* of <code>printVal()</code> for this type:
* <b><i> All the various versions of printVal() will only
* print a value, or a value with declaration, if the variable is
* in the projection.</i></b>
* <br>
* <br>In other words, if a call to
* <code>isProject()</code> for a particular variable returns
* <code>true</code> then <code>printVal()</code> will print a value
* (or a declaration and a value).
* <br>
* <br>If <code>isProject()</code> for a particular variable returns
* <code>false</code> then <code>printVal()</code> is basically a No-Op.
* <br>
* <br>
*
* @param os the <code>PrintWriter</code> on which to print the value.
* @param space this value is passed to the <code>printDecl</code> method,
* and controls the leading spaces of the output.
* @param print_decl_p a boolean value controlling whether the
* variable declaration is printed as well as the value.
* @see BaseType#printVal(PrintWriter, String, boolean)
* @see ServerMethods#isProject()
*/
public void printVal(PrintWriter os, String space, boolean print_decl_p) {
if(!Project)
return;
super.printVal(os,space,print_decl_p);
}
// --------------- Projection Interface
/** Set the state of this variable's projection. <code>true</code> means
that this variable is part of the current projection as defined by
the current constraint expression, otherwise the current projection
for this variable should be <code>false</code>.
@param state <code>true</code> if the variable is part of the current
projection, <code>false</code> otherwise.
@param all This parameter has no effect for this type of variable.
@see CEEvaluator */
public void setProject(boolean state, boolean all) {
Project = state;
}
/** Set the state of this variable's projection. <code>true</code> means
that this variable is part of the current projection as defined by
the current constraint expression, otherwise the current projection
for this variable should be <code>false</code>.
@param state <code>true</code> if the variable is part of the current
projection, <code>false</code> otherwise.
@see CEEvaluator */
public void setProject(boolean state) {
setProject(state, true);
}
/** Is the given variable marked as projected? If the variable is listed
in the projection part of a constraint expression, then the CE parser
should mark it as <em>projected</em>. When this method is called on
such a variable it should return <code>true</code>, otherwise it
should return <code>false</code>.
@return <code>true</code> if the variable is part of the current
projections, <code>false</code> otherwise.
@see CEEvaluator
@see #setProject(boolean)
*/
public boolean isProject(){
return(Project);
}
// --------------- RelOps Interface
/** The RelOps interface defines how each type responds to relational
operators. Most (all?) types will not have sensible responses to all of
the relational operators (e.g. DBoolean won't know how to match a regular
expression but DString will). For those operators that are nonsensical a
class should throw InvalidOperatorException.*/
public boolean equal(BaseType bt) throws InvalidOperatorException, RegExpException, SBHException{
return(Operator.op(EQUAL,this,bt));
}
public boolean not_equal(BaseType bt) throws InvalidOperatorException, RegExpException, SBHException{
return(Operator.op(NOT_EQUAL,this,bt));
}
public boolean greater(BaseType bt) throws InvalidOperatorException, RegExpException, SBHException{
return(Operator.op(GREATER,this,bt));
}
public boolean greater_eql(BaseType bt) throws InvalidOperatorException, RegExpException, SBHException{
return(Operator.op(GREATER_EQL,this,bt));
}
public boolean less(BaseType bt) throws InvalidOperatorException, RegExpException, SBHException{
return(Operator.op(LESS,this,bt));
}
public boolean less_eql(BaseType bt) throws InvalidOperatorException, RegExpException, SBHException{
return(Operator.op(LESS_EQL,this,bt));
}
public boolean regexp(BaseType bt) throws InvalidOperatorException, RegExpException, SBHException{
return(Operator.op(REGEXP,this,bt));
}
// --------------- FileIO Interface
/** Set the Synthesized property.
@param state If <code>true</code> then the variable is considered a
synthetic variable and no part of DODS will ever try to read it from a
file, otherwise if <code>false</code> the variable is considered a
normal variable whose value should be read using the
<code>read()</code> method. By default this property is false.
@see #isSynthesized()
@see #read(String,Object)
*/
public void setSynthesized(boolean state){
Synthesized = state;
}
/** Get the value of the Synthesized property.
@return <code>true</code> if this is a synthetic variable,
<code>false</code> otherwise. */
public boolean isSynthesized(){
return(Synthesized);
}
/** Set the Read property. A normal variable is read using the
<code>read()</code> method. Once read the <em>Read</em> property is
<code>true</code>. Use this function to manually set the property
value. By default this property is false.
@param state <code>true</code> if the variable has been read,
<code>false</code> otherwise.
@see #isRead()
@see #read(String,Object)
*/
public void setRead(boolean state){
ReadMe = state;
}
/** Get the value of the Read property.
@return <code>true</code> if the variable has been read,
<code>false</code> otherwise.
@see #read(String,Object)
@see #setRead(boolean)
*/
public boolean isRead(){
return(ReadMe);
}
/** Read a value from the named dataset for this variable.
@param datasetName String identifying the file or other data store
from which to read a vaue for this variable.
@param specialO This <code>Object</code> is a goody that is used by Server implementations
to deliver important, and as yet unknown, stuff to the read method. If you
don't need it, make it a <code>null</code>.
@return <code>true</code> if more data remains to be read, otherwise
<code>false</code>. This is an abtsract method that must be implemented
as part of the installation/localization of a DODS server.
@exception IOException
@exception EOFException */
public abstract boolean read(String datasetName, Object specialO) throws NoSuchVariableException, IOException, EOFException;
/**
* Server-side serialization for DODS variables (sub-classes of
* <code>BaseType</code>).
* This does not send the entire class as the Java <code>Serializable</code>
* interface does, rather it sends only the binary data values. Other software
* is responsible for sending variable type information (see <code>DDS</code>).
*
* Writes data to a <code>DataOutputStream</code>. This method is used
* on the server side of the DODS client/server connection, and possibly
* by GUI clients which need to download DODS data, manipulate it, and
* then re-save it as a binary file.
*
* @param sink a <code>DataOutputStream</code> to write to.
* @exception IOException thrown on any <code>OutputStream</code> exception.
* @see BaseType
* @see DDS
* @see ServerDDS */
public void serialize(String dataset,DataOutputStream sink,CEEvaluator ce, Object specialO)
throws NoSuchVariableException, SDODSException, IOException {
if(!isRead())
read(dataset, specialO);
if(ce.evalClauses(specialO))
externalize(sink);
}
}
| perkinss/ERDDAP_ONC | src/dods/dap/Server/SDFloat64.java | 2,984 | /** Set the Read property. A normal variable is read using the
<code>read()</code> method. Once read the <em>Read</em> property is
<code>true</code>. Use this function to manually set the property
value. By default this property is false.
@param state <code>true</code> if the variable has been read,
<code>false</code> otherwise.
@see #isRead()
@see #read(String,Object)
*/ | block_comment | en | true |
222147_10 | // 2022-09-06
// 연구소3
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static class Virus {
int x;
int y;
public Virus(int x, int y) {
this.x = x;
this.y = y;
}
}
static int N,M;
static int [][] map;
static ArrayList<Virus> viruses;
static int emptyCnt;
static int [] numbers;
static int [] dx = {-1,0,1,0};
static int [] dy = {0,1,0,-1};
static int ans = Integer.MAX_VALUE;
public static void main(String args[]) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(in.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
map = new int [N][N];
viruses = new ArrayList<Virus>();
emptyCnt = 0; // 퍼트릴 칸 수
for(int i=0; i<N; i++) {
st = new StringTokenizer(in.readLine());
for(int j=0; j<N; j++) {
map[i][j] = Integer.parseInt(st.nextToken());
if(map[i][j] == 1) {
map[i][j] = -1; // 벽은 -1로 표시
}
else if(map[i][j] == 2) {
viruses.add(new Virus(i,j));
map[i][j] = -2; // 바이러스를 -2로 표시
} else {
emptyCnt+=1;
}
}
}
numbers = new int [M];
comb(0,0);
if(ans==Integer.MAX_VALUE) ans = -1; // 모든 빈칸에 퍼트리지 못했으면 -1
else if(emptyCnt!=0) ans+=1; // 퍼트릴 빈칸이 있었으면 +1
// 다 퍼트렸을 경우는 빈칸이 없으므로 시간이 +1이 안됐기 때문
// else ans; // 모든 빈칸에 퍼트릴 칸이 아예 없는 경우는 0초의 시간이 흘렀으나
// 모든 빈칸에
System.out.println(ans);
}
private static void comb(int start, int count) {
if(count==M) {
Spread();
return;
}
for(int i=start; i<viruses.size(); i++) {
numbers[count]=i;
comb(i+1, count+1);
}
}
private static void Spread() {
boolean[][] visited = new boolean[N][N];
int[][] copyMap = new int [N][N];
int time = 0;
int cnt = emptyCnt;
boolean isMove;
// 바이러스를 새로운 조합으로 뽑았을 경우 맵 초기화
for(int i=0; i<N; i++) {
for(int j=0; j<N; j++) {
copyMap[i][j] = map[i][j];
}
}
Queue<Virus> q = new ArrayDeque<>();
// 선택한 바이러스를 큐에 넣기
for(int i=0; i<numbers.length; i++) {
q.add(viruses.get(numbers[i]));
int x = viruses.get(numbers[i]).x;
int y = viruses.get(numbers[i]).y;
visited[x][y]=true;
copyMap[x][y] = 0;
}
while(!q.isEmpty()) {
int len = q.size();
isMove = false;
for(int l=0; l<len; l++) {
Virus v = q.poll();
int curX = v.x;
int curY = v.y;
// 4방탐색
for(int i=0; i<4; i++) {
int nx = curX + dx[i];
int ny = curY + dy[i];
if(isValid(nx, ny) && !visited[nx][ny]) {
if(copyMap[nx][ny]==-2 || copyMap[nx][ny]==0) {
if(copyMap[nx][ny]==0) {
cnt-=1;
copyMap[nx][ny] = copyMap[curX][curY]+1;
} else if(copyMap[nx][ny]==-2) {
copyMap[nx][ny] = 0;
}
q.add(new Virus(nx,ny));
isMove = true; // 비활성화 바이러스를 활성화 시키거나 퍼트리면 움직임.
}
visited[nx][ny] = true;
}
}
}
if(cnt!=0 && isMove) time+=1; // 한번이라도 움직였으면 시간이 흐름.
// 단, 모든 칸에 바이러스를
}
if(cnt==0) {
if(ans>time) {
ans = time;
/*System.out.println();
for(int i=0; i<N; i++) {
for(int j=0; j<N; j++) {
System.out.print(copyMap[i][j]+ " ");
}
System.out.println();
}*/
}
}
}
private static boolean isValid(int nx, int ny) {
if(nx>=0 && ny>=0 && nx<N && ny<N) return true;
else return false;
}
}
| yujin032497/baekjoon_java | 17142.java | 1,527 | // 바이러스를 새로운 조합으로 뽑았을 경우 맵 초기화 | line_comment | en | true |
222384_9 | /** Board.java
* Creates a board based on user input and runs an interactive loop to either allow the user to solve the board or to automatically solve it
* if the board is solvable, prints out a step-by-step solution
* if the board is unsolvable, prints out a best-found solution
*
* created by 1530b
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import java.util.Scanner;
import static java.lang.System.exit;
public class Board {
public int grid[][];
HashMap<Integer, Coordinate> mapFromIntegerToCoord = new HashMap<>();
public Board(int choice) {
if (choice == 1) {
generateBoard(new Random(System.currentTimeMillis()));
} else if (choice == 2) {
generateBoard();
} else {
Constants.outputStream.println("Invalid input given.");
exit(1);
}
}
/**
* Performs a deep copy of a board by copying its grid and mappings.
* @param b
*/
public Board(Board b) {
grid = new int[Constants.dimX][Constants.dimY];
for (int i = 0; i < Constants.dimX; i++) {
for (int j = 0; j < Constants.dimY; j++) {
grid[i][j] = b.grid[i][j];
mapFromIntegerToCoord.put(b.grid[i][j], new Coordinate(i, j));
}
}
}
/**
* compares the grid of this to board b for equality
* @param b
* @return
*/
public boolean equals(Board b) {
for (int i = 0; i < Constants.dimX; i++) {
if (!grid[i].equals(b.grid[i])) {
return false;
}
}
return true;
}
/**
* generated a board using a random seeded with time.
* 1. generate 9 unique, random integers (0-9)
* 2. export them into an array
* 3. convert into an integer array
* 4. set up grid
*
* @param rand
*/
private void generateBoard(Random rand) {
grid = new int[Constants.dimX][Constants.dimY];
int[] boardVals = new int[Constants.gridSize];
for (int i = 0; i < (Constants.gridSize); i++) {
boardVals[i] = i;
}
shuffleNumbers(boardVals, rand);
int arrIndex = 0;
for (int i = 0; i < Constants.dimX; i++) {
for (int j = 0; j < Constants.dimY; j++) {
int num = boardVals[arrIndex++];
mapFromIntegerToCoord.put(num, new Coordinate(i, j));
grid[i][j] = num;
}
}
}
/**
* Generates board based on user input
* 1. take input from user
* 2. parse char by char
* 3. input into grid
*/
private void generateBoard() {
Scanner scan = new Scanner(Constants.inputStream);
Constants.outputStream.println("Some boards such as 728045163 are impossible.");
Constants.outputStream.println("Others such as 245386107 are possible.");
Constants.outputStream.print("Enter a string of 6 digits (including 0) for the board --> ");
String input = scan.nextLine().trim();
grid = new int[Constants.dimX][Constants.dimY];
int strIndex = 0;
for (int i = 0; i < Constants.dimX; i++) {
for (int j = 0; j < Constants.dimY; j++) {
int num = Character.getNumericValue(input.charAt(strIndex++));
mapFromIntegerToCoord.put(num, new Coordinate(i, j));
grid[i][j] = num;
}
}
}
/**
* Takes an array and shuffles it a random number of times
* @param arr
* @param rand
*/
private void shuffleNumbers(int[] arr, Random rand) {
int numTimesToSwap = rand.nextInt(200);
for (int i = 0; i < numTimesToSwap; i++) {
int index1 = rand.nextInt((Constants.gridSize) - 1);
int index2 = rand.nextInt((Constants.gridSize) - 1);
int tmp = arr[index2];
arr[index2] = arr[index1];
arr[index1] = tmp;
}
}
/**
* prints out the current grid
*/
public void printBoard() {
for (int i = 0; i < Constants.dimX; i++) {
Constants.outputStream.print(" ");
for (int j = 0; j < Constants.dimY; j++) {
Constants.outputStream.print(grid[i][j] == 0 ? " " : grid[i][j] + " ");
}
Constants.outputStream.print("\n");
}
}
/**
* determines whether the current grid is already solved
* @return
*/
public boolean isSolved() {
for (int i = 0; i < Constants.dimX; i++) {
for (int j = 0; j < Constants.dimY; j++) {
if (i == Constants.dimX - 1 && j == Constants.dimY - 1) { //if at bottom right corner, index should be 0
if (grid[i][j] != 0) {
return false;
}
} else if (grid[i][j] != (i * Constants.dimX) + j + 1) //every other index should satisfy its spot
return false;
}
}
return true;
}
/**
* slides a piece into the empty slot
* @param n
*/
public void makeMove(int n) {
if (mapFromIntegerToCoord.containsKey(n)) {
Coordinate coord = mapFromIntegerToCoord.remove(n);
Coordinate zeroCoord = mapFromIntegerToCoord.remove(0);
grid[zeroCoord.X][zeroCoord.Y] = grid[coord.X][coord.Y];
grid[coord.X][coord.Y] = 0;
mapFromIntegerToCoord.put(0, new Coordinate(coord.X, coord.Y));
mapFromIntegerToCoord.put(n, new Coordinate(zeroCoord.X, zeroCoord.Y));
}
}
/**
* determines whether a given move is valid
* @param n
* @return
*/
public boolean isValidMove(int n) {
Coordinate coord = mapFromIntegerToCoord.get(n);
if (mapFromIntegerToCoord.containsKey(n)) {
if (coord.X + 1 <= Constants.dimX - 1) {
if (grid[coord.X + 1][coord.Y] == 0) {
return true;
}
}
if (coord.Y + 1 <= Constants.dimY - 1) {
if (grid[coord.X][coord.Y + 1] == 0) {
return true;
}
}
if (coord.X - 1 >= 0) {
if (grid[coord.X - 1][coord.Y] == 0) {
return true;
}
}
if (coord.Y - 1 >= 0) {
if (grid[coord.X][coord.Y - 1] == 0) {
return true;
}
}
}
return false;
}
/**
* while the board is unsolved, allows the user to:
* a. make a move (if it is valid)
* b. prompt for an automatic solution (if one exists, otherwise print the best board found)
* c. quit
*
*/
public void interactiveLoop() {
Scanner scan = new Scanner(Constants.inputStream);
int boardCounter = 1;
Constants.outputStream.println("Initial board is:");
boolean autoSolve = false;
while (!isSolved() && !autoSolve) {
Constants.outputStream.println(boardCounter++ + ".");
printBoard();
Constants.outputStream.println("Heuristic Value: " + currentHeuristic());
Constants.outputStream.print("\nPiece to move: ");
String move = scan.next();
char m = move.charAt(0);
if (m == 's') {
autoSolve = true;
} else {
int numericInput = Character.getNumericValue(m);
if (numericInput == 0) {
Constants.outputStream.println("\nExiting program.");
exit(0);
}
if (isValidMove(numericInput)) {
makeMove(numericInput);
} else {
Constants.outputStream.println("*** Invalid move. Please retry.");
}
}
}
if (!isSolved()) {
SearchTree tree = autoSolve();
if (tree.bestBoardHeuristic > 0) {
Constants.outputStream.println("\nAll " +tree.oldBoards.size() + " moves have been tried.");
Constants.outputStream.println("That puzzle is impossible to solve. Best board found:");
tree.bestBoardFound.printBoard();
Constants.outputStream.println("Heuristic value: " + tree.bestBoardHeuristic);
Constants.outputStream.println("\nExiting program.");
} else {
Constants.outputStream.println("1.");
printBoard();
ArrayList<Board> list = tree.createPath();
for (int i = 0; i < list.size(); i++) {
Constants.outputStream.println(i + 2 + ".");
list.get(i).printBoard();
}
Constants.outputStream.println("\nDone.");
}
}
}
/**
* attempts to solve the board by:
* repeatedly making the best move possible by using a calculated heuristic at each step
* @return SearchTree
*/
private SearchTree autoSolve() {
Constants.outputStream.println("Solving puzzle automatically..........................");
Node v = new Node(null, this);
SearchTree tree = new SearchTree(v);
boolean unsolvable = false;
while (!v.board.isSolved() && !unsolvable) {
ArrayList<Board> children = v.board.getChildren();
for (Board b : children) {
tree.addNode(new Node(v.board, b));
}
Node nextMove = tree.pop();
if (nextMove == null) {
unsolvable = true;
} else {
v = nextMove;
}
}
return tree;
}
/**
* Calculates the intended coordinate of a given integer.
* ex:
* 1's intended coordinate in a 3x3 grid is (0,0)
* 2's intended coordinate in a 3x3 grid is (0,1)
* 8's intended coordinate in a 3x3 grid is (2,1)
* @param n
* @return a coordinate with the intended position of n
*/
private static Coordinate getIntendedCoordinate(int n) {
int intX = (n - 1) / Constants.dimX;
int intY = (n - 1) % Constants.dimY;
return new Coordinate(intX, intY);
}
/**
* calculates the number of moves required to get a given number into it's intended location
* @param n
* @return
*/
private int movesFromIntendedSlot(int n) {
Coordinate currCoordinate = mapFromIntegerToCoord.get(n);
if (n == 0) {
return Math.abs((Constants.dimX - 1) - currCoordinate.X) + Math.abs((Constants.dimY - 1) - currCoordinate.Y);
} else {
Coordinate intendedCoordinate = getIntendedCoordinate(n);
return Math.abs(intendedCoordinate.X - currCoordinate.X) + Math.abs(intendedCoordinate.Y - currCoordinate.Y);
}
}
/**
* calculates the heuristic of the current board by calculating the moves required to get the number at each index into it's desired index
* @return
*/
public int currentHeuristic() {
int total = 0;
for (int i = 0; i < Constants.dimX; i++) {
for (int j = 0; j < Constants.dimY; j++) {
total += movesFromIntendedSlot(grid[i][j]);
}
}
return total;
}
/**
* returns an ArrayList of board objects containing potential children of the current board
* @return
*/
public ArrayList<Board> getChildren() {
ArrayList<Board> children = new ArrayList<>();
Coordinate posOfZero = mapFromIntegerToCoord.get(0);
if (posOfZero.X + 1 <= Constants.dimX - 1) {
Board aBoard = new Board(this);
aBoard.makeMove(grid[posOfZero.X + 1][posOfZero.Y]);
children.add(aBoard);
}
if (posOfZero.Y + 1 <= Constants.dimY - 1) {
Board aBoard = new Board(this);
aBoard.makeMove(grid[posOfZero.X][posOfZero.Y + 1]);
children.add(aBoard);
}
if (posOfZero.X - 1 >= 0) {
Board aBoard = new Board(this);
aBoard.makeMove(grid[posOfZero.X - 1][posOfZero.Y]);
children.add(aBoard);
}
if (posOfZero.Y - 1 >= 0) {
Board aBoard = new Board(this);
aBoard.makeMove(grid[posOfZero.X][posOfZero.Y - 1]);
children.add(aBoard);
}
return children;
}
}
| sbukhari17/EightTileCommandLine | src/Board.java | 3,219 | //every other index should satisfy its spot | line_comment | en | false |
222409_3 | import java.util.List;
import java.util.ArrayList;
public class Student implements Comparable{
String name;
int idNum;
int gradYear;
int drawNumber;
public List<Course> requests;
public List<Course> schedule;
/**
* @param name: string the student's first and last name;
* @param idNum: int the student's 999 number.
* @param gradYear: 4 digit graduation year.
* @param drawNumber: the draw number determines the student's place in the algorithm.
*/
public Student(String name, int idNum, int gradYear,int drawNumber){
this.name = name;
this.idNum = idNum;
this.gradYear = gradYear;
this.drawNumber = drawNumber;
this.requests = new ArrayList<Course>();
this.schedule = new ArrayList<Course>();
}
/**
* Returns true if idNumbers are the same;
* @param Object: any possible object.
*
* @return boolean: true if idNumbers are the same.
*/
public boolean equals(Object o){
if((o instanceof Student)){
return idNum == ((Student)(o)).idNum;
}
return false;
}
/**
* ToString returns a string representation including
* name, graduation year and draw number.
*/
public String toString(){
return name + " " + gradYear + " " + drawNumber;
}
/**
* Write a compareTo that sorts the student by draw number and
* class year.
* The first person should be a 4th year with draw number 1.
* The last person should be a 1st year with a the largest draw number.
* All 4th years come before all 3rd years, etc.
*
* @return retval:
* 1 if the first thing comes first,
* 0 if they are equal
* -1 if the second thing comes firt.
*/
public int compareTo(Object s){
Student toCompare = (Student)s;
if(this.gradYear < toCompare.gradYear){
return -1;
}
else if(this.gradYear > toCompare.gradYear){
return 1;
}
else{
if(this.drawNumber < toCompare.drawNumber){return -1;}
if(this.drawNumber == toCompare.drawNumber){return 0;}
else{
return 1;
}
}
}
/**
* Check to see if the student is registered for any section of a course.
* @param maybe: Course. The potential course to register for.
*
* @return boolean: true if the student is registered for any section of the course.
*/
public boolean isRegisteredFor(Course maybe){
//TODO
// supposed to check if the dept and the section already exists in the schedule. We should not check the section because
//a class can have different sections. example: check if CMPU 102 already exists. This will check all the sections.
for(Course c: this.schedule){
if(c.dept.equals(maybe.dept) && (c.courseNum == maybe.courseNum)){
return true;
}
}
return false;
}
/**
* @return the total registered credits (limit is 4.5)
*/
public double totalRegisteredCredits(){
double totalCredits = 0.0;
for(Course c : this.schedule){
totalCredits += c.credits;
}
//TODO
return totalCredits;
}
/**
* @param maybe: Course the potential course
*
* @return true if the student already has something at that time.
*/
public boolean hasAConflict(Course maybe){
for (Course c: this.schedule){
if(c.conflictsWith(maybe)){
return true;
}
}
//TODO
return false;
}
}
| Felomondi/Course_Pre-registration_Algorithm- | Student.java | 881 | /**
* Write a compareTo that sorts the student by draw number and
* class year.
* The first person should be a 4th year with draw number 1.
* The last person should be a 1st year with a the largest draw number.
* All 4th years come before all 3rd years, etc.
*
* @return retval:
* 1 if the first thing comes first,
* 0 if they are equal
* -1 if the second thing comes firt.
*/ | block_comment | en | false |
222572_2 | /* a Soups instance holds
a collection of TriSoup instances,
one for each texture
*/
import java.util.ArrayList;
public class Soups{
private TriSoup[] soups;
// accumulate triangles here
private ArrayList<Triangle> triangles;
// build a "soups" object with
// given number of separate images,
// create empty soup's for each,
// and create empty list of triangles
public Soups( int numTextures ){
soups = new TriSoup[ numTextures ];
for( int k=0; k<soups.length; k++ ){
soups[k] = new TriSoup();
}
triangles = new ArrayList<Triangle>();
}
// add this triangle to soups
public void addTri( Triangle tri ) {
triangles.add( tri );
System.out.println("after adding " + tri + " this soups has " +
triangles.size() + " tris" );
}
// go through list of triangles and add
// them to the soups
public void addTris( ArrayList<Triangle> list ) {
for( int k=0; k<list.size(); k++ ) {
triangles.add( list.get(k) );
}
}
// sort triangles into individual soups
// for each image
public void sortByTexture(){
for( int k=0; k<triangles.size(); k++ ){
Triangle tri = triangles.get(k);
soups[ tri.getTexture() ].add( tri );
}
}
// draw all the TriSoup's
public void draw(){
System.out.println("draw the soups " + this );
// actually draw each soup
for( int k=0; k<soups.length; k++ ){
OpenGL.selectTexture( Pic.get(k) );
System.out.println("soup for texture # " + k +
" has " + soups[k].size() + " triangles" );
soups[ k ].draw();
}
}
// release all the TriSoup's in this soups
public void cleanup(){
for( int k=0; k<soups.length; k++ ){
soups[k].cleanup();
}
}
}
| boxoforanmore/carscene | Soups.java | 502 | // build a "soups" object with | line_comment | en | false |
222663_0 | package src;
/**
* Thanawat Potidet
* 6510450445
* */
public interface State {
void insertQuarter(GumballMachine gm);
void ejectQuarter(GumballMachine gm);
void turnCrank(GumballMachine gm);
void dispense(GumballMachine gm);
}
| ThanawatPtd/ssd-hw-2-uml-state-diagram | src/State.java | 86 | /**
* Thanawat Potidet
* 6510450445
* */ | block_comment | en | true |
223132_1 | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0 ){
int n = sc.nextInt();
int a[] = new int[n];
for (int i = 0 ; i < n ; i++ ) a[i] = sc.nextInt();
Arrays.sort( a );
int min = Integer.MAX_VALUE;
for ( int i = 0 ; i < n - 1 ; i++ ) {
min = Math.min( min , a[i + 1] - a[i] );
}
System.out.println( min );
}
}
}
| harsh-agrwal/Code-chef-Sorting | Racing Horses.java | 238 | /* Name of the class has to be "Main" only if the class is public. */ | block_comment | en | false |
223145_1 | import java.util.Scanner;
class PrimeTracing
{
//this program is For UnderStanding The Tracing Of Prime Number
//this is the Prime Number program in java
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter A Number : ");
int num = sc.nextInt();
boolean flag = true;
for (int i=2;i<num;i++) {
System.out.println(i);
if(num%i==0)
{
System.out.println(num);
flag = false;
break;
}
}
System.out.println(flag?"prime Number":"Not Prime Number.");
}
} | akashm936/JAVA-Learning | PrimeTracing.java | 180 | //this is the Prime Number program in java | line_comment | en | true |
223154_12 | /* Generated By:JavaCC: Do not edit this line. langB.java */
package parser;
import java.io.*;
public class langB implements langBConstants {
final static String Version = "Compilador Beluga - 2013/1";
boolean Menosshort = false; // sa�da resumida = falso
// Define o m�todo "main" da classe langB.
public static void main(String args[]) throws ParseException
{
String filename = ""; // nome do arquivo a ser analisado
langB parser; // analisador l�xico/sint�tico
int i;
boolean ms = false;
System.out.println(Version);
// l� os par�metros passados para o compilador
// verificar a necessidade deste for.
for (i = 0; i < args.length - 1; i++)
{
if ( args[i].toLowerCase().equals("-short") )
ms = true;
else
{
System.out.println("Uso correto deve ser: java langB [-short] arquivo_de_entrada");
System.exit(0);
}
}
if (args[i].equals("-"))
{ // l� da entrada padr�o
System.out.println("Lendo da entrada padrao . . .");
parser = new langB(System.in);
}
else
{ // l� do arquivo
filename = args[args.length-1];
System.out.println("Lendo do arquivo " + filename + " . . .");
try {
parser = new langB(new java.io.FileInputStream(filename));
}
catch (java.io.FileNotFoundException e) {
System.out.println("Arquivo " + filename + " nao .");
return;
}
}
parser.Menosshort = ms;
parser.program(); // chama o m�todo que faz a an�lise
if ( parser.token_source.foundLexError() != 0 ) // verifica se houve erro l�xico
System.out.println(parser.token_source.foundLexError() + " Erros lexicos encontrados");
else
System.out.println("Programa analisado corretamente.");
} // main
static public String im(int x)
{
int k;
String s;
s = tokenImage[x];
k = s.lastIndexOf("\u005c"");
try {s = s.substring(1,k);}
catch (StringIndexOutOfBoundsException e)
{}
return s;
}
void program() throws ParseException {
Token t;
do
{
t = getNextToken();
Token st = t;
while ( st.specialToken != null)
st = st.specialToken;
do {
if ( Menosshort )
System.out.println(st.image + " " +
im(st.kind) + " " +
st.kind);
else
System.out.println("Linha: " + st.beginLine +
" Coluna: " + st.beginColumn +
" " + st.image +
" " + im(st.kind) + " "+t.kind);
st = st.next;
} while (st != t.next);
} while (t.kind != langBConstants.EOF);
}
/** Generated Token Manager. */
public langBTokenManager token_source;
SimpleCharStream jj_input_stream;
/** Current token. */
public Token token;
/** Next token. */
public Token jj_nt;
private int jj_ntk;
private int jj_gen;
final private int[] jj_la1 = new int[0];
static private int[] jj_la1_0;
static private int[] jj_la1_1;
static private int[] jj_la1_2;
static {
jj_la1_init_0();
jj_la1_init_1();
jj_la1_init_2();
}
private static void jj_la1_init_0() {
jj_la1_0 = new int[] {};
}
private static void jj_la1_init_1() {
jj_la1_1 = new int[] {};
}
private static void jj_la1_init_2() {
jj_la1_2 = new int[] {};
}
/** Constructor with InputStream. */
public langB(java.io.InputStream stream) {
this(stream, null);
}
/** Constructor with InputStream and supplied encoding */
public langB(java.io.InputStream stream, String encoding) {
try { jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
token_source = new langBTokenManager(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 0; i++) jj_la1[i] = -1;
}
/** Reinitialise. */
public void ReInit(java.io.InputStream stream) {
ReInit(stream, null);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream stream, String encoding) {
try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
token_source.ReInit(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 0; i++) jj_la1[i] = -1;
}
/** Constructor. */
public langB(java.io.Reader stream) {
jj_input_stream = new SimpleCharStream(stream, 1, 1);
token_source = new langBTokenManager(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 0; i++) jj_la1[i] = -1;
}
/** Reinitialise. */
public void ReInit(java.io.Reader stream) {
jj_input_stream.ReInit(stream, 1, 1);
token_source.ReInit(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 0; i++) jj_la1[i] = -1;
}
/** Constructor with generated Token Manager. */
public langB(langBTokenManager tm) {
token_source = tm;
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 0; i++) jj_la1[i] = -1;
}
/** Reinitialise. */
public void ReInit(langBTokenManager tm) {
token_source = tm;
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 0; i++) jj_la1[i] = -1;
}
private Token jj_consume_token(int kind) throws ParseException {
Token oldToken;
if ((oldToken = token).next != null) token = token.next;
else token = token.next = token_source.getNextToken();
jj_ntk = -1;
if (token.kind == kind) {
jj_gen++;
return token;
}
token = oldToken;
jj_kind = kind;
throw generateParseException();
}
/** Get the next Token. */
final public Token getNextToken() {
if (token.next != null) token = token.next;
else token = token.next = token_source.getNextToken();
jj_ntk = -1;
jj_gen++;
return token;
}
/** Get the specific Token. */
final public Token getToken(int index) {
Token t = token;
for (int i = 0; i < index; i++) {
if (t.next != null) t = t.next;
else t = t.next = token_source.getNextToken();
}
return t;
}
private int jj_ntk() {
if ((jj_nt=token.next) == null)
return (jj_ntk = (token.next=token_source.getNextToken()).kind);
else
return (jj_ntk = jj_nt.kind);
}
private java.util.List<int[]> jj_expentries = new java.util.ArrayList<int[]>();
private int[] jj_expentry;
private int jj_kind = -1;
/** Generate ParseException. */
public ParseException generateParseException() {
jj_expentries.clear();
boolean[] la1tokens = new boolean[67];
if (jj_kind >= 0) {
la1tokens[jj_kind] = true;
jj_kind = -1;
}
for (int i = 0; i < 0; i++) {
if (jj_la1[i] == jj_gen) {
for (int j = 0; j < 32; j++) {
if ((jj_la1_0[i] & (1<<j)) != 0) {
la1tokens[j] = true;
}
if ((jj_la1_1[i] & (1<<j)) != 0) {
la1tokens[32+j] = true;
}
if ((jj_la1_2[i] & (1<<j)) != 0) {
la1tokens[64+j] = true;
}
}
}
}
for (int i = 0; i < 67; i++) {
if (la1tokens[i]) {
jj_expentry = new int[1];
jj_expentry[0] = i;
jj_expentries.add(jj_expentry);
}
}
int[][] exptokseq = new int[jj_expentries.size()][];
for (int i = 0; i < jj_expentries.size(); i++) {
exptokseq[i] = jj_expentries.get(i);
}
return new ParseException(token, exptokseq, tokenImage);
}
/** Enable tracing. */
final public void enable_tracing() {
}
/** Disable tracing. */
final public void disable_tracing() {
}
}
| lucasperin/Beluga | AL/src/langB.java | 2,482 | /** Generated Token Manager. */ | block_comment | en | true |
223395_0 |
class Employee{
int salary;
String name;
public int getSalary(){
return salary;
}
public String getName(){
return name;
}
public void setName(String n){
name = n;
}
}
class CellPhone{
public void ring(){
System.out.println("Ringing...");
}
public void vibrate(){
System.out.println("Vibrating...");
}
public void callFriend(){
System.out.println("Calling Mukul...");
}
}
class Square{
int side;
public int area(){
return side*side;
}
public int perimeter(){
return 4*side;
}
}
class routine{
public void wakeup()
{
System.out.println("I wake up at 4 o'clock daily");
}
public void breakfast(){
System.out.println("have at 8 o'clock");}
}
class Tommy{
public void hit(){
System.out.println("Hitting the enemy");
}
public void run(){
System.out.println("Running from the enemy");
}
public void fire(){
System.out.println("Firing on the enemy");
}
}
class rectangle{
int l,b;
public int area()
{
return l*b;
}
public int perimeter()
{
return 2*(l+b);
}
}
public class Custom_practice{
public static void main(String[] args) {
/*
// Problem 1
Employee harry = new Employee();
harry.setName("CodeWithHarry");
harry.salary = 233;
System.out.println(harry.getSalary());
System.out.println(harry.getName());
// Problem 2
CellPhone asus = new CellPhone();
asus.callFriend();
asus.vibrate();
//asus.ring();
// Problem 3
Square sq = new Square();
sq.side = 3;
System.out.println(sq.area());
System.out.println(sq.perimeter());
// Problem 5
Tommy player1 = new Tommy();
player1.fire();
player1.run();
player1.hit();
routine kalash = new routine();
kalash.wakeup();
kalash.breakfast(); */
rectangle rec = new rectangle();
rec.l = 5;
rec.b = 6;
System.out.println(rec.area());
System.out.println(rec.perimeter());
}
} | Kalashtyagi/java-programs | Custom_practice.java | 607 | /*
// Problem 1
Employee harry = new Employee();
harry.setName("CodeWithHarry");
harry.salary = 233;
System.out.println(harry.getSalary());
System.out.println(harry.getName());
// Problem 2
CellPhone asus = new CellPhone();
asus.callFriend();
asus.vibrate();
//asus.ring();
// Problem 3
Square sq = new Square();
sq.side = 3;
System.out.println(sq.area());
System.out.println(sq.perimeter());
// Problem 5
Tommy player1 = new Tommy();
player1.fire();
player1.run();
player1.hit();
routine kalash = new routine();
kalash.wakeup();
kalash.breakfast(); */ | block_comment | en | true |
223422_0 | import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class JResortCalculator extends JFrame implements ItemListener {
final int BASE_PRICE= 200;
final int WEEKEND_PREMIUM=100;
final int BREAKFAST_PREMIUM= 20;
final int GOLF_PREMIUM= 75;
int totalPrice= BASE_PRICE;
JCheckBox weekendBox= new JCheckBox ("Weekend premium $" + WEEKEND_PREMIUM, false);
JCheckBox breakfastBox= new JCheckBox ("Breakfast $" + BREAKFAST_PREMIUM, false);
JCheckBox golfBox= new JCheckBox("Golf $" + GOLF_PREMIUM,false);
JLabel resortlabel = new JLabel("Resort Price Calculator");
JLabel pricelabel= new JLabel("The price for your stay is");
JTextField totPrice= new JTextField(4);
JLabel optionExplainLabel= new JLabel ("Base price for a room is $" + BASE_PRICE+ ".");
JLabel optionExplainLabel2= new JLabel ("Check the options you want");
public JResortCalculator() {
super("Resort Price Estimator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
add(resortlabel);
add(optionExplainLabel);
add(optionExplainLabel2);
add(weekendBox);
add(breakfastBox);
add(golfBox);
add(pricelabel);
add(totPrice);
totPrice.setText("$" + totalPrice);
weekendBox.addItemListener(this);
breakfastBox.addItemListener(this);
golfBox.addItemListener(this);
}
@Override
public void itemStateChanged(ItemEvent event)
{
Object source= event.getSource();
int select= event.getStateChange();
if (source==weekendBox)
if (select==ItemEvent.SELECTED)
totalPrice+=WEEKEND_PREMIUM;
else totalPrice-=WEEKEND_PREMIUM;
else if (source == breakfastBox)
{
if (select==ItemEvent.SELECTED)
totalPrice+=BREAKFAST_PREMIUM;
else totalPrice-= BREAKFAST_PREMIUM;
}
else // if (source == golfBox) by default
if (select == ItemEvent.SELECTED)
totalPrice += GOLF_PREMIUM;
else
totalPrice -= GOLF_PREMIUM;
totPrice.setText("$" +totalPrice);
}
public static void main (String[] args)
{
JResortCalculator aFrame= new JResortCalculator();
final int WIDTH =300;
final int HEIGHT= 200;
aFrame.setSize(WIDTH, HEIGHT);
aFrame.setVisible(true);
}
}
| RitaB-afk/src | JResortCalculator.java | 647 | // if (source == golfBox) by default | line_comment | en | true |
223732_3 | package Plants;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import Scenes.Playing;
import UI.Point;
import Helpz.Audio;
public class Plants{
protected int type;
protected int health;
protected boolean idle=true, threaten=false, exploded=false;
protected Timer timer, timer2, timer3; //set timer
protected int x, y; //array for plant location [5][9]
private int cw=74, ch=76; //cherrybomb
private static int[][] occ = new int[5][10];
private static Point[][] coor = new Point[5][9]; //array for plants coordinate
private Clip clip, clip2;
private Thread tcherry; //thread for waiting time
public Plants(int type, int x, int y){
this.type=type;
this.x=x;
this.y=y;
if(type.equals(4)){ //Wallnut
health = 1000;
}else if(type.equals(5)){ //Cherrybomb
health = 200;
tcherry = new Thread(new CherryWaits());
try{
clip = AudioSystem.getClip();
clip2 = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(Audio.class.getResource(("../data/sfx/Cherry_enlarge.wav"))));
clip2.open(AudioSystem.getAudioInputStream(Audio.class.getResource(("../data/sfx/Cherrybomb.wav"))));
}catch(Exception ex){
ex.printStackTrace();
}
}else{}
}
//getter
public int getX(){return x;}
public int getY(){return y;}
public int getType(){return type;}
public int getHealth(){return health;}
public boolean isThreaten(){return threaten;}
public static int getOcc(int x, int y){return occ[x][y];}
public static Point getCoor(int x, int y){return coor[x][y];}
public boolean isIdle(){return idle;}
//setter
public static void setOcc(int i, int j){
occ[i][j]=0;
}
public static void setCoor(int i, int j){
coor[i][j]=new Point(296+j*81,117+i*98);
}
public void setThreat(boolean threat){
threaten=threat;
}
public boolean put(int x, int y, int type){
if(occ[x][y]==0){ //empty spot
occ[x][y]=(int)type;
Playing.plants.add(new Plants(type, x, y));
return true;
}else{
return false;
}
}
public void attack(){
timer.start();
if(getType() == 3){ //repeater
timer2.start();
}
idle=false;
}
public void hit(int damage){
health-=damage;
}
//check is Actor dead
public boolean isDead(){
return health<=0;
}
public void act(){
timer3.start();
}
public void stop(){
timer.stop();
timer2.stop();
timer3.stop();
idle=true;
}
//cherrybomb
//private class Threading
private class CherryWaits implements Runnable {
public void run() {
try{
Thread.sleep(800); //Exploded cherry waits for 800 milliseconds
} catch (InterruptedException e) {}
}
}
public void startTimer(){
tcherry.start();
}
public void enlarge(){
cw+=1; ch+=1;
}
public int getCw(){return cw;}
public int getCh(){return ch;}
public boolean isExploded(){return exploded;}
public boolean isTcherryAlive(){return tcherry.isAlive();}
public void setExplode(){
exploded=true;
}
public void cherry_enlarge(){ //play cherry_enlarge sound
clip.start();
}
public void cherrybomb(){ //play cherrybomb sound
clip.stop();
clip2.start();
}
}
| Ho-Gia-Khang/Plants-vs-Zombies | Plants/Plants.java | 1,005 | //array for plants coordinate | line_comment | en | true |
223821_0 | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
// write your code here
Scanner scn=new Scanner(System.in);
int n=scn.nextInt();
printDecreasing(n);
}
public static void printDecreasing(int n){
// Base condition ->3
if(n==0) {
return ;
}
// My work ->2
System.out.println(n);
// faith ->1
printDecreasing(n-1);
}
}
| kartikeyaGUPTA45/Pepcoding-FJP-05 | Recursion/Print decreasing.java | 132 | // write your code here | line_comment | en | true |
223860_0 | /**
* Copyright (C) 2021, 2023
* *** *** *
* 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 <https://www.gnu.org/licenses/>.
* *** *** *
* Sundquist
*/
package sog.core;
import java.util.Arrays;
import java.util.List;
/**
*
*/
@Test.Subject( "test." )
@FunctionalInterface
public interface Parser<T> {
/**
* Convert the canonical String representation to an instance of type T
*
* @param s
* @return
*/
public T fromString( String s );
/**
* A marker interface for identifying a parser as being a faithful string representation.
*
* To be faithful, a Parser p must satisfy the following two properties:
* F1. For each non-null object t of type T, p.fromString( t.toString() ).equals( t )
* F2. For each String s in the domain of fromString, p.fromString( s ).toString().equals( s )
*/
@FunctionalInterface
public static interface Faithful<T> extends Parser<T> {
@Override
public String toString();
@Override
public T fromString( String s );
}
@Test.Decl( "Throws NumberFormatException for mal-formed string" )
@Test.Decl( "Correct for sample cases" )
@Test.Decl( "Parser.INTEGER satisfies F1" )
@Test.Decl( "Parser.INTEGER does not satisfy F2" )
public static final Parser<Integer> INTEGER = Integer::parseInt;
@Test.Decl( "Throws NumberFormatException for mal-formed string" )
@Test.Decl( "Correct for sample cases" )
@Test.Decl( "Parser.LONG satisfies F1" )
@Test.Decl( "Parser.LONG does not satisfy F2" )
public static final Parser<Long> LONG = Long::parseLong;
@Test.Decl( "Returns false for mal-formed string" )
@Test.Decl( "Correct for sample cases" )
@Test.Decl( "Parser.BOOLEAN satisfies F1" )
@Test.Decl( "Parser.BOOLEAN does not satisfy F2" )
public static final Parser<Boolean> BOOLEAN = Boolean::parseBoolean;
@Test.Decl( "Correct for sample cases" )
@Test.Decl( "Parser.STRING satisfies F1" )
@Test.Decl( "Parser.STRING satisfies F2" )
public static final Parser<String> STRING = String::toString;
@Test.Decl( "Collection of common cases" )
@Test.Decl( "Array of length one allowed" )
@Test.Decl( "Empty array not allowed" )
@Test.Decl( "White space after comma ignored" )
@Test.Decl( "Parser.CSV does not satisfy F1" )
@Test.Decl( "Parser.CSV does not satisfy F2" )
public static final Parser<String[]> CSV = (s) -> s.split( ",\\s*" );
@Test.Decl( "Collection of common cases" )
@Test.Decl( "List of length one allowed" )
@Test.Decl( "Empty list not allowed" )
@Test.Decl( "White space after comma ignored" )
@Test.Decl( "Parser.LIST does not satisfy F1" )
@Test.Decl( "Parser.LSIT does not satisfy F2" )
public static final Parser<List<String>> LIST = (s) -> Arrays.asList( CSV.fromString(s) );
}
| sundquis/sog | src/sog/core/Parser.java | 984 | /**
* Copyright (C) 2021, 2023
* *** *** *
* 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 <https://www.gnu.org/licenses/>.
* *** *** *
* Sundquist
*/ | block_comment | en | true |
223873_1 | import java.util.*;
public class incRecursion {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n =sc.nextInt();
printInc(n);
}
public static void printInc(int n) {
// base case
if(n < 0) {
return;
}
// faith: a func that prints all number till n-1
printInc(n-1);
// my work
System.out.println(n);
}
} | asadakhlaaq2/Hacktoberfest-Project-20222 | Java Codes/incRecursion.java | 119 | // faith: a func that prints all number till n-1 | line_comment | en | true |
223891_58 | import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
* @authorFelipe Custódio, Gabriel Scalici
*/
public class Chain {
// image properties
int h; // height
int w; // width
// shape properties
int height;
int width;
// bitmaps
int pixels[][]; // image with treshold 1 or 0
int visited[][]; // stores visited pixels
// initial coordinates of the shape
int begin[];
// final coordinates of the shape
int end[];
// perimeter
int points;
double perimeter;
public Chain() throws IOException {
// read input file
System.out.print("Filename: ");
String filename = new String();
filename = Input.readString();
File shape = new File(filename);
BufferedImage image = ImageIO.read(shape);
// setar propriedades da image para uso posterior
h = image.getHeight(); // height
w = image.getWidth(); // width
// initialize coordinates vectors
begin = new int[2];
end = new int[2];
points = 0;
perimeter = 0;
// treshold image
pixels = new int[h][w];
visited = new int [h][w];
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
pixels[i][j] = image.getRGB(j, i);
if (pixels[i][j] != -1) {
// shades of gray -> black
pixels[i][j] = 1;
} else {
// background -> white
pixels[i][j] = 0;
}
// set pixel as unvisited
visited[i][j] = 0;
}
}
}
public void firstPixel() {
boolean flag = false;
// locate first black pixel
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
if (pixels[i][j] == 1 && !(flag)) {
// get coordinates
begin[0] = i;
begin[1] = j;
flag = true;
}
}
}
}
public void lastPixel() {
boolean flag = false;
// find first pixel from down-up
for (int i = h - 1; i >= 0; i--) {
for (int j = w - 1; j >= 0; j--) {
if (pixels[i][j] == 1 && !(flag)) {
// get coordinates
end[0] = i;
end[1] = j;
flag = true;
}
}
}
}
public void setHeight() {
// y of last pixel - y of first pixel
height = (end[0] - begin[0] + 1);
}
public void setWidth() {
// get x coordinates of first and final pixels
int aux[] = new int[2];
boolean flag = false;
// find first pixel to the left
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
if (pixels[j][i] == 1 && !(flag)) {
// get x coordinate
aux[0] = i;
flag = true;
}
}
}
flag = false;
// find first pixel to the right
for (int i = w - 1; i >= 0; i--) {
for (int j = h - 1; j >= 0; j--) {
if (pixels[j][i] == 1 && !(flag)) {
// get x coordinate
aux[1] = i;
flag = true;
}
}
}
// x of last pixel - x of first pixel
width = (aux[1] - aux[0] + 1);
}
public void border() {
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
if (pixels[i][j] == 1) {
// if a neighbor of a pixel is empty, that pixel
// is on the border of the shape
if (borderPixel(i, j)) points++;
}
}
}
}
public boolean borderPixel(int i, int j) {
// only check black pixels
if (pixels[i][j] == 0) return false;
// check left
if (j == 0) return true; // image border = shape border
if (j > 0) {
if (pixels[i][j - 1] == 0) {
return true;
}
}
// check up
if (i == 0) return true;
if (i > 0) {
if (pixels[i - 1][j] == 0) {
return true;
}
}
// check right
if (j == w) return true;
if (j < w) {
if (pixels[i][j + 1] == 0) {
return true;
}
}
// check down
if (i == h) return true;
if (i < h) {
if (pixels[i + 1][j] == 0) {
return true;
}
}
// no empty pixel around = not border pixel
return false;
}
public int[] borderNeighbors(int i, int j) {
int index[] = new int[2];
boolean flag = false;
// check around pixel for unvisited border pixels
// calculates chain codes distance
// check east
if (borderPixel(i, j+1) && !flag && !flag && visited[i][j+1] == 0) {
j = j + 1;
System.out.print("0 ");
perimeter += 1;
flag = true;
index[0] = i;
index[1] = j;
return index;
}
// check southeast
if (borderPixel(i+1, j+1) && !flag && visited[i+1][j+1] == 0) {
i = i + 1;
j = j + 1;
System.out.print("1 ");
perimeter += Math.sqrt(2);
flag = true;
index[0] = i;
index[1] = j;
return index;
}
// check south
if (borderPixel(i+1, j) && !flag && visited[i+1][j] == 0) {
i = i + 1;
System.out.print("2 ");
perimeter += 1;
flag = true;
index[0] = i;
index[1] = j;
return index;
}
// check southwest
if (borderPixel(i+1, j-1) && !flag && visited[i+1][j-1] == 0) {
i = i + 1;
j = j - 1;
System.out.print("3 ");
perimeter += Math.sqrt(2);
flag = true;
index[0] = i;
index[1] = j;
return index;
}
// check west
if (borderPixel(i, j-1) && !flag && visited[i][j-1] == 0) {
j = j - 1;
System.out.print("4 ");
perimeter += 1;
flag = true;
index[0] = i;
index[1] = j;
return index;
}
// check northwest
if (borderPixel(i-1, j-1) && !flag && visited[i-1][j-1] == 0) {
i = i - 1;
j = j - 1;
System.out.print("5 ");
perimeter += Math.sqrt(2);
flag = true;
index[0] = i;
index[1] = j;
return index;
}
// check north
if (borderPixel(i-1, j) && !flag && visited[i-1][j] == 0) {
i = i - 1;
System.out.print("6 ");
perimeter += 1;
flag = true;
index[0] = i;
index[1] = j;
return index;
}
// check northeast
if (borderPixel(i-1, j+1) && !flag && visited[i-1][j+1] == 0) {
i = i - 1;
j = j + 1;
System.out.print("7 ");
perimeter += Math.sqrt(2);
flag = true;
index[0] = i;
index[1] = j;
return index;
}
// no neighbor border pixels
index[0] = i;
index[1] = j;
return index;
}
public void chainCodes(int i, int j) {
/*
i e j = index of current pixel
index[0], index[1] = next border pixel (if exists)
*/
// coordinates of current pixel
int[] index = new int[2];
// check for border pixels around
index = borderNeighbors(i, j);
// set pixel as visited
visited[i][j] = 1;
// if next border pixel is visited, we're back to the first pixel
if (visited[index[0]][index[1]] == 0) {
chainCodes(index[0], index[1]);
} else {
System.out.println();
}
}
public static void main(String[] args) throws IOException {
Chain c = new Chain();
// get key coordinates
c.firstPixel();
c.lastPixel();
// calculate shape properties
c.setHeight();
c.setWidth();
System.out.println("Shape width: " + c.width);
System.out.println("Shape height: " + c.height);
// generate chain codes
// get coordinates of first border pixel after initial
int[] index = new int[2];
System.out.print("Chain Codes: ");
index = c.borderNeighbors(c.begin[0], c.begin[1]);
c.chainCodes(index[0], index[1]);
// get perimeter size
c.border();
System.out.println("Border pixels: " + c.points + " pixels");
System.out.println("Shape perimeter: " + c.perimeter);
}
} | felipecustodio/chain-codes | Chain.java | 2,581 | // generate chain codes | line_comment | en | false |
224093_2 | import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
static int currentIndex = 0;
static int currentLine = 1;
public static void main(String[] args) throws IOException {
//read input file
File f=new File("input.txt");
FileReader fr=new FileReader(f);
BufferedReader br=new BufferedReader(fr);
//Call identify for the very first time with initial inputs.
identify(br, br.readLine());
}
/*This function stands for reading new line, it also checks whether there are new line or not, also sets the current
variables. It is a must to use this function*/
public static String readLn(BufferedReader br) throws IOException {
currentLine++;
currentIndex=0;
String line = br.readLine();
if (line == null){
System.out.println("End Of File");
return null;
}
return line;
}
/*
This function stands for reading next character. It also increments currentIndex.
*/
public static char readNextCh(String line) throws IOException {
return line.charAt(++currentIndex);
}
/*Identify is the main function that reads new characters and lines, then categorizes.
* Functions shouldn't call identify always, because end of the identify function, it calls itself recursively.*/
public static void identify(BufferedReader br, String line) throws IOException {
//if current line finished, go to next line. If it is null, then return
if (line.length()<currentIndex+1){
line = readLn(br);
if (line == null)
return;
}
//Because we want to get the current char, we didn't call readNextCh. But in other cases, we should use.
char ch = line.charAt(currentIndex);
//Bracket Control
switch (ch){
case '(':
System.out.println("LEFTPAR "+currentLine+":"+ ++currentIndex);
break;
case ')':
System.out.println("RIGHTPAR "+currentLine+":"+ ++currentIndex);
break;
case '[':
System.out.println("LEFTSQUAREB "+currentLine+":"+ ++currentIndex);
break;
case ']':
System.out.println("RIGHTSQUAREB "+currentLine+":"+ ++currentIndex);
break;
case '{':
System.out.println("LEFTCURLYB "+currentLine+":"+ ++currentIndex);
break;
case '}':
System.out.println("RIGHTCURLYB "+currentLine+":"+ ++currentIndex);
break;
default: //Will be deleted, for now, currentIndex must be incremented in somewhere.
//IMPORTANT: If you are working on your function, DELETE THIS DEFAULT PART and do not forget
//to increment currentIndex if none of the tokens are available now.
++currentIndex;
}
//Check if it is a letter
//Check if it is a number
//All cases must be checked here.
/*YOUR FUNCTIONS MUST BE HERE!*/
//Recursion baby, there must be no code after this line in this function.
identify(br,line);
}
} | mtlgkbb20/Lexical-Analyzer | src/Main.java | 692 | /*This function stands for reading new line, it also checks whether there are new line or not, also sets the current
variables. It is a must to use this function*/ | block_comment | en | true |
224232_9 | package packt;
import com.aliasi.tokenizer.IndoEuropeanTokenizerFactory;
import edu.stanford.nlp.ling.HasWord;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import edu.stanford.nlp.process.CoreLabelTokenFactory;
import edu.stanford.nlp.process.DocumentPreprocessor;
import edu.stanford.nlp.process.PTBTokenizer;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import opennlp.tools.cmdline.postag.POSModelLoader;
import opennlp.tools.namefind.NameFinderME;
import opennlp.tools.namefind.TokenNameFinderModel;
import opennlp.tools.postag.POSModel;
import opennlp.tools.postag.POSSample;
import opennlp.tools.postag.POSTaggerME;
import opennlp.tools.tokenize.SimpleTokenizer;
import opennlp.tools.tokenize.Tokenizer;
import opennlp.tools.tokenize.TokenizerME;
import opennlp.tools.tokenize.TokenizerModel;
import opennlp.tools.tokenize.WhitespaceTokenizer;
import opennlp.tools.util.Span;
public class Chapter1 {
public static void main(String[] args) {
// apacheOpenNLPExample();
// stanfordNLPExample();
lingpipeExamples();
// findingPartsOfText();
// findingSentences();
// findingPeopleAndThings();
// nameFinderExample();
// detectingPartsOfSpeechExample();
// extractingRelationshipsExample();
}
private static void apacheOpenNLPExample() {
try (InputStream is = new FileInputStream(
new File("C:\\OpenNLP Models", "en-token.bin"))) {
TokenizerModel model = new TokenizerModel(is);
Tokenizer tokenizer = new TokenizerME(model);
String tokens[] = tokenizer.tokenize("He lives at 1511 W. Randolph.");
for (String a : tokens) {
System.out.print("[" + a + "] ");
}
System.out.println();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
private static void stanfordNLPExample() {
PTBTokenizer ptb = new PTBTokenizer(
new StringReader("He lives at 1511 W. Randolph."),
new CoreLabelTokenFactory(), null);
while (ptb.hasNext()) {
System.out.println(ptb.next());
}
}
private static void lingpipeExamples() {
List<String> tokenList = new ArrayList<>();
List<String> whiteList = new ArrayList<>();
String text = "A sample sentence processed \nby \tthe "
+ "LingPipe tokenizer.";
com.aliasi.tokenizer.Tokenizer tokenizer = IndoEuropeanTokenizerFactory.INSTANCE.
tokenizer(text.toCharArray(), 0, text.length());
tokenizer.tokenize(tokenList, whiteList);
for (String element : tokenList) {
System.out.print(element + " ");
}
System.out.println();
}
private static void splitMethodDemonstration() {
String text = "Mr. Smith went to 123 Washington avenue.";
String tokens[] = text.split("\\s+");
for (String token : tokens) {
System.out.println(token);
}
}
private static void findingPartsOfText() {
String text = "Mr. Smith went to 123 Washington avenue.";
String tokens[] = text.split("\\s+");
for (String token : tokens) {
System.out.println(token);
}
}
private static void findingSentences() {
String paragraph = "The first sentence. The second sentence.";
Reader reader = new StringReader(paragraph);
DocumentPreprocessor documentPreprocessor
= new DocumentPreprocessor(reader);
List<String> sentenceList = new LinkedList<String>();
for (List<HasWord> element : documentPreprocessor) {
StringBuilder sentence = new StringBuilder();
List<HasWord> hasWordList = element;
for (HasWord token : hasWordList) {
sentence.append(token).append(" ");
}
sentenceList.add(sentence.toString());
}
for (String sentence : sentenceList) {
System.out.println(sentence);
}
}
private static void findingPeopleAndThings() {
String text = "Mr. Smith went to 123 Washington avenue.";
String target = "Washington";
int index = text.indexOf(target);
System.out.println(index);
}
private static void nameFinderExample() {
try {
String[] sentences = {
"Tim was a good neighbor. Perhaps not as good a Bob "
+ "Haywood, but still pretty good. Of course Mr. Adam "
+ "took the cake!"};
Tokenizer tokenizer = SimpleTokenizer.INSTANCE;
TokenNameFinderModel model = new TokenNameFinderModel(new File(
"C:\\OpenNLP Models", "en-ner-person.bin"));
NameFinderME finder = new NameFinderME(model);
for (String sentence : sentences) {
// Split the sentence into tokens
String[] tokens = tokenizer.tokenize(sentence);
// Find the names in the tokens and return Span objects
Span[] nameSpans = finder.find(tokens);
// Print the names extracted from the tokens using the Span data
System.out.println(Arrays.toString(
Span.spansToStrings(nameSpans, tokens)));
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
private static void detectingPartsOfSpeechExample() {
String sentence = "POS processing is useful for enhancing the "
+ "quality of data sent to other elements of a pipeline.";
POSModel model = new POSModelLoader()
.load(new File("C:/Current Books/NLP and Java/Models/", "en-pos-maxent.bin"));
POSTaggerME tagger = new POSTaggerME(model);
String tokens[] = WhitespaceTokenizer.INSTANCE
.tokenize(sentence);
String[] tags = tagger.tag(tokens);
POSSample sample = new POSSample(tokens, tags);
String posTokens[] = sample.getSentence();
String posTags[] = sample.getTags();
for (int i = 0; i < posTokens.length; i++) {
System.out.print(posTokens[i] + " - " + posTags[i]);
}
System.out.println();
for (int i = 0; i < tokens.length; i++) {
System.out.print(tokens[i] + "[" + tags[i] + "] ");
}
}
private static void extractingRelationshipsExample() {
Properties properties = new Properties();
properties.put("annotators", "tokenize, ssplit, parse");
StanfordCoreNLP pipeline = new StanfordCoreNLP(properties);
Annotation annotation = new Annotation(
"The meaning and purpose of life is plain to see.");
pipeline.annotate(annotation);
pipeline.prettyPrint(annotation, System.out);
}
}
| PacktPublishing/Natural-Language-Processing-with-Java-Second-Edition | Chapter01/Chapter1.java | 1,716 | // Find the names in the tokens and return Span objects | line_comment | en | true |
224516_0 | import java.util.*;
class NumberTheory {
static ArrayList<Integer> primes = new ArrayList();
/**Generate all prime numbers less than or equal to n. Sieve of Eratosthenes
* There are approximately n/log n prime numbers < n
* O(n*log(log n))
* @param n The largest number to consider
* @return All prime numbers less than or equal to n*/
static ArrayList<Integer> primes(int n) {
boolean[] visited = new boolean[n+1];
for(int p = 2; p <= n; ++p)
if(!visited[p]) {
primes.add(p);
for(int m = p*p; m <= n && m > p; m += p)
visited[m] = true;
}
return primes;
}
/**Generate a table specifying whether a number is prime or not, for all numbers up to n. Sieve of Eratosthenes
* There are approximately n/log n prime numbers < n
* O(n*log(log n))
* @param n The largest number to consider
* @return Which numbers less than or equal to n are prime*/
static boolean[] primeTable(int n) {
boolean[] primes = new boolean[n+1];
Arrays.fill(primes, true);
primes[0] = false;
primes[1] = false;
for(int p = 2; p <= Math.sqrt(n); ++p)
if(primes[p]) {
for(int m = p*p; m <= n; m += p)
primes[m] = false;
}
return primes;
}
/**Factorize the integer n. primes() must have been run beforehand
* O(sqrt n)
* @param n The number to factorize
* @return A list of primes and their power in the factorization*/
static ArrayList<Pair> factorize(int n) {
ArrayList<Pair> factors = new ArrayList();
for(int p : primes) {
if(p*p > n)
break;
int count = 0;
while(n%p == 0) {
count++;
n /= p;
}
if(count > 0)
factors.add(new Pair(p, count));
}
if(n > 1)
factors.add(new Pair(n, 1));
return factors;
}
/**Count how many times n! can be divided by the prime number p
* <=> Count how many times p appears in the factorization of n!
* O(log n)
* @param n The base of the factorial
* @param p The factor to count
* @return How many times n! can be divided by the prime number p*/
static int factorialDivisible(int n, int p) {
int factor = p;
int count = 0;
while(true) {
int times = n/factor;
if(times <= 0)
break;
count += times;
factor *= p;
}
return count;
}
/**Generate all binomial coefficients a choose b where a, b <= n
* O(n^2)
* @param n The largest binomial coefficient to generate
* @return An array where index [i][j] is the binomial coefficient i choose j*/
static int[][] binomialCoefficients(int n) {
int[][] pascal = new int[n+1][n+1];
for(int i = 1; i <= n; ++i) {
pascal[i][0] = 1;
for(int j = 1; j <= i; ++j)
pascal[i][j] = pascal[i-1][j-1] + pascal[i-1][j];
}
return pascal;
}
/**Find the binomial coefficient n choose k = n!/(k!*(n-k)!)
* O(k) time, O(1) space
* @param n Number of elements to choose from
* @param k Number of elements to choose
* @return Number of ways to choose k from n elements*/
static long binomialCoefficient(int n, int k) {
long res = 1;
if(n/2 < k)
k = n-k;
for(int i = 1; i <= k; ++i) {
res *= (n-i+1);
res /= i;
}
return res;
}
/**Generate the n first Catalan numbers
* O(n^2)
* @param n How many numbers to generate
* @return An array where index [i] is the i-th Catalan number*/
static int[] catalanNumbers(int n) {
int[] catalan = new int[n+1];
catalan[0] = 1;
for(int i = 1; i <= n; ++i)
for(int j = 0; j < i; ++j)
catalan[i] += catalan[j]*catalan[i-j-1];
return catalan;
}
/**Find the greatest common divisor of a and b. Euclid's division algorithm
* O(log min(|a|, |b|))
* @param a The first number
* @param b The second number
* @return The greatest common divisor*/
static int gcd(int a, int b) {
while(b != 0) {
int t = b;
b = a%b;
a = t;
}
return Math.abs(a);
}
/**Calculate Bezout's identity: x and y, such that a*x+b*y = gcd(a, b). Euclid's extended algorithm
* O((log min(|a|, |b|))^2)
* @param a The first number
* @param b The second number
* @return <x, y, z> such that a*x+b*y = gcd(a, b) = z*/
static Triple bezoutsIdentity(int a, int b) {
int[] t = {1, 0};
int[] s = {0, 1};
int[] r = {b, a};
int pos = 0;
while(r[pos] != 0) {
int npos = (pos+1)%2;
int q = r[npos]/r[pos];
r[npos] -= q*r[pos];
s[npos] -= q*s[pos];
t[npos] -= q*t[pos];
pos = npos;
}
pos = (pos+1)%2;
if(r[pos] < 0)
return new Triple(-s[pos], -t[pos], -r[pos]);
return new Triple(s[pos], t[pos], r[pos]);
}
/**Calculate the modular multiplicative inverse of a modulo m. Euclid's extended algorithm
* O((log min(|a|, |b|))^2)
* @param a A non-negative integer
* @param m An integer > 1
* @return The modular multiplicative inverse x such that ax === 1 (mod m), -1 if a and m are not coprime*/
static int multiplicativeInverse(int a, int m) {
Triple t = bezoutsIdentity(a, m);
if(t.trd != 1)
return -1;
return (t.fst+m)%m;
}
}
| halseth/algo_cheatsheet | NumberTheory.java | 1,726 | /**Generate all prime numbers less than or equal to n. Sieve of Eratosthenes
* There are approximately n/log n prime numbers < n
* O(n*log(log n))
* @param n The largest number to consider
* @return All prime numbers less than or equal to n*/ | block_comment | en | false |
224575_2 | package nachos.threads;
import java.util.PriorityQueue;
import nachos.machine.*;
/**
* Uses the hardware timer to provide preemption, and to allow threads to sleep
* until a certain time.
*/
public class Alarm {
/**
* Allocate a new Alarm. Set the machine's timer interrupt handler to this
* alarm's callback.
*
* <p>
* <b>Note</b>: Nachos will not function correctly with more than one alarm.
*/
public Alarm() {
Machine.timer().setInterruptHandler(new Runnable() {
public void run() {
timerInterrupt();
}
});
waitingPQ = new PriorityQueue<ThreadWake>();
}
/**
* The timer interrupt handler. This is called by the machine's timer
* periodically (approximately every 500 clock ticks). Causes the current
* thread to yield, forcing a context switch if there is another thread that
* should be run.
*/
public void timerInterrupt() {
boolean intStatus = Machine.interrupt().disable();
while (waitingPQ.peek() != null && Machine.timer().getTime() >= waitingPQ.peek().getWakeTime()) {
waitingPQ.poll().getThreadToWake().ready();
}
Machine.interrupt().restore(intStatus);
KThread.yield();
}
/**
* Put the current thread to sleep for at least <i>x</i> ticks, waking it up
* in the timer interrupt handler. The thread must be woken up (placed in
* the scheduler ready set) during the first timer interrupt where
*
* <p>
* <blockquote> (current time) >= (WaitUntil called time)+(x) </blockquote>
*
* @param x the minimum number of clock ticks to wait.
*
* @see nachos.machine.Timer#getTime()
*/
public void waitUntil(long x) {
// for now, cheat just to get something working (busy waiting is bad)
long wakeTime = Machine.timer().getTime() + x;
ThreadWake toAdd = new ThreadWake(KThread.currentThread(), wakeTime);
boolean intStatus = Machine.interrupt().disable();
waitingPQ.add(toAdd);
KThread.sleep();
Machine.interrupt().restore(intStatus);
}
private PriorityQueue<ThreadWake> waitingPQ;
private static class PingAlarmTest implements Runnable {
PingAlarmTest(int which, Alarm alarm) {
this.which = which;
this.alarm = alarm;
}
Alarm alarm;
public void run() {
System.out.println("thread " + which + " started.");
alarm.waitUntil(which);
System.out.println("Current Time: " + Machine.timer().getTime());
System.out.println("thread " + which + " ran.");
}
private int which;
}
public static void selfTest() {
Alarm myAlarm = new Alarm();
System.out.println("*** Entering Alarm self test");
KThread thread1 = new KThread(new PingAlarmTest(1000,myAlarm));
thread1.fork();
KThread thread2 = new KThread(new PingAlarmTest(500,myAlarm));
thread2.fork();
new PingAlarmTest(2000,myAlarm).run();
System.out.println("*** Exiting Alarm self test");
}
}
| Kodyin/EECS211-Nachos | threads/Alarm.java | 815 | /**
* The timer interrupt handler. This is called by the machine's timer
* periodically (approximately every 500 clock ticks). Causes the current
* thread to yield, forcing a context switch if there is another thread that
* should be run.
*/ | block_comment | en | false |
224576_0 | import mpi.* ;
public class Pi {
public static void main(String[] args) {
int rank, size, i;
double pi125dt = 3.141592653589793238462643;
pi125dt = Math.PI;
double h, sum, x;
MPI.Init(args);
size = MPI.COMM_WORLD.Size();
rank = MPI.COMM_WORLD.Rank();
int[] n = new int[1];
double[] mypi = new double[1];
double[] pi = new double[1];
if (rank == 0)
n[0] = 1000000; // number of intervals
MPI.COMM_WORLD.Bcast(n, 0, 1, MPI.INT, 0);
h = 1.0 / (double) n[0];
sum = 0.0;
for (i = rank + 1; i <= n[0]; i += size) {
x = h * ((double) i - 0.5);
sum += (4.0 / (1.0 + x * x));
}
mypi[0] = h * sum;
System.out.println("Rank: " + rank + ", mezivysledek: " + mypi[0]);
MPI.COMM_WORLD.Reduce(mypi, 0, pi, 0, 1, MPI.DOUBLE, MPI.SUM, 0);
if (rank == 0) {
System.out.println("__________________________________________");
System.out.println("Pi is approximately " + pi[0]);
System.out.println("Error is: " + (pi[0] - pi125dt));
}
MPI.Finalize();
}
}
| MachOndrej/DPG | cv3_mpi/src/Pi.java | 418 | // number of intervals | line_comment | en | true |
224642_1 | import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class DomesticFlight extends JFrame
{
JComboBox CBFrom, CBTo, CBClass, CBAdult, CBChildren, CBInfant;
JLabel LFrom, LTo, LBookingDate, LClass, LAdult, LChildren, LInfant, LBookingDetails, LPassengerDetails, LDate, LImg1, LImg2, LNotes;
JTextField TFBookingDate;
Icon img1, img2;
JButton BFindFlight;
JPanel PPanel1, PPanel2;
LoginPage type1;
public DomesticFlight(LoginPage type1)
{
Container c =getContentPane();
c.setLayout(new BorderLayout());
String[] sItem1={"Trivandrum"};
String[] sItem2 ={ "Bangalore", "Chennai ", "Delhi", "Goa", "Hyderabad", "Kolkata", "Lucknow", "Mumbai", "Vishakapatnam" };
String[] sItem3={"Economic","Business"};
this.type1 = type1;
PPanel1 = new JPanel(null);
PPanel1.setPreferredSize(new Dimension(500,200));
LBookingDetails = new JLabel("<html><b><font color=\"#C71585\">Booking Details</font></b></html>");
LFrom = new JLabel("From :");
LTo = new JLabel("To :");
LBookingDate = new JLabel("Booking Date:");
LClass = new JLabel("Class :");
CBFrom = new JComboBox(sItem1);
CBTo = new JComboBox(sItem2);
CBClass = new JComboBox(sItem3);
TFBookingDate = new JTextField(10);
LDate = new JLabel("(DD/MM/YYYY)");
LDate.setForeground(Color.red);
img1=new ImageIcon("map1.jpg");
LImg1 = new JLabel(img1);
BFindFlight = new JButton("Find Flight");
LBookingDetails.setBounds(20,3,100,20);
LFrom.setBounds(20,40,100,20);
CBFrom.setBounds(100,40,100,20);
LTo.setBounds(20,100,100,20);
CBTo.setBounds(100,100,100,20);
LBookingDate.setBounds(14,160,100,20);
TFBookingDate.setBounds(100,160,100,20);
LDate.setBounds(210,160,100,20);
LClass.setBounds(20,220,100,20);
CBClass.setBounds(100,220,100,20);
BFindFlight.setBounds(50,270,100,25);
LImg1.setBounds(0,290,495,260);
PPanel1.add(LBookingDetails);
PPanel1.add(LFrom);
PPanel1.add(CBFrom);
PPanel1.add(LTo);
PPanel1.add(CBTo);
PPanel1.add(LBookingDate);
PPanel1.add(TFBookingDate);
PPanel1.add(LDate);
PPanel1.add(LClass);
PPanel1.add(CBClass);
PPanel1.add(BFindFlight);
PPanel1.add(LImg1);
PPanel1.setBackground(Color.white);
c.add(PPanel1,BorderLayout.WEST);
PPanel2 = new JPanel(null);
PPanel2.setPreferredSize(new Dimension(320,160));
LPassengerDetails=new JLabel("<html><b><font color=\"#C71585\">PassengerDetails</font></b></html>");
LAdult = new JLabel("Adults(12+)");
LChildren = new JLabel("Children(2-11)");
LInfant = new JLabel("Infants(under 2)");
String[] item4={"1","2","3","4","5","6"};
CBAdult = new JComboBox(item4);
String[] item5={"0","1","2","3","4"};
CBChildren = new JComboBox(item5);
String[] item6={"0","1","2","3"};
CBInfant = new JComboBox(item6);
img2 = new ImageIcon("note_bg.gif");
LImg2 = new JLabel(img2);
LNotes = new JLabel("<html><body><p>NOTE: Bookings with International Credit Cards <p> have temporarily been suspended.This Service<p> will resume shortly and we will have a notice<p> posted on our website.We regret any <p>inconvenience caused to our passengers.</body></html>");
LPassengerDetails.setBounds(40,3,100,20);
LAdult.setBounds(40,40,100,20);
CBAdult.setBounds(140,40,100,20);
LChildren.setBounds(40,105,100,20);
CBChildren.setBounds(140,105,100,20);
LInfant.setBounds(40,170,100,20);
CBInfant.setBounds(140,170,100,20);
LImg2.setBounds(16,220,320,200);
LNotes.setBounds(55,240,380,180);
PPanel2.add(LPassengerDetails);
PPanel2.add(LAdult);
PPanel2.add(LChildren);
PPanel2.add(LInfant);
PPanel2.add(CBAdult);
PPanel2.add(CBChildren);
PPanel2.add(CBInfant);
PPanel2.add(LNotes);
PPanel2.add(LImg2);
PPanel2.setBackground(Color.white);
c.add(PPanel2,BorderLayout.EAST);
setSize(795,580);
setVisible(true);
BFindFlight.addActionListener(new button3(this, type1));
}
public static void main(String args[])
{
LoginPage type1=null;
new DomesticFlight(type1);
}
}
class button3 implements ActionListener
{
DomesticFlight type;
LoginPage type1;
button3(DomesticFlight type, LoginPage type1)
{
this.type = type;
this.type1 = type1;
}
public void actionPerformed(ActionEvent e)
{
String sFrom = (String)type.CBFrom.getSelectedItem();
String sTo = (String)type.CBTo.getSelectedItem();
String sClass = (String)type.CBClass.getSelectedItem();
String sBookingDate = type.TFBookingDate.getText();
Integer iPrice=0;
String sTime="";
Integer iAdult = Integer.parseInt((String)type.CBAdult.getSelectedItem());
Integer iChildren = Integer.parseInt((String)type.CBChildren.getSelectedItem());
Integer iInfant = Integer.parseInt((String)type.CBInfant.getSelectedItem());
int i = 0;
if(sClass.equals("Economic"))
{
try{
while(i<20)
{
if(type1.row1[i][1].equals(sTo))
{
iPrice = Integer.parseInt((String)type1.row1[i][2]);
sTime = (String)type1.row1[i][3];
break;
}
i++;
}
}catch(Exception e1)
{
JOptionPane.showMessageDialog(null, "You have no rights to access");
System.exit(0);
}
}
else
{
try
{
while(i<20)
{
if(type1.row1[i][1].equals(sTo))
{
iPrice = Integer.parseInt((String)type1.row3[i][2]);
sTime = (String)type1.row3[i][3];
break;
}
i++;
}
}catch(Exception e1)
{
JOptionPane.showMessageDialog(null, "You have no rights to access it");
System.exit(0);
}
}
type.setTitle(iPrice + " " + sTime);
iPrice = (iPrice*iAdult)+(iPrice*(iChildren/2));
int iCount=0;
int iSeatCount=0;
String[] sTempFrom=new String[1250];
String[] sTempTo=new String[1250];
String[] sTempClass=new String[1250];
String[] sTempBookingDate=new String[1250];
String[] sTempTime=new String[1250];
Integer[] iTempAdult=new Integer[1250];
Integer[] iTempChildren=new Integer[1250];
Integer[] iTempInfant=new Integer[1250];
Integer[] iTempPrice=new Integer[1250];
try
{
//read from data
Save2 save1;
ObjectInputStream OIS1 = new ObjectInputStream(new FileInputStream("save2"));
do
{
save1 = (Save2)OIS1.readObject();
sTempFrom[iCount] = save1.sFrom;
sTempTo[iCount] = save1.sTo;
sTempClass[iCount] = save1.sClass;
sTempBookingDate[iCount] = save1.sBookingDate;
sTempTime[iCount] = save1.sTime;
iTempAdult[iCount] = save1.iAdult;
iTempChildren[iCount] = save1.iChildren;
iTempInfant[iCount] = save1.iInfant;
iTempPrice[iCount] = save1.iPrice;
iCount++;
if(save1.sBookingDate.equals(sBookingDate))
if(save1.sTo.equals(sTo))
iSeatCount=iSeatCount + save1.iAdult + save1.iChildren + save1.iInfant;
}while(save1!=null);
OIS1.close();
}
catch(Exception e1)
{
}
iSeatCount = iSeatCount + iAdult + iChildren + iInfant;
if(iSeatCount > 60)
{
JOptionPane.showMessageDialog(null,"Seats are full. Sorry!");
}
else
{
int iChoice = JOptionPane.showConfirmDialog(null,"Seats available. Do you want to Book now?");
if(iChoice == JOptionPane.YES_OPTION)
{
new PrintTicket1(sFrom, sTo, sClass, iAdult, iChildren, iInfant, sBookingDate, iPrice, sTime);
try
{
//write into data
Save2 save2=new Save2(sFrom, sTo, sClass, iAdult, iChildren, iInfant, sBookingDate, iPrice, sTime);
ObjectOutputStream OOS1 = new ObjectOutputStream(new FileOutputStream("save2"));
for(i=0;i<iCount;i++)
{
Save2 temp1=new Save2(sTempFrom[i], sTempTo[i], sTempClass[i], iTempAdult[i], iTempChildren[i], iTempInfant[i], sTempBookingDate[i], iTempPrice[i], sTempTime[i]);
OOS1.writeObject(temp1);
System.out.println(temp1);
}
OOS1.writeObject(save2);
OOS1.close();
}catch(Exception e1)
{
System.out.println(e1);
}
}
else
{
}
}
}
}
class Save2 implements Serializable
{
String sFrom, sTo, sClass, sBookingDate, sTime;
Integer iPrice, iAdult, iChildren, iInfant;
// int iCount;
public Save2(String sFrom, String sTo, String sClass, Integer iAdult, Integer iChildren, Integer iInfant, String sBookingDate, Integer iPrice, String sTime)
{
this.sFrom=sFrom;
this.sTo=sTo;
this.sClass=sClass;
this.iAdult=iAdult;
this.iChildren=iChildren;
this.iInfant=iInfant;
this.sBookingDate=sBookingDate;
this.iPrice=iPrice;
this.sTime=sTime;
// this.iCount = iCount;
}
public String toString()
{
return sFrom+" "+sTo+" "+sClass+" "+iAdult+" "+iChildren+" "+iInfant+" "+sBookingDate+" "+iPrice+" "+sTime;
}
} | MacknJeez/airplanebooking | DomesticFlight.java | 3,323 | //write into data
| line_comment | en | true |
224680_1 | package haven;
import java.util.HashSet;
import java.util.Set;
public enum GobTag {
TREE, BUSH, LOG, STUMP, HERB,
ANIMAL, AGGRESSIVE, CRITTER,
DOMESTIC, YOUNG, ADULT,
CATTLE, COW, BULL, CALF,
GOAT, NANNY, BILLY, KID,
HORSE, MARE, STALLION, FOAL,
PIG, SOW, HOG, PIGLET,
SHEEP, EWE, RAM, LAMB,
MENU, PICKUP;
private static final String[] AGGRO = {
"/bear", "/boar", "/troll", "/wolverine", "/badger", "/adder"
};
private static final String[] ANIMALS = {
"/fox", "/swan", "/bat", "/beaver"
};
private static final String[] CRITTERS = {
"/rat", "/swan", "/squirrel", "/silkmoth", "/frog", "/rockdove", "/quail", "/toad", "/grasshopper",
"/ladybug", "/forestsnail", "/dragonfly", "/forestlizard", "/waterstrider", "/firefly", "/sandflea",
"/rabbit", "/crab", "/cavemoth", "/grub", "/hedgehog"
};
private static final boolean DBG = false;
private static final Set<String> UNKNOWN = new HashSet<>();
public static Set<GobTag> tags(Gob gob) {
Set<GobTag> tags = new HashSet<>();
Resource res = gob.getres();
if(res != null) {
String name = res.name;
if(name.startsWith("gfx/terobjs/trees")) {
if(name.endsWith("log") || name.endsWith("oldtrunk")) {
tags.add(LOG);
} else if(name.contains("stump")) {
tags.add(STUMP);
} else {
tags.add(TREE);
}
} else if(name.startsWith("gfx/terobjs/bushes")) {
tags.add(BUSH);
} else if(name.startsWith("gfx/terobjs/herbs/")) {
tags.add(HERB);
} else if(name.startsWith("gfx/kritter/")) {
if(domesticated(gob, name, tags)) {
tags.add(ANIMAL);
tags.add(DOMESTIC);
} else if(ofType(name, CRITTERS)) {
tags.add(ANIMAL);
tags.add(CRITTER);
} else if(ofType(name, AGGRO)) {
tags.add(ANIMAL);
tags.add(AGGRESSIVE);
} else if(ofType(name, ANIMALS)) {
tags.add(ANIMAL);
} else if(DBG && !UNKNOWN.contains(name)) {
UNKNOWN.add(name);
gob.glob.sess.ui.message(name, GameUI.MsgType.ERROR);
System.out.println(name);
}
}
if(anyOf(tags, GobTag.HERB, GobTag.CRITTER)) {
tags.add(PICKUP);
}
if(!anyOf(tags, GobTag.STUMP, GobTag.ANIMAL) || anyOf(tags, GobTag.DOMESTIC)) {
tags.add(MENU);
}
}
return tags;
}
private static boolean ofType(String name, String[] patterns) {
for (String pattern : patterns) {
if(name.contains(pattern)) { return true; }
}
return false;
}
private static boolean domesticated(Gob gob, String name, Set<GobTag> tags) {
if(name.contains("/cattle/")) {
tags.add(CATTLE);
//TODO: add distinction between cow and bull
if(name.endsWith("/calf")) {
tags.add(CALF);
}
return true;
} else if(name.contains("/goat/")) {
tags.add(GOAT);
if(name.endsWith("/billy")) {
tags.add(BILLY);
} else if(name.endsWith("/nanny")) {
tags.add(NANNY);
} else if(name.endsWith("/kid")) {
tags.add(KID);
}
return true;
} else if(name.contains("/horse/")) {
tags.add(HORSE);
if(name.endsWith("/foal")) {
tags.add(FOAL);
} else if(name.endsWith("/mare")) {
tags.add(MARE);
} else if(name.endsWith("/stallion")) {
tags.add(STALLION);
}
return true;
} else if(name.contains("/pig/")) {
tags.add(PIG);
if(name.endsWith("/hog")) {
tags.add(HOG);
} else if(name.endsWith("/piglet")) {
tags.add(PIGLET);
} else if(name.endsWith("/sow")) {
tags.add(SOW);
}
return true;
} else if(name.contains("/sheep/")) {
tags.add(SHEEP);
//TODO: add distinction between ewe and ram
if(name.endsWith("/lamb")) {
tags.add(LAMB);
}
return true;
}
return false;
}
private static boolean anyOf(Set<GobTag> target, GobTag... tags) {
for (GobTag tag : tags) {
if(target.contains(tag)) {return true;}
}
return false;
}
}
| wafflekat/hafen-client | src/haven/GobTag.java | 1,333 | //TODO: add distinction between ewe and ram | line_comment | en | true |
224751_13 | package burp.Utils;
import burp.AutoRepeater;
import burp.BurpExtender;
import burp.IExtensionStateListener;
import burp.Logs.LogEntry;
import burp.Logs.LogManager;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
public class AutoRepeaterMenu implements Runnable, IExtensionStateListener {
private final JRootPane rootPane;
private static ArrayList<AutoRepeater> autoRepeaters;
private static JMenu autoRepeaterJMenu;
private static JMenuItem toggleSettingsVisibility;
private static boolean showSettingsPanel;
public static boolean sendRequestsToPassiveScanner;
public static boolean addRequestsToSiteMap;
public AutoRepeaterMenu(JRootPane rootPane) {
this.rootPane = rootPane;
autoRepeaters = BurpExtender.getAutoRepeaters();
showSettingsPanel = true;
BurpExtender.getCallbacks().registerExtensionStateListener(this);
}
/**
* Action listener for setting visibility
*/
class SettingVisibilityListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
// Toggling settings panel
if (toggleSettingsVisibility.getText().equals("Hide Settings Panel")) {
showSettingsPanel = false;
toggleSettingsVisibility.setText("Show Settings Panel");
} else {
showSettingsPanel = true;
toggleSettingsVisibility.setText("Hide Settings Panel");
}
// toggling every AutoRepeater tab
for (AutoRepeater ar : autoRepeaters) {
ar.toggleConfigurationPane(showSettingsPanel);
}
}
}
/**
* Action listener for import settings menu
*/
class ImportSettingListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
final JFileChooser importPathChooser = new JFileChooser();
int replaceTabs = JOptionPane.showConfirmDialog(rootPane, "Would you like to replace the current tabs?", "Replace Tabs", JOptionPane.YES_NO_CANCEL_OPTION);
if (replaceTabs == 2) {
// cancel selected
return;
}
int returnVal = importPathChooser.showOpenDialog(rootPane);
if (returnVal != JFileChooser.APPROVE_OPTION) {
BurpExtender.getCallbacks().printOutput("Cannot open a file dialog for importing settings.");
return;
}
File file = importPathChooser.getSelectedFile();
String fileData = Utils.readFile(file);
if (fileData.equals("")) {
// file empty
return;
}
if (replaceTabs == 1) {
// do not replace current tabs
BurpExtender.initializeFromSave(fileData, false);
} else if (replaceTabs == 0) {
// replace current tabs
BurpExtender.getCallbacks().printOutput("Removing Tabs");
BurpExtender.initializeFromSave(fileData, true);
}
}
}
/**
* Action listener for export settings menu.
*/
class ExportSettingListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
Object[] options = {"Current Tab", "Every Tab", "Cancel"};
int option = JOptionPane.showOptionDialog(rootPane, "Which tab would you like to export?", "Export Tabs",
JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
if (option == 2) { return; }
final JFileChooser exportPathChooser = new JFileChooser();
int returnVal = exportPathChooser.showSaveDialog(rootPane);
if (returnVal != JFileChooser.APPROVE_OPTION) {
BurpExtender.getCallbacks().printOutput("Cannot open a file dialog for exporting settings.");
return;
}
File file = exportPathChooser.getSelectedFile();
try (PrintWriter out = new PrintWriter(file.getAbsolutePath())) {
if (option == 0) {
// export current tab
out.println(BurpExtender.exportSave(BurpExtender.getSelectedAutoRepeater()));
} else if (option == 1) {
// export every tab
out.println(BurpExtender.exportSave());
}
} catch (FileNotFoundException error) {
error.printStackTrace();
}
}
}
/**
* Action listener for export logs menu.
*/
class ExportLogsListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
Object[] options = {"Export", "Cancel"};
final String[] EXPORT_OPTIONS = {"CSV", "JSON"};
final String[] EXPORT_WHICH_OPTIONS = {"All Tab Logs", "Selected Tab Logs"};
final String[] EXPORT_VALUE_OPTIONS = {"Log Entry", "Log Entry + Full HTTP Request"};
final JComboBox<String> exportTypeComboBox = new JComboBox<>(EXPORT_OPTIONS);
final JComboBox<String> exportWhichComboBox = new JComboBox<>(EXPORT_WHICH_OPTIONS);
final JComboBox<String> exportValueComboBox = new JComboBox<>(EXPORT_VALUE_OPTIONS);
final JFileChooser exportLogsPathChooser = new JFileChooser();
JPanel exportLogsPanel = new JPanel();
exportLogsPanel.setLayout(new BoxLayout(exportLogsPanel, BoxLayout.PAGE_AXIS));
exportLogsPanel.add(exportWhichComboBox);
exportLogsPanel.add(exportValueComboBox);
exportLogsPanel.add(exportTypeComboBox);
JPanel buttonPanel = new JPanel();
exportLogsPanel.add(buttonPanel);
int option = JOptionPane.showOptionDialog(rootPane, exportLogsPanel,
"Export Logs", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
if (option == 1) {
return;
}
int returnVal = exportLogsPathChooser.showSaveDialog(rootPane);
if (returnVal != JFileChooser.APPROVE_OPTION) {
BurpExtender.getCallbacks().printOutput("Cannot open a file dialog for exporting logs.");
return;
}
AutoRepeater autoRepeater = BurpExtender.getSelectedAutoRepeater();
LogManager logManager = autoRepeater.getLogManager();
File file = exportLogsPathChooser.getSelectedFile();
ArrayList<LogEntry> logEntries = new ArrayList<>();
// collect relevant entries
if ((exportWhichComboBox.getSelectedItem()).equals("All Tab Logs")) {
logEntries = autoRepeater.getLogTableModel().getLog();
} else if ((exportWhichComboBox.getSelectedItem()).equals("Selected Tab Logs")) {
int[] selectedRows = autoRepeater.getLogTable().getSelectedRows();
for (int row : selectedRows) {
logEntries.add(logManager.getLogEntry(autoRepeater.getLogTable().convertRowIndexToModel(row)));
}
}
// determine if whole request should be exported or just the log contents
boolean exportFullHttp = !((exportValueComboBox.getSelectedItem()).equals("Log Entry"));
try (PrintWriter out = new PrintWriter(file.getAbsolutePath())) {
if ((exportTypeComboBox.getSelectedItem()).equals("CSV")) {
out.println(Utils.exportLogEntriesToCsv(logEntries, exportFullHttp));
} else if ((exportTypeComboBox.getSelectedItem()).equals("JSON")) {
out.println(Utils.exportLogEntriesToJson(logEntries, exportFullHttp));
}
} catch (FileNotFoundException error) {
error.printStackTrace();
}
}
}
class DuplicateCurrentTabListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JsonArray serializedTab = BurpExtender.exportSaveAsJson(BurpExtender.getSelectedAutoRepeater());
for (JsonElement tabConfiguration : serializedTab) {
BurpExtender.addNewTab(tabConfiguration.getAsJsonObject());
}
}
}
@Override
public void extensionUnloaded() {
// unregister menu
JMenuBar burpMenuBar = rootPane.getJMenuBar();
BurpExtender.getCallbacks().printOutput("Unregistering menu");
burpMenuBar.remove(autoRepeaterJMenu);
burpMenuBar.repaint();
}
@Override
public void run() {
JMenuBar burpJMenuBar = rootPane.getJMenuBar();
autoRepeaterJMenu = new JMenu("AutoRepeater");
// initialize menu items and add action listeners
JMenuItem duplicateCurrentTab = new JMenuItem("Duplicate Selected Tab");
duplicateCurrentTab.addActionListener(new DuplicateCurrentTabListener());
toggleSettingsVisibility = new JMenuItem("Hide Settings Panel");
toggleSettingsVisibility.addActionListener(new SettingVisibilityListener());
JCheckBoxMenuItem toggleSendRequestsToPassiveScanner = new JCheckBoxMenuItem("Send Requests To Passive Scanner");
toggleSendRequestsToPassiveScanner.addActionListener(l ->
sendRequestsToPassiveScanner = toggleSendRequestsToPassiveScanner.getState());
JCheckBoxMenuItem toggleAddRequestsToSiteMap = new JCheckBoxMenuItem("Add Requests To Site Map");
toggleAddRequestsToSiteMap.addActionListener(l ->
addRequestsToSiteMap = toggleAddRequestsToSiteMap.getState());
JMenuItem showImportMenu = new JMenuItem("Import Settings");
showImportMenu.addActionListener(new ImportSettingListener());
JMenuItem showExportMenu = new JMenuItem("Export Settings");
showExportMenu.addActionListener(new ExportSettingListener());
JMenuItem showExportLogsMenu = new JMenuItem("Export Logs");
showExportLogsMenu.addActionListener(new ExportLogsListener());
// add menu items to the menu
autoRepeaterJMenu.add(duplicateCurrentTab);
autoRepeaterJMenu.add(toggleSettingsVisibility);
autoRepeaterJMenu.addSeparator();
autoRepeaterJMenu.add(toggleAddRequestsToSiteMap);
autoRepeaterJMenu.add(toggleSendRequestsToPassiveScanner);
autoRepeaterJMenu.addSeparator();
autoRepeaterJMenu.add(showImportMenu);
autoRepeaterJMenu.add(showExportMenu);
autoRepeaterJMenu.add(showExportLogsMenu);
// add menu to menu bar
burpJMenuBar.add(autoRepeaterJMenu, burpJMenuBar.getMenuCount() - 2);
}
}
| PortSwigger/auto-repeater | src/burp/Utils/AutoRepeaterMenu.java | 2,275 | // determine if whole request should be exported or just the log contents | line_comment | en | false |
224873_3 |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.MissingFormatArgumentException;
import java.util.Scanner;
/**
* Meant to recommend classes for next quarter based on major, current curriculum, unofficial
* transcripts, and what classes are being offered.
*
* @author albiterri
* @version 1.0
* Last Edited: 04/27/2020
*/
public class RecommendCourses {
private ArrayList<String> curriculumCourses = new ArrayList<>();
private ArrayList<String> takenCourses;
private ArrayList<String> recommendedCourses = new ArrayList<>();
private ArrayList<String> remainingCourses = new ArrayList<>();
private ArrayList<String> electivesNQ = new ArrayList<>();
private ArrayList<Course> prerequisiteRecommendations = new ArrayList<>();
/**
* Constructor that calls all logic that eventually will store necessary recommendations
* data into recommendedCourses, remainingCourses, electivesNQ, and prerequisitesRecommendations list
*
* @param major student's major (CS or SE)
* @param nextQuarter upcoming quarter (Fall = 1, Winter = 2, Spring = 3)
* @param curriculumFile student's curriculum (Currently only CS and SE available)
* @param transcriptFile unofficial transcript from my.msoe.edu
* @param offeringsFile offerings.csv from SE2800 blackboard
* @param electivesFile electives.csv from SE800 blackboard
* @param prerequisitesFile prerequisites.csv from SE800 blackboard
* @throws IOException for incorrect files or formatting
*/
public RecommendCourses(String major, String nextQuarter, File curriculumFile, File transcriptFile,
File offeringsFile, File electivesFile, File prerequisitesFile) throws IOException {
if(major.isBlank() | nextQuarter.isBlank()) {
throw new MissingFormatArgumentException("Your have not input a supported major. Please Try Again!");
}
if((major.equals("CS") | major.equals("SE")) &&
(Integer.parseInt(nextQuarter) > 3 && Integer.parseInt(nextQuarter) < 1)) {
parseCurriculum(major,curriculumFile);
takenCourses = new TranscriptParser(transcriptFile).getCoursesTaken();
recommendCourse(major,nextQuarter,offeringsFile,electivesFile, prerequisitesFile);
} else {
throw new IllegalArgumentException("Currently your major (" + major + ") or quarter (" + nextQuarter +
") is not supported for getting recommendations. Please try either CS/SE and quarters 1-3.");
}
}
/**
* Helper function that will parse the curriculum file in order to get what classes
* the student has to take overall.
*
* @param givenMajor student's major
* @param curriculumFile curriculum.csv from SE2800 blackboard
* @throws IOException for incorrect files or formatting
*/
private void parseCurriculum(String givenMajor, File curriculumFile) throws IOException {
String line = "";
String cvsSplitBy = ",";
int section = 0;
boolean majorLine = true;
BufferedReader br = new BufferedReader(new FileReader(curriculumFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] currentLine = line.split(cvsSplitBy);
for(String column: currentLine) {
if(!column.equals(givenMajor) && majorLine) {
section++;
} else if(column.equals(givenMajor) && majorLine) {
break;
}
if(!majorLine) {
curriculumCourses.add(currentLine[section]);
break;
}
}
majorLine = false;
}
if(curriculumCourses.isEmpty()) {
throw new IOException("Current major is not supported. Try CS,SE,CE, or EE");
}
br.close();
}
/**
* Helper function to help breakdown recommendations data including classes for next
* quarter, electives for next quarter, prerequisites for recommended classes, and classes that the student
* has yet to take
*
* @param studentMajor student's major
* @param nextQuarter upcoming quarter
* @param offeringsFile offerings.csv from SE2800 blackboard
* @param electivesFile electives.csv from SE800 blackboard
* @param prerequisitesFile prerequisites.csv from SE800 blackboard
* @throws IOException for incorrect files or formatting
*/
private void recommendCourse(String studentMajor, String nextQuarter, File offeringsFile
, File electivesFile, File prerequisitesFile) throws IOException {
CSVParser recommendParser = new CSVParser();
ArrayList<String> nextQuarterCourses = recommendParser.quarterMajorCourses(offeringsFile
,studentMajor,nextQuarter);
CSVPrerequisite prerequisiteParser = new CSVPrerequisite();
prerequisiteParser.parse(prerequisitesFile);
ArrayList<Course> prerequisiteCourses = prerequisiteParser.getCourses();
for(String course: curriculumCourses) { //Curriculum - Taken = Remaining Classes
if(!takenCourses.contains(course)) {
remainingCourses.add(course);
}
}
for(String course: nextQuarterCourses) { //NextQ - Taken = Recommendations for Next Quarter
if(!takenCourses.contains(course)) {
recommendedCourses.add(course);
}
}
for(String course: recommendedCourses) { //Find prerequisites for recommended courses
Course foundCourse = hasPrerequisite(course,prerequisiteCourses);
if(!foundCourse.getName().equals("BlankCourse")) {
prerequisiteRecommendations.add(foundCourse);
}
}
ArrayList<String> allQuarterClasses = recommendParser.quarterMajorCourses(offeringsFile,
"all",nextQuarter);
ArrayList<String> allElectives = new CSVParser().getElectives(electivesFile,studentMajor,"all");
for(String elective: allElectives) { //Find electives offered next quarter for student's major
if(allQuarterClasses.contains(elective) && !electivesNQ.contains(elective)) {
electivesNQ.add(elective);
}
}
for(String course: electivesNQ) { //Find electives that have prerequisites
Course foundCourse = hasPrerequisite(course,prerequisiteCourses);
if(!foundCourse.getName().equals("BlankCourse")) {
prerequisiteRecommendations.add(foundCourse);
}
}
}
/**
* Helper function used to search through list of courses with prerequisites to find out
* if the given course has any prerequisites.
*
* @param course given course to check for prerequisites
* @param prerequisiteCourses parsed list of prerequisite data
* @return either a blank course or a course with prerequisite datat
*/
private Course hasPrerequisite(String course, ArrayList<Course> prerequisiteCourses) {
Course prereqCourse = new Course("BlankCourse");
for(Course c: prerequisiteCourses) {
if(c.getName().equals(course) && !c.getPrerequisites().isBlank()) {
return c;
}
}
return prereqCourse;
}
public ArrayList<String> getRecommendations() {
return recommendedCourses;
}
public ArrayList<String> getRemainingCourses() {
return remainingCourses;
}
public ArrayList<String> getElectivesNQ() {
return electivesNQ;
}
public ArrayList<Course> getPrerequisiteRecommendations() {
return prerequisiteRecommendations;
}
public static void main(String[] args) throws IOException {
File curriculum = new File(System.getProperty("user.dir") +
"\\docs\\newcurriculum.csv");
File transcriptAlbiter = new File(System.getProperty("user.dir") +
"\\docs\\TranscriptFiles\\transcript.pdf");
File transcriptChapman = new File(System.getProperty("user.dir") +
"\\docs\\TranscriptFiles\\Chapmann_transcript.pdf");
File offerings = new File(System.getProperty("user.dir") +
"\\docs\\offerings.csv");
File electives = new File(System.getProperty("user.dir") +
"\\docs\\electives.csv");
File prerequisites = new File(System.getProperty("user.dir") +
"\\docs\\prerequisites.csv");
Scanner in = new Scanner(System.in);
System.out.print("Enter major you would like to see courses for (Ex: CS, SE, etc): ");
String major = in.nextLine().toUpperCase();
System.out.print("Enter your upcoming quarter (Ex: Fall = 1, Winter = 2, Spring = 3): ");
String nextQuarter = in.nextLine();
RecommendCourses r = new RecommendCourses(major,nextQuarter,curriculum,transcriptChapman
,offerings,electives,prerequisites);
switch (nextQuarter) {
case "1":
nextQuarter = "Fall";
break;
case "2":
nextQuarter = "Winter";
break;
case "3":
nextQuarter = "Spring";
break;
default:
break;
}
System.out.println("\nAs an " + major + " you should take these classes for " + nextQuarter + " quarter:" +
" (Classes may be year specific)");
for(String recommended: r.getRecommendations()) {
System.out.println(recommended);
}
System.out.println("\n\nHere are some electives you can take next quarter: ");
for(String elective: r.getElectivesNQ()) {
System.out.println(elective);
}
System.out.println("\n\nThe following recommended courses have prereqs: ");
for(Course c: r.getPrerequisiteRecommendations()) {
System.out.println(c.getName() + "-- " + c.getPrerequisites());
}
System.out.println("\n\nThese are classes you have yet to take: ");
for(String remaining: r.getRemainingCourses()) {
System.out.println(remaining);
}
}
}
| raalbiteri/Software-Engineering-Process-Scrum-Project | RecommendCourses.java | 2,321 | // use comma as separator | line_comment | en | false |
225434_0 | import org.lwjgl.util.glu.GLU;
public class Camera {
final static float FRACTION = 0.001f;
private float camAngle;
private float x;
private float y;
private float z;
private float lx;
private float lz;
/**
* Creates new Camera instance
*/
public Camera(){
camAngle = 0.0f;
x = 5.0f;
y = 0.0f;
z = 0.0f;
lx = 0.0f;
lz = 0.0f;
}
/**
* Shift the camera right by FRACTION
*/
public void shiftRight(){
camAngle += FRACTION;
lx = (float)Math.sin(camAngle);
lz = -(float)Math.cos(camAngle);
}
/**
* Shift the camera left by FRACTION
*/
public void shiftLeft(){
camAngle -= FRACTION;
lx = (float)Math.sin(camAngle);
lz = -(float)Math.cos(camAngle);
}
/**
* Move forward by FRACTION
*/
public void moveForward(){
x += lx * FRACTION;
z += lz * FRACTION;
}
/**
* Move back by FRACTION
*/
public void moveBack(){
x -= lx * FRACTION;
z -= lz * FRACTION;
}
/**
* Points the camera at the current point viewed
*/
public void moveCamera(){
GLU.gluLookAt(x, y, z,
x + lx, 0, z + lz,
0, 1, 0);
}
}
| eeue56/3DBlocks | src/Camera.java | 423 | /**
* Creates new Camera instance
*/ | block_comment | en | false |
225768_2 |
/* A Naive recursive implementation of LCS problem in java*/
public class LongestCommonSubsequence {
/* Returns length of LCS for X[0..m-1], Y[0..n-1] */
int lcs(char[] X, char[] Y, int m, int n)
{
if (m == 0 || n == 0)
return 0;
if (X[m - 1] == Y[n - 1])
return 1 + lcs(X, Y, m - 1, n - 1);
else
return max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n));
}
/* Utility function to get max of 2 integers */
int max(int a, int b)
{
return (a > b) ? a : b;
}
public static void main(String[] args)
{
LongestCommonSubsequence lcs = new LongestCommonSubsequence();
String s1 = "AGGTAB";
String s2 = "GXTXAYB";
char[] X = s1.toCharArray();
char[] Y = s2.toCharArray();
int m = X.length;
int n = Y.length;
System.out.println("Length of LCS is"
+ " " + lcs.lcs(X, Y, m, n));
}
}
| MaintanerProMax/HacktoberFest2022 | LCS.java | 334 | /* Utility function to get max of 2 integers */ | block_comment | en | false |
225913_0 | package W01.S201250136;
/*
* @Descripttion:
* @version:
* @Author: Lian Jianheng
* @Date: 2021-09-12 09:30:44
* @LastEditors:
* @LastEditTime: 2021-09-12 09:30:45
*/
public class Rock extends Being
{
private int aggressivity;
public Rock(String name, int aggressivity)
{
super(name);
this.aggressivity = aggressivity;
}
int attack()
{
System.out.println("岩石掉下来了!!");
return aggressivity;
}
}
| jwork-2021-attic/jw01-jianhenglian | Rock.java | 184 | /*
* @Descripttion:
* @version:
* @Author: Lian Jianheng
* @Date: 2021-09-12 09:30:44
* @LastEditors:
* @LastEditTime: 2021-09-12 09:30:45
*/ | block_comment | en | true |
226101_0 |
/*=============================================================================
| Assignment: Final Project - Multiple Document Summarization
| Author: Group7 - (Sampath, Ajay, Visesh)
| Grader: Walid Shalaby
|
| Course: ITCS 6190
| Instructor: Srinivas Akella
|
| Language: Java
| Version : 1.8.0_101
|
| Deficiencies: No logical errors.
*===========================================================================*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.io.Text;
/*
* Mapper class to emit cluster center as key and vectors as values
* */
public class KMeansMapper extends Mapper<LongWritable, Text, ClusterCenter, Text> {
private final List<ClusterCenter> centers = new ArrayList<>();
private DistanceMeasurer distanceMeasurer;
/*
* first iteration, k-random centers, in every follow-up iteration we have
* new calculated centers
*/
@SuppressWarnings("deprecation")
@Override
protected void setup(Context context) throws IOException, InterruptedException {
super.setup(context);
Configuration conf = context.getConfiguration();
Path centroids = new Path(conf.get("centroid.path"));
FileSystem fs = FileSystem.get(conf);
try (SequenceFile.Reader reader = new SequenceFile.Reader(fs, centroids, conf)) {
ClusterCenter key = new ClusterCenter();
IntWritable value = new IntWritable();
int index = 0;
while (reader.next(key, value)) {
ClusterCenter clusterCenter = new ClusterCenter(key);
clusterCenter.setClusterIndex(index++);
centers.add(clusterCenter);
}
}
distanceMeasurer = new ManhattanDistance();
}
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
ClusterCenter nearest = null;
double nearestDistance = Double.MAX_VALUE;
String line = value.toString();
String fileName, vectorValues;
String[] fileNameAndValues;
String[] sec = line.split("\t");
if (sec.length == 1) {
fileNameAndValues = line.split("=");
fileName = fileNameAndValues[0];
vectorValues = fileNameAndValues[1];
} else {
fileNameAndValues = sec[1].split("=");
fileName = fileNameAndValues[0];
vectorValues = fileNameAndValues[1];
}
Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher(vectorValues);
String v = null;
while (m.find()) {
v = m.group(1);
}
String[] vec = v.split(",");
double[] vecArray = new double[vec.length];
for (int i = 0; i < vec.length; i++) {
String trim = vec[i].replaceAll("\\s+", "");
vecArray[i] = Double.parseDouble(trim);
}
VectorWritable vw = new VectorWritable(vecArray);
for (ClusterCenter c : centers) {
// calculating manhattan distance between cluster center and vector.
double dist = distanceMeasurer.measureDistance(c.getCenterVector(), vw.getVector());
// assign vector to the nearest center.
if (nearest == null) {
nearest = c;
nearestDistance = dist;
} else {
if (nearestDistance > dist) {
nearest = c;
nearestDistance = dist;
}
}
}
String finalValue = fileName + "=" + vw;
context.write(nearest, new Text(finalValue));
}
}
| pajaydev/Multi-Document-Text-Summarization | KMeansMapper.java | 1,030 | /*=============================================================================
| Assignment: Final Project - Multiple Document Summarization
| Author: Group7 - (Sampath, Ajay, Visesh)
| Grader: Walid Shalaby
|
| Course: ITCS 6190
| Instructor: Srinivas Akella
|
| Language: Java
| Version : 1.8.0_101
|
| Deficiencies: No logical errors.
*===========================================================================*/ | block_comment | en | true |
226857_0 | package toy;
import java.awt.Point;
/**
* saves position and gamma for one user
* @author bzfkroli
*
*/
public class MSData
{
private Point position;
private Double gamma;
public MSData(Point pos, Double demand)
{
position = pos;
gamma = demand;
}
public MSData(int x, int y, double demand)
{
position = new Point(x,y);
gamma = demand;
}
public Point getPosition()
{
return this.position;
}
public double getXPosition()
{
return this.position.getX();
}
public double getYPosition()
{
return this.position.getY();
}
public Double getGamma()
{
return this.gamma;
}
public void setPosition(Point pos)
{
this.position = pos;
}
public void setPosition(int x, int y)
{
this.position = new Point(x,y);
}
public void changePosition(boolean xdir, int l)
{
if(xdir) position.translate(l,0);
else position.translate(0,l);
}
public void setGamma(Double demand)
{
this.gamma = demand;
}
public void changeGamma(Double factor)
{
this.gamma *= factor;
}
}
| viqizevic/Base-Station-Simulation-Environment | toy/MSData.java | 365 | /**
* saves position and gamma for one user
* @author bzfkroli
*
*/ | block_comment | en | true |
227093_0 | import java.util.*;
public class Jon_Snow {
public static void main(String ar[])
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt() ;
int k = sc.nextInt() ;
int x = sc.nextInt() ;
int arr[] = new int[1024] ;
for(int i = 0; i < n; i++)
arr[sc.nextInt()]++;
MiMaStrength(arr,k, x) ;
}
static void MiMaStrength(int arr[], int k, int x)
{
int dp[] = new int[1024] ;
// int cuurentTotal = 0 ;
for(int i = 0 ; i < k ; i++)
{
int currentTotal = 0 ;
int dptemp[] = new int[1024];
for(int j = 0 ; j <= 1023 ; j++)
{
if(arr[j] % 2 == 0)
{
dptemp[j] += arr[j] / 2 ;
dptemp[j ^ x] += arr[j] / 2 ;
}else if(currentTotal % 2 == 0)
{
dptemp[j] = arr[j] / 2;
dptemp[j ^ x] += arr[j] / 2 + 1 ;
}
else
{
dptemp[j ^ x] += arr[j] / 2 ;
dptemp[j] += arr[j] / 2 + 1 ;
}
}
arr = dptemp ;
}
int min = Integer.MAX_VALUE;
for (int i = 0; i <= 1023; i++) {
if (arr[i] != 0) {
min = i;
break;
}
}
int max = Integer.MIN_VALUE;
for (int i = 1023; i >= 1; i--) {
if (arr[i] != 0) {
max = i;
break;
}
}
System.out.println(max + " " + min);
}
}
| pradhuman2022/Ds-Algo | Jon_Snow.java | 514 | // int cuurentTotal = 0 ; | line_comment | en | true |
227115_24 | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.util.stream.Collectors;
public class SnowMan {
private static final int SNOWMAN_MIN_WORD_LENGTH = 5;
private static final int SNOWMAN_MAX_WORD_LENGTH = 8;
private static final int SNOWMAN_MAX_WRONG_GUESSES = 7;
private static final String SNOWMAN_1 = "* * * *";
private static final String SNOWMAN_2 = " * *_ * *";
private static final String SNOWMAN_3 = "* _[_]_ * ";
private static final String SNOWMAN_4 = " * (\") *";
private static final String SNOWMAN_5 = "* \\( : )/ *";
private static final String SNOWMAN_6 = " *(_ : _) *";
private static final String SNOWMAN_7 = "--------------";
private static final String WORDS_FILE_PATH = "words.txt";
private static List<String> WORDS;
static {
WORDS = loadWordsFromFile();
}
public static void StartGame() {
Scanner scanner = new Scanner(System.in);
String snowManWord = getRandomWord(SNOWMAN_MIN_WORD_LENGTH, SNOWMAN_MAX_WORD_LENGTH);
snowMan(snowManWord);
scanner.close();
}
static void snowMan(String snowManWord) {
HashMap<Character, Boolean> snowManWordMap = buildWordDict(snowManWord);
ArrayList<Character> wrongGuessList = new ArrayList<>();
boolean continueGuess = true;
while (wrongGuessList.size() <= SNOWMAN_MAX_WRONG_GUESSES && continueGuess){
Character userInput = getLetterfromUser(snowManWordMap, wrongGuessList);
if (snowManWordMap.containsKey(userInput)){
snowManWordMap.put(userInput,true);
System.out.println("You guessed a letter!");
} else {
wrongGuessList.add(userInput);
System.out.println("The letter is not in the word");
}
printSnowmanGraphic(wrongGuessList.size());
printWordProgressString(snowManWord, snowManWordMap);
printWrongGuessList(wrongGuessList);
if (getWordProgress(snowManWord,snowManWordMap)){
System.out.println("Congratulations, you win!");
continueGuess = false;
} else if (wrongGuessList.size() == SNOWMAN_MAX_WRONG_GUESSES){
System.out.println("Sorry, you lose! The word is "+ snowManWord);
continueGuess = false;
}
}
}
// This method is designed to load words from words.txt
private static List<String> loadWordsFromFile() {
List<String> words = new ArrayList<>();
// starts a try-with-resources block. It creates a BufferedReader to efficiently
// read the contents of a file specified by the WORDS_FILE_PATH.
// The try-with-resources ensures that the BufferedReader is closed properly
// after use.
try (BufferedReader reader = new BufferedReader(new FileReader(WORDS_FILE_PATH))) {
String line;
while ((line = reader.readLine()) != null) {
words.add(line.trim());
}
// This block catches any IOException that might occur during the file reading
// process.
// If an exception occurs, it prints the stack trace to the console using
// e.printStackTrace().
} catch (IOException e) {
e.printStackTrace();
}
return words;
}
public static String getRandomWord(int minLen, int maxLen) {
List<String> filteredWordList = WORDS.stream()
.filter(word -> word.length() >= minLen && word.length() <= maxLen).collect(Collectors.toList());
Random random = new Random();
int randomIndex = random.nextInt(filteredWordList.size());
return filteredWordList.get(randomIndex);
}
// This function prints out the appropriate snowman image
// depending on the number of wrong guesses the player has made.
public static void printSnowmanGraphic(int numWrongGuesses) {
StringBuilder graphic = new StringBuilder();
for (int i = 1; i <= numWrongGuesses; i++) {
if (i == 1) {
// graphic.append(SNOWMAN_1);
System.out.println(SNOWMAN_1);
} else if (i == 2) {
System.out.println(SNOWMAN_2);
} else if (i == 3) {
System.out.println(SNOWMAN_3);
} else if (i == 4) {
System.out.println(SNOWMAN_4);
} else if (i == 5) {
System.out.println(SNOWMAN_5);
} else if (i == 6) {
System.out.println(SNOWMAN_6);
} else if (i == 7) {
System.out.println(SNOWMAN_7);
}
}
}
// This function takes snowmanWord string as input and returns
// a HashMap with a key-value pair for each letter in
// snowmanWord where the key is the letter and the value is `false`.
public static HashMap<Character, Boolean> buildWordDict(String snowmanWord) {
HashMap<Character, Boolean> snowmanWordMap = new HashMap<>();
for (char letter : snowmanWord.toCharArray()) {
snowmanWordMap.put(letter, false);
}
return snowmanWordMap;
}
// This function takes the snowman_word and snowman_word_dict as input.
// It prints an output_string that shows the correct letter guess placements
// as well as the placements for the letters yet to be guessed.
public static void printWordProgressString(String snowmanWord, HashMap<Character, Boolean> snowmanHashMap) {
// String progressString = ""; //string is immutable
StringBuilder progressString = new StringBuilder();
for (char letter : snowmanWord.toCharArray()) {
if (snowmanHashMap.get(letter)) {
progressString.append(letter + " ");
} else {
progressString.append("_ ");
}
}
System.out.println(progressString);
}
// This function takes the snowman_word and snowman_word_dict as input.
// It returns True if all the letters of the word have been guessed, and False
// otherwise.
public static boolean getWordProgress(String snowmanWord, HashMap<Character, Boolean> snowmanHashMap) {
for (char letter : snowmanWord.toCharArray()) {
if (!snowmanHashMap.get(letter)) {
return false;
}
}
return true;
}
// This function takes the snowman_word_dict and the list of characters
// that have been guessed incorrectly (wrong_guesses_list) as input.
// It asks for input from the user of a single character until
// a valid character is provided and then returns this character.
public static Character getLetterfromUser(HashMap<Character, Boolean> snowmanHashMap,
ArrayList<Character> wrongGuessArr) {
boolean validInput = false;
Scanner scanner = new Scanner(System.in);
String userInputString = "";
while (!validInput) {
System.out.println("Guess a letter (Press Ctrl + C to exit the game): ");
userInputString = scanner.nextLine();
if (userInputString.length() > 1) {
System.out.println("You must only enter 1 letter at a time!");
} else {
char userInputChar = Character.toLowerCase(userInputString.charAt(0));
if (!Character.isLetter(userInputChar)) {
System.out.println("You must input a letter!");
} else if (snowmanHashMap.containsKey(userInputChar) && snowmanHashMap.get(userInputChar)) {
System.out.println("You already guessed that letter and it's in the word!");
} else if (isCharinArr(userInputChar, wrongGuessArr)) {
System.out.println("You already guessed that letter and it's not in the word!");
} else {
validInput = true;
}
}
}
return Character.toLowerCase(userInputString.charAt(0));
}
public static boolean isCharinArr(char c, ArrayList<Character> arr) {
for (char ch : arr) {
if (Character.toLowerCase(c) == Character.toLowerCase(ch)) {
return true;
}
}
return false;
}
public static void printWrongGuessList(ArrayList<Character> wrongGuessList){
String guesses = "";
System.out.println("Wrong guesses: ");
for (char guess: wrongGuessList){
guesses+=guess + " ";
}
System.err.println(guesses);
}
}
| goldenkairos/snow-man-java | SnowMan.java | 2,096 | // It asks for input from the user of a single character until | line_comment | en | true |
227534_0 | /*
* Decompiled with CFR 0.152.
*
* Could not load the following classes:
* com.google.common.util.concurrent.FutureCallback
*/
package net;
import com.google.common.util.concurrent.FutureCallback;
import deobf.NetHandlerPlayClient;
import net.minecraft.network.packts.C19PacketResourcePackStatus;
import net.minecraft.network.packts.C19PacketResourcePackStatus$Action;
class PQ
implements FutureCallback<Object> {
String b;
NetHandlerPlayClient a;
public void onFailure(Throwable throwable) {
NetHandlerPlayClient.a(this.a).sendPacket(new C19PacketResourcePackStatus(this.b, C19PacketResourcePackStatus$Action.FAILED_DOWNLOAD));
}
public void onSuccess(Object object) {
NetHandlerPlayClient.a(this.a).sendPacket(new C19PacketResourcePackStatus(this.b, C19PacketResourcePackStatus$Action.SUCCESSFULLY_LOADED));
}
PQ(NetHandlerPlayClient netHandlerPlayClient, String string) {
this.a = netHandlerPlayClient;
this.b = string;
}
}
| oooooomygod/novoline-opensource | net/PQ.java | 286 | /*
* Decompiled with CFR 0.152.
*
* Could not load the following classes:
* com.google.common.util.concurrent.FutureCallback
*/ | block_comment | en | true |
227613_2 | import java.math.BigInteger;
import java.util.Arrays;
import java.util.Scanner;
public class is_fibo {
public static void main(String[] args) {
/*
* Problem Statement
You are given an integer, N. Write a program to determine if N is an element of the Fibonacci Sequence.
The first few elements of fibonacci sequence are 0,1,1,2,3,5,8,13,⋯ A fibonacci sequence is one where every element is a sum of the previous two elements in the sequence. The first two elements are 0 and 1.
Input Format
The first line contains T, number of test cases.
T lines follows. Each line contains an integer N.
Output Format
Display IsFibo if N is a fibonacci number and IsNotFibo if it is not a fibonacci number. The output for each test case should be displayed in a new line.
Constraints
1≤T≤10^5 //Number of test cases can be anywhere up to 10,000
1≤N≤10^10 // Size of number can be anything from 1 to 10,000,000,000 (use long data structure).
Sample Input
3 //number of test cases
5
7
8
Sample Output
IsFibo
IsNotFibo
IsFibo
*/
Scanner stdin = new Scanner(System.in);
long[] fibo = new long[1000];//fibonacci has an approximate lower bound of 1.5^n, so 1000 elements should be more than enough.
fibo[0] = 0;
fibo[1] = 1;
long x = fibo[0] + fibo[1];
int iterator = 2;
while(x < 10000000000L){ //Inside this loop, we preprocess the values of fibonacci up to 10,000,000,000
fibo[iterator] = fibo[iterator-1] + fibo[iterator-2];
iterator++;
x = fibo[iterator-1];
//System.out.println(fibo[iterator-1]);
}
Arrays.sort(fibo);
int numberOfCases = Integer.parseInt(stdin.nextLine());
String input;
BigInteger intInput;
BigInteger output;
for (int a = 0; a < numberOfCases; a++) {
input = stdin.nextLine();
long inputLong = Long.parseLong(input, 10);
if(Arrays.binarySearch(fibo, inputLong) < 0){
// System.out.println("InputLong is fibo" + inputLong);
System.out.println("IsNotFibo");
}
else{
//System.out.println("InputLong is not fibo" + inputLong);
System.out.println("IsFibo");
}
}
}
}
| PeterASteele/HackerRankProblems | is_fibo.java | 718 | //Inside this loop, we preprocess the values of fibonacci up to 10,000,000,000 | line_comment | en | true |
228488_0 | import java.util.ArrayList;
import java.util.Scanner;
public class films {
public static void main(String[] args) {
Applicanion.run();
}
}
class Movie {
int id;
String name;
int creatorID;
int producerID;
int release_dateID;
int total_episodesID;
public Movie(int id, String name, int creatorID, int producerID, int release_dateID, int total_episodesID) {
this.id = id;
this.name = name;
this.creatorID = creatorID;
this.producerID = producerID;
this.release_dateID = release_dateID;
this.total_episodesID = total_episodesID;
}
}
class Producer {
int id;
String name;
public Producer(int id, String name) {
this.id = id;
this.name = name;
}
}
class Release_date {
int id;
String release_date;
public Release_date(int id, String release_date) {
this.id = id;
this.release_date = release_date;
}
}
class Film_duration {
int id;
String film_duration;
public Film_duration(int id, String film_duration) {
this.id = id;
this.film_duration = film_duration;
}
}
class Total_episodes {
int id;
String total_episodes;
public Total_episodes(int id, String total_episodes) {
this.id = id;
this.total_episodes = total_episodes;
}
}
class DataBases {
ArrayList<Movie> film_name = new ArrayList<>();
ArrayList<Producer> producers = new ArrayList<>();
ArrayList<Release_date> date = new ArrayList<>();
ArrayList<Film_duration> duration = new ArrayList<>();
ArrayList<Total_episodes> episodes = new ArrayList<>();
}
class DataBasesAPI {
int filmsIDg;
int producerIDg;
int release_dateIDg;
int durationIDg;
int total_episodesIDg;
DataBases db;
private int get_ProducerIDg() {
return producerIDg++;
}
private int get_Release_dateIDg() {
return release_dateIDg++;
}
private int get_DurationIDg() {
return durationIDg++;
}
private int get_total_episodesIDg() {
return total_episodesIDg++;
}
public void init() {
db = new DataBases();
producerIDg = -1;
Producer Producer_1 = new Producer(get_ProducerIDg(), "Продюсер: Алекс Маркес");
Producer Producer_2 = new Producer(get_ProducerIDg(), "Продюсер: Пётр Точилин");
Producer Producer_3 = new Producer(get_ProducerIDg(), "Продюсер: Андрей Лошак");
db.producers.add(Producer_1);
db.producers.add(Producer_2);
db.producers.add(Producer_3);
release_dateIDg = -1;
Release_date r_date_1 = new Release_date(get_Release_dateIDg(), "Дата выхода: 2016-09-16");
Release_date r_date_2 = new Release_date(get_Release_dateIDg(), "Дата выхода: 2006-08-10");
Release_date r_date_3 = new Release_date(get_Release_dateIDg(), "Дата выхода: 2022-03-01");
db.date.add(r_date_1);
db.date.add(r_date_2);
db.date.add(r_date_3);
durationIDg = -1;
Film_duration f_d_1 = new Film_duration(get_DurationIDg(), "Длительность: 1ч:35м");
Film_duration f_d_2 = new Film_duration(get_DurationIDg(), "Длительность: 1ч:33м");
Film_duration f_d_3 = new Film_duration(get_DurationIDg(), "Длитнльность: 40 минут серия");
db.duration.add(f_d_1);
db.duration.add(f_d_2);
db.duration.add(f_d_3);
total_episodesIDg = -1;
Total_episodes tEpisodes_1 = new Total_episodes(get_total_episodesIDg(), "Всего серий: 1 фильм");
Total_episodes tEpisodes_2 = new Total_episodes(get_total_episodesIDg(), "Всего серий: 1 фильм");
Total_episodes tEpisodes_3 = new Total_episodes(get_total_episodesIDg(), "Всего серий: 7 серий");
db.episodes.add(tEpisodes_1);
db.episodes.add(tEpisodes_2);
db.episodes.add(tEpisodes_3);
db.film_name.add(new Movie(1, "---////----\nФильм: Хакер", 1, 1, 1, 1));
db.film_name.add(new Movie(2, "---////----\\nФильм: Хоттабыч", 2, 2, 2, 2));
db.film_name.add(new Movie(3, "---////----\\nСериал: Холивар", 3, 3, 3, 3));
}
public DataBases get_Bases() {
return db;
}
}
class Film_info {
String name_film;
String producer;
String release_date;
String duration;
String total_episodes;
public Film_info(String name_film, String producer, String release_date, String duration,
String total_episodes) {
this.name_film = name_film;
this.producer = producer;
this.release_date = release_date;
this.duration = duration;
this.total_episodes = total_episodes;
}
@Override
public String toString() {
return String.format("%s -> %s -> %s -> %s -> %s",
name_film,
producer,
release_date,
duration,
total_episodes);
}
}
class Search_film {
DataBases db;
public Search_film(DataBases db) {
this.db = db;
}
public Film_info getFilm(int id) {
Movie f = db.film_name.get(id);
Producer p = db.producers.get(id);
Release_date rD = db.date.get(id);
Film_duration fD = db.duration.get(id);
Total_episodes tE = db.episodes.get(id);
return new Film_info(f.name, p.name, rD.release_date, fD.film_duration, tE.total_episodes);
}
}
class Applicanion {
public static void run(){
Scanner scan = new Scanner(System.in);
System.out.println("Введите id для вывода информации о фильме: \n1-Хакер \n2-Хоттабыч \n3-Холивар\n---////----");
int id_film = scan.nextInt();
scan.close();
DataBasesAPI dbAPI = new DataBasesAPI();
dbAPI.init();
DataBases db = dbAPI.get_Bases();
Search_film sF = new Search_film(db);
if (id_film > 4 & id_film < 1){
System.out.println("Нет id в каталоге");
}else{
System.out.println(sF.getFilm(id_film-1));
}
}
}
| kazakovmakvit/Java | Work_OOP_JAVA/films.java | 1,898 | ////----\nФильм: Хакер", 1, 1, 1, 1)); | line_comment | en | true |
228498_10 | package Java.Vue;
import javax.imageio.ImageIO;
import javax.swing.*;
import Java.Controleur.ChangerPanneau;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
public class GestionFilms extends JPanel{
private MainFrame mainframe;
public GestionFilms(MainFrame mainframe) throws IOException {
this.mainframe=mainframe;
// Utilisation de BorderLayout au lieu de setLayout(null)
setLayout(new BorderLayout());
super.setPreferredSize(new Dimension(600,400));
// Barre noire en haut
JPanel bandeNoirePanel = new JPanel();
bandeNoirePanel.setBackground(Color.BLACK);
bandeNoirePanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 5));
// Texte "Rateflix" à gauche en rouge
JLabel rateflixLabel = new JLabel("Rateflix");
rateflixLabel.setFont(new Font("American Typewriter", Font.BOLD, 20));
rateflixLabel.setForeground(Color.RED);
bandeNoirePanel.add(rateflixLabel);
// Espace entre Rateflix et GP
bandeNoirePanel.add(new JLabel(" "));
// // Liens Gestion des Profils
// JLabel GestionFilmsLabel = new JLabel("Gestion des profils");
// GestionFilmsLabel.setForeground(Color.LIGHT_GRAY);
// GestionFilmsLabel.setFont(new Font("American Typewriter", Font.BOLD, 12));
// bandeNoirePanel.add(GestionFilmsLabel);
initButton(bandeNoirePanel);
// Espace entre GF et GP
bandeNoirePanel.add(new JLabel(" "));
// Liens Gestion des Films
JLabel gestionFilmsLabel = new JLabel("Gestion des films");
gestionFilmsLabel.setForeground(Color.WHITE);
gestionFilmsLabel.setFont(new Font("American Typewriter", Font.BOLD, 12));
bandeNoirePanel.add(gestionFilmsLabel);
// Ajout du bandeau en haut de la page
add(bandeNoirePanel, BorderLayout.NORTH);
// Zone de recherche + zone ajouter un film
JPanel recherchePanel = new JPanel();
recherchePanel.setBackground(Color.WHITE);
JTextField rechercheField = new JTextField(20);
JButton rechercheButton = new JButton("Rechercher");
JButton ajouterFilmButton = new JButton("Ajouter un film");
recherchePanel.add(rechercheField);
recherchePanel.add(rechercheButton);
recherchePanel.add(ajouterFilmButton);
// Ajout de la zone de recherche
recherchePanel.setBounds(0, 35, 600, 35);
add(recherchePanel, BorderLayout.CENTER);
// Panneau pour les images
JPanel imagesPanel = new JPanel();
imagesPanel.setBackground(Color.WHITE);
imagesPanel.setLayout(new GridLayout(0, 4, 5, 5)); ///4 colonnes pour 4 films par lignes
// Dossier contenant les images
File folder = new File("Vue/Movie_Cover");
File[] listOfFiles = folder.listFiles();
// Afficher chaque image dans une colonne avec le titre en dessous et au milieu
if (listOfFiles != null) {
for (File file : listOfFiles) {
if (file.isFile() && isImageFile(file)) {
BufferedImage bufferedImage = ImageIO.read(file);
// Redimensionner l'image
int newWidth = 100;
int newHeight = 150;
Image scaledImage = bufferedImage.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
ImageIcon scaledImageIcon = new ImageIcon(scaledImage);
JLabel imageLabel = new JLabel();
imageLabel.setIcon(scaledImageIcon);
// Ajouter le titre du film en dessous et au milieu de l'image
String fileNameWithoutExtension = file.getName().replaceFirst("[.][^.]+$", ""); // Retirer l'extension du nom de fichier
fileNameWithoutExtension = fileNameWithoutExtension.replace("_", " "); // Remplacer les underscores par des espaces
JLabel titleLabel = new JLabel(fileNameWithoutExtension);
titleLabel.setHorizontalAlignment(JLabel.CENTER);
// Utiliser un GridLayout pour aligner l'image et le titre verticalement
JPanel imageWithTitlePanel = new JPanel();
imageWithTitlePanel.setLayout(new GridLayout(1, 1));
imageWithTitlePanel.add(imageLabel);
imageWithTitlePanel.add(titleLabel);
imagesPanel.add(imageWithTitlePanel);
}
}
}
/// Définir les bounds pour le panneau d'images
imagesPanel.setBorder(BorderFactory.createEmptyBorder(40, 5, 0, 5)); ///espace entre zone de recherche et panneau images
// Utilisation d'une JScrollPane pour permettre le défilement
JScrollPane scrollPane = new JScrollPane(imagesPanel);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
// Ajout du panneau d'images à la partie centrale
add(scrollPane, BorderLayout.CENTER);
// Ajouter un écouteur d'événements au bouton de recherche
rechercheButton.addActionListener(e -> {
// Récupérer le texte saisi dans la zone de recherche
String rechercheText = rechercheField.getText().toLowerCase(); // Convertir en minuscules pour la recherche insensible à la casse
// Filtrer les films en fonction du texte de recherche
imagesPanel.removeAll();
if (listOfFiles != null) {
for (File file : listOfFiles) {
if (file.isFile() && isImageFile(file)) {
String fileNameWithoutExtension = file.getName().replaceFirst("[.][^.]+$", "").replace("_", " ").toLowerCase();
// Vérifier si le titre du film correspond à la recherche
if (fileNameWithoutExtension.contains(rechercheText)) {
BufferedImage bufferedImage = null;
try {
bufferedImage = ImageIO.read(file);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Redimensionner l'image
int newWidth = 100;
int newHeight = 150;
Image scaledImage = bufferedImage.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
ImageIcon scaledImageIcon = new ImageIcon(scaledImage);
JLabel imageLabel = new JLabel();
imageLabel.setIcon(scaledImageIcon);
JLabel titleLabel = new JLabel(fileNameWithoutExtension);
titleLabel.setHorizontalAlignment(JLabel.CENTER);
JPanel imageWithTitlePanel = new JPanel();
imageWithTitlePanel.setLayout(new GridLayout(2, 1));
imageWithTitlePanel.add(imageLabel);
imageWithTitlePanel.add(titleLabel);
(imagesPanel).add(imageWithTitlePanel);
}
}
}
}
// Rafraîchir l'affichage
imagesPanel.revalidate();
imagesPanel.repaint();
});
}
// Vérifier si le fichier est une image
private boolean isImageFile(File file) {
String name = file.getName();
return name.endsWith(".jpg") || name.endsWith(".jpeg") || name.endsWith(".png");
}
private void initButton(JPanel bandeNoirePanel) {
// Liens Gestion des Profils
JButton gestionProfilsLabel = new JButton(new ChangerPanneau(this.mainframe, "Gestion des profils", "PROFILS",null));
gestionProfilsLabel.setForeground(Color.LIGHT_GRAY);
gestionProfilsLabel.setContentAreaFilled(false); // Rend la zone de contenu transparente
gestionProfilsLabel.setBorderPainted(false);
gestionProfilsLabel.setFont(new Font("American Typewriter", Font.BOLD, 12));
bandeNoirePanel.add(gestionProfilsLabel);
}
} | Xav-duru/Projet-RateFlix | Java/Vue/GestionFilms.java | 1,952 | // Liens Gestion des Films
| line_comment | en | true |
228909_11 | /*COMP163 Word Use Count
Dr. Ken Williams
Dorian Holmes
10/12/2017
*/
public class WordUseCount{
public static void main( String[] args) throws java.net.MalformedURLException,java.io.IOException {
java.util.Scanner keyboard = new java.util.Scanner(System.in);
System.out.print("Enter the URL");
String mixedFileName = keyboard.next(); //stores what user enters in
String filename = mixedFileName.toLowerCase(); //makes it lowercase
java.net.URL webFile = new java.net.URL(filename);
java.util.Scanner file = new java.util.Scanner(webFile.openStream()); //opens and declare url as object
int count = 0; // declare variable
System.out.print("Enter word");
String word = keyboard.next().toLowerCase().trim(); //stores word as a lowercase
int find = 0;
int pos = 0;
String line; //declare variable
while(file.hasNext()) {
line = file.nextLine(); // read line
line = line.toLowerCase();// makes line lower case
pos = line.indexOf(word);
while(pos != -1){
count++; //incrument number of loops occuring
pos = line.indexOf(word,pos+1); // find word
}
}
System.out.println( word + " occurs " +count+" time."); // Prints output on screen
}
} | Doetheman/Showcase | WordUseCount.java | 343 | // Prints output on screen
| line_comment | en | true |
228921_8 | /*
Sara Zavala 18893
Hoja de Trabajo 7
Estructura de Datos
Binary Tree: Diccionario
*/
//Codigo referenciado de este link
//www.cs.pomona.edu/classes/cs062/structure5/Association.java
//Lo cambié y me basé para recordar la estructura
//http://www.cs.williams.edu/~jeannie/cs136/javadoc/structure5/structure5/ComparableAssociation.html
//https://stackoverflow.com/questions/52641366/how-to-make-an-object-of-association-comparable-by-only-one-generic-parameter-ty
public class Association<K extends Comparable<K>, V> implements Comparable<Association<K, V>> {
private K key;
private V value;
//Constructor
public Association(K key, V value) {
this.key = key;
this.value = value;
}
//Sets y gets
public void setKey(K key) {
this.key = key;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
//Metodos de Association
public boolean equals(Object other)
{
Association<K,V> otherAssoc = (Association<K,V>)other;
return getKey().equals(otherAssoc.getKey());
}
public int hashCode()
{
return getKey().hashCode();
}
@Override
public int compareTo(Association<K, V> o) {
return key.compareTo(o.getKey());
}
@Override
public String toString() {
return "Association{" +
"key=" + key +
", value=" + value +
'}';
}
}
| saritazavala/HojaTrabajo7 | src/Association.java | 432 | //Metodos de Association | line_comment | en | true |
228939_4 | import java.util.HashMap;
import tester.*;
/**
* Tester for Bakery
*
* @author Michael Hu and William Enright
* @version 6/18/2014
*/
public class ExamplesBakery {
/** example database */
Database d;
/**
* Initializes example KVMaps
*/
public ExamplesBakery() {
d = new Database("orders", "bakeryItems", "ord", "inv");
}
/**
* resets the database
*/
private void reset() {
d = new Database("orders", "bakeryItems", "ord", "inv");
}
/**
* Tests the addOrder method
*
* @param t
* a Tester
*/
public void testAddOrder(Tester t) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(72, 5);
t.checkExpect(d.totalPurchases(), 20);
d.addOrder("Williams", map);
t.checkExpect(d.totalPurchases(), 20);
reset();
}
} | TheMichaelHu/bakery | ExamplesBakery.java | 258 | /**
* Tests the addOrder method
*
* @param t
* a Tester
*/ | block_comment | en | true |
229314_10 | import java.util.ArrayList;
/**
* A Class Representing Owner's Object
* @author User-1
* @version 1.0.0
*/
public class Owner {
private String name = "";
private String ppsNum = "";
private String password = "";
private ArrayList<String> propertiesOwned = new ArrayList<String>();
/**
* @param name Name of owner
* @param ppsNum Personal Public Service Number (ppsNum) of owner
* @param password Password of owner
*/
public Owner(String name, String ppsNum, String password) {
setName(name);
setPpsNum(ppsNum);
setPassword(password);
}
/**
* Method to set name of owner
* @param name name of the owner
*/
public void setName(String name) {
this.name = name;
}
/**
* Method to set pps number
* @param ppsNum Personal Public Service Number of owner
*/
public void setPpsNum(String ppsNum) {
this.ppsNum = ppsNum;
}
/**
* Method to set password (no return type)
* @param password Password of the wner
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Method to return name
* @return value of name
*/
public String getName() {
return name;
}
/**
* Personal Public Service Number
* @return return Personal Public Service Number of the owner
*/
public String getPpsNum() {
return ppsNum;
}
/**
* Show password
* @return password of user
*/
public String getPassword() {
return password;
}
/**
* Add Property to Owner's property list
* @param eircode eircode of Property
*/
public void addProperty(String eircode){
propertiesOwned.add(eircode);
}
/**
* Method to Remove Property from the list using id
* @param propertyId id of Property
*/
public void removeProperty(int propertyId){
propertiesOwned.remove(propertyId);
}
/**
* Get properties list
* @return List of properties Owned
*/
public ArrayList<String> getPropertiesEircodes(){
return propertiesOwned;
}
} | j1m-ryan/CS4013-Project | src/Owner.java | 519 | /**
* Get properties list
* @return List of properties Owned
*/ | block_comment | en | false |
229648_1 | /*
* ****************************************************************************
* Copyright VMware, Inc. 2010-2016. All Rights Reserved.
* ****************************************************************************
*
* This software is made available for use under the terms of the BSD
* 3-Clause license:
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.vmware.performance;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.ws.soap.SOAPFaultException;
import com.vmware.common.annotations.Action;
import com.vmware.common.annotations.Option;
import com.vmware.common.annotations.Sample;
import com.vmware.connection.ConnectedVimServiceBase;
import com.vmware.performance.widgets.LineChart;
import com.vmware.vim25.ArrayOfPerfCounterInfo;
import com.vmware.vim25.ArrayOfPerfInterval;
import com.vmware.vim25.InvalidPropertyFaultMsg;
import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.PerfCounterInfo;
import com.vmware.vim25.PerfEntityMetricBase;
import com.vmware.vim25.PerfEntityMetricCSV;
import com.vmware.vim25.PerfInterval;
import com.vmware.vim25.PerfMetricId;
import com.vmware.vim25.PerfMetricSeriesCSV;
import com.vmware.vim25.PerfQuerySpec;
import com.vmware.vim25.RetrieveOptions;
import com.vmware.vim25.RuntimeFaultFaultMsg;
/**
* <pre>
* VIUsage
*
* This sample creates a GUI for graphical representation of the counters
*
* <b>Parameters:</b>
* url [required] : url of the web service
* username [required] : username for the authentication
* password [required] : password for the authentication
* host [required] : Name of the host
* counter [required] : Full counter name in dotted notation
* (group.counter.rollup)
* e.g. cpu.usage.none
*
* <b>Command Line:</b>
* run.bat com.vmware.performance.VIUsage --url [webserviceurl]
* --username [username] --password [password]
* --host [host name] --counter [Counter_type {group.counter.rollup}]
* </pre>
*/
@Sample(name = "vi-usage", description = "This sample creates a GUI for graphical representation of the counters")
public class VIUsage extends ConnectedVimServiceBase implements ActionListener{
private ManagedObjectReference perfManager;
private ManagedObjectReference propCollectorRef;
private String hostname;
private String countername;
@Option(name = "hostname")
public void setHostname(String hostname) {
this.hostname = hostname;
}
@Option(name = "counter")
public void setCountername(String countername) {
this.countername = countername;
}
private PerfInterval[] intervals;
private LineChart chart;
private JPanel mainPanel, selectPanel, displayPanel;
private JComboBox intervalBox = null;
private JLabel chartLabel = null;
private String stats;
private ManagedObjectReference hostmor;
private JFrame frame;
/**
* Establishes session with the virtual center server.
*
* @throws Exception the exception
*/
void init() {
propCollectorRef = serviceContent.getPropertyCollector();
perfManager = serviceContent.getPerfManager();
}
/**
* @throws Exception
*/
void populateData() throws DatatypeConfigurationException {
createMainPanel();
initChart();
updateChart();
}
/**
* @throws InterruptedException
* @throws Exception
*/
public void displayUsage() throws InvocationTargetException, NoSuchMethodException,
IllegalAccessException, InterruptedException {
stats = countername;
Map<String, ManagedObjectReference> results = null;
try {
results = getMOREFs.inFolderByType(serviceContent.getRootFolder(), "HostSystem",
new RetrieveOptions());
} catch (RuntimeFaultFaultMsg e) {
e.printStackTrace();
} catch (InvalidPropertyFaultMsg e) {
e.printStackTrace();
}
hostmor = results.get(hostname);
if (hostmor == null) {
System.out.println("Host " + hostname + " Not Found");
return;
}
Map<String, Object> prop = null;
try {
prop = getMOREFs.entityProps(perfManager, new String[] { "historicalInterval" });
} catch (InvalidPropertyFaultMsg e) {
e.printStackTrace();
} catch (RuntimeFaultFaultMsg e) {
e.printStackTrace();
}
ArrayOfPerfInterval arrayPerlInterval = (ArrayOfPerfInterval) prop
.get("historicalInterval");
List<PerfInterval> historicalInterval = arrayPerlInterval.getPerfInterval();
intervals = new PerfInterval[historicalInterval.size()];
for (int i = 0; i < historicalInterval.size(); i++) {
intervals[i] = historicalInterval.get(i);
}
if (intervals.length == 0) {
System.out.println("No historical intervals");
return;
}
javax.swing.SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
try {
createAndShowGUI();
} catch (SOAPFaultException sfe) {
printSoapFaultException(sfe);
} catch (Exception ex) {
System.out.println("Exception -: " + ex.getMessage());
ex.printStackTrace();
}
}
});
Thread.currentThread().join();
}
/**
*
*/
private void initChart() {
PerfInterval interval = intervals[intervalBox.getSelectedIndex()];
int period = interval.getSamplingPeriod();
int tickInterval;
String format;
if (period <= 300) {
tickInterval = 3600 / period;
format = "{3}:{4}";
} else if (period <= 3600) {
tickInterval = 6 * 3600 / period;
format = "{1}/{2} {3}:{4}";
} else {
tickInterval = 24 * 3600 / period;
format = "{1}/{2}";
}
int movingAvg = tickInterval;
if (chart != null) {
displayPanel.remove(chart);
}
chart =
new LineChart(tickInterval, period * 1000, format, format,
movingAvg, true);
chart.setPreferredSize(new Dimension(600, 150));
displayPanel.add(chart);
if (frame != null) {
frame.pack();
}
}
@SuppressWarnings("unchecked")
private void updateChart() throws DatatypeConfigurationException {
List<PerfCounterInfo> counterInfoList = new ArrayList<PerfCounterInfo>();
Map<String, Object> prop = null;
try {
prop = getMOREFs.entityProps(perfManager, new String[] { "perfCounter" });
ArrayOfPerfCounterInfo arrayPerfCounterInfo = (ArrayOfPerfCounterInfo) prop
.get("perfCounter");
counterInfoList = arrayPerfCounterInfo.getPerfCounterInfo();
} catch (SOAPFaultException sfe) {
printSoapFaultException(sfe);
} catch (Exception x) {
System.out.println("Error in getting perfCounter property: " + x);
return;
}
if (counterInfoList != null && !counterInfoList.isEmpty()) {
Map<String, PerfCounterInfo> counterMap =
new HashMap<String, PerfCounterInfo>();
for (PerfCounterInfo counterInfo : counterInfoList) {
String group = counterInfo.getGroupInfo().getKey();
String counter = counterInfo.getNameInfo().getKey();
String rollup = counterInfo.getRollupType().value();
String key = group + "." + counter + "." + rollup;
counterMap.put(key, counterInfo);
}
List<PerfMetricId> metricIds = new ArrayList<PerfMetricId>();
String[] statNames = new String[1];
String key = stats;
if (counterMap.containsKey(key)) {
PerfCounterInfo counterInfo = counterMap.get(key);
statNames[0] = counterInfo.getNameInfo().getLabel();
String instance = "";
PerfMetricId pmfids = new PerfMetricId();
pmfids.setCounterId(counterInfo.getKey());
pmfids.setInstance(instance);
metricIds.add(pmfids);
} else {
System.out.println("Unknown counter " + key);
for (PerfCounterInfo counterInfo : counterInfoList) {
String group = counterInfo.getGroupInfo().getKey();
String counter = counterInfo.getNameInfo().getKey();
String rollup = counterInfo.getRollupType().value();
System.out.println("Counter " + group + "." + counter + "."
+ rollup);
}
System.out.println("Select The Counter From This list");
System.exit(1);
}
PerfInterval interval = intervals[intervalBox.getSelectedIndex()];
XMLGregorianCalendar endTime =
DatatypeFactory.newInstance().newXMLGregorianCalendar(
new GregorianCalendar());
PerfQuerySpec querySpec = new PerfQuerySpec();
querySpec.setEntity(hostmor);
querySpec.setFormat("csv");
querySpec.setIntervalId(interval.getSamplingPeriod());
//querySpec.setEndTime(endTime);
querySpec.getMetricId().addAll(metricIds);
List<PerfEntityMetricBase> metrics =
new ArrayList<PerfEntityMetricBase>();
try {
List<PerfQuerySpec> listpqspecs =
Arrays.asList(new PerfQuerySpec[]{querySpec});
List<PerfEntityMetricBase> listpemb =
vimPort.queryPerf(perfManager, listpqspecs);
metrics = listpemb;
} catch (SOAPFaultException sfe) {
printSoapFaultException(sfe);
} catch (Exception x) {
System.out.println("Error in queryPerf: " + x);
return;
}
if (metrics == null || metrics.size() == 0) {
System.out.println("queryPerf returned no entity metrics");
return;
}
PerfEntityMetricBase metric = metrics.get(0);
PerfEntityMetricCSV csvMetric = (PerfEntityMetricCSV) metric;
List<PerfMetricSeriesCSV> lipmscsv = csvMetric.getValue();
List<PerfMetricSeriesCSV> csvSeriesList = lipmscsv;
if (csvSeriesList.size() == 0) {
System.out.println("queryPerf returned no CSV series");
return;
}
String statName = statNames[0];
PerfMetricSeriesCSV csvSeries = csvSeriesList.get(0);
String[] strValues = csvSeries.getValue().split(",");
int[] values = new int[strValues.length];
for (int i = 0; i < strValues.length; ++i) {
values[i] = Integer.parseInt(strValues[i]);
}
chart.setValues(values, endTime.getMillisecond());
displayPanel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder(statName),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
}
}
private void createMainPanel() {
selectPanel = new JPanel();
displayPanel = new JPanel();
chartLabel = new JLabel();
chartLabel.setHorizontalAlignment(JLabel.CENTER);
chartLabel.setVerticalAlignment(JLabel.CENTER);
chartLabel.setVerticalTextPosition(JLabel.CENTER);
chartLabel.setHorizontalTextPosition(JLabel.CENTER);
String[] intervalNames = new String[intervals.length];
for (int i = 0; i < intervals.length; ++i) {
intervalNames[i] = intervals[i].getName();
}
intervalBox = new JComboBox(intervalNames);
selectPanel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("Interval"),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
displayPanel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("Metric Name"),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
displayPanel.add(chartLabel);
selectPanel.add(intervalBox);
intervalBox.addActionListener(this);
mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
mainPanel.add(selectPanel);
mainPanel.add(displayPanel);
}
@Override
public void actionPerformed(ActionEvent event) {
if ("comboBoxChanged".equals(event.getActionCommand())) {
System.out.println("Updating interval");
initChart();
try {
updateChart();
} catch (SOAPFaultException sfe) {
printSoapFaultException(sfe);
} catch (DatatypeConfigurationException ex) {
System.out.println("Error encountered: " + ex);
}
}
}
private void createAndShowGUI() throws DatatypeConfigurationException {
try {
String lookAndFeel = UIManager.getSystemLookAndFeelClassName();
UIManager.setLookAndFeel(lookAndFeel);
JFrame.setDefaultLookAndFeelDecorated(true);
} catch (Exception x) {
x.printStackTrace();
}
populateData();
frame = new JFrame("VIUsage");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addWindowListener(new WindowListener() {
@Override
public void windowOpened(WindowEvent e) {
}
@Override
public void windowIconified(WindowEvent e) {
}
@Override
public void windowDeiconified(WindowEvent e) {
}
@Override
public void windowDeactivated(WindowEvent e) {
}
@Override
public void windowClosing(WindowEvent e) {
try {
connection.disconnect();
} catch (SOAPFaultException sfe) {
printSoapFaultException(sfe);
} catch (Exception ex) {
System.out.println("Failed to disconnect - " + ex.getMessage());
ex.printStackTrace();
}
}
@Override
public void windowClosed(WindowEvent e) {
}
@Override
public void windowActivated(WindowEvent e) {
}
});
frame.setContentPane(mainPanel);
frame.pack();
frame.setVisible(true);
}
private static void printSoapFaultException(SOAPFaultException sfe) {
System.out.println("SOAP Fault -");
if (sfe.getFault().hasDetail()) {
System.out.println(sfe.getFault().getDetail().getFirstChild()
.getLocalName());
}
if (sfe.getFault().getFaultString() != null) {
System.out.println("\n Message: " + sfe.getFault().getFaultString());
}
}
@Action
public void run() throws InvocationTargetException, NoSuchMethodException, IllegalAccessException, InterruptedException {
init();
displayUsage();
}
}
| vmwarecode/VIUsage | VIUsage.java | 3,933 | /**
* <pre>
* VIUsage
*
* This sample creates a GUI for graphical representation of the counters
*
* <b>Parameters:</b>
* url [required] : url of the web service
* username [required] : username for the authentication
* password [required] : password for the authentication
* host [required] : Name of the host
* counter [required] : Full counter name in dotted notation
* (group.counter.rollup)
* e.g. cpu.usage.none
*
* <b>Command Line:</b>
* run.bat com.vmware.performance.VIUsage --url [webserviceurl]
* --username [username] --password [password]
* --host [host name] --counter [Counter_type {group.counter.rollup}]
* </pre>
*/ | block_comment | en | true |
229803_6 | package comp2100.ass1;
import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.URISyntaxException;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import org.json.simple.JSONObject;
/**
* This class is for user to add new person
* @author Zhenyue Qin, u5505995
*
*/
public class AddContacts extends JFrame implements Serializable{
/* The ArrayList persons are all the objects stored */
static ArrayList<Person> persons;//= new ArrayList<Person>();
final JTextField firstName = new JTextField();
final JTextField lastName = new JTextField();
final JTextField number = new JTextField();
final JTextField birthday = new JTextField();
final JTextField email = new JTextField();
final JTextField address = new JTextField();
/* These object are for JComboBox */
static Object selectedDate;
static Object selectedMonth;
static Object selectedYear;
static String imageName;
public AddContacts() {
super("Add New Contacts");
/* The container is everything contained in the frame */
Container container = getContentPane();
container.setLayout(new BorderLayout());
container.setBackground(Color.WHITE);
/* These are the words in the top */
JLabel topWords = new JLabel();
topWords.setText("Please input the information");
topWords.setFont(APPLibrary.arialFifteen);
topWords.setHorizontalAlignment(JLabel.CENTER);
JLabel heading = new JLabel();
heading.setText("New Contact");
heading.setFont(APPLibrary.arielTwentyFive);
heading.setHorizontalAlignment(JLabel.CENTER);
topWords.setForeground(Color.GRAY);
/* Put the words into one panel */
JPanel headings = new JPanel();
headings.setLayout(new GridLayout(0, 1));
headings.add(heading);
headings.add(topWords);
/* These are the buttons */
JPanel inputs = new JPanel();
inputs.setLayout(new GridLayout(0, 2));
inputs.setBackground(Color.WHITE);
/* These are the input fields */
JLabel infoFirstName = new JLabel();
infoFirstName.setText("First Name: ");
inputs.add(infoFirstName);
firstName.setPreferredSize(new Dimension(140, 40));
inputs.add(firstName);
JLabel infoLastName = new JLabel();
infoLastName.setText("Last Name: ");
lastName.setPreferredSize(new Dimension(140, 40));
inputs.add(infoLastName);
inputs.add(lastName);
/* This is to add image */
/* The idea is to copy the image to the current directory and save the path */
/* TRICKY PART */
JButton addImage = new JButton("Add the Profile");
addImage.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//File Chooser: https://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html
/* Get the image from the file chooser */
JFileChooser fc = new JFileChooser();
fc.showOpenDialog(AddContacts.this);
/* The image */
File chosenfile = fc.getSelectedFile();
String newName = chosenfile.getName();
imageName = APPLibrary.getPath + newName;
/* New Image */
File newFile = new File(APPLibrary.getPath + newName);
newFile.getParentFile().mkdirs();
try {
newFile.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
APPLibrary.copyFile(chosenfile, newFile);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
JLabel infoNumber = new JLabel();
infoNumber.setText("Phone number: ");
number.setPreferredSize(new Dimension(140, 40));
inputs.add(infoNumber);
inputs.add(number);
JLabel infoBirthday = new JLabel();
infoBirthday.setText("Birthday (DD/MM/YYYY)");
birthday.setPreferredSize(new Dimension(100,40));
inputs.add(infoBirthday);
/* This is to generate elements for JComboBox */
String[] dates = new String[32];
for (int i=1; i<=31; i++) {
dates[i] = Integer.toString(i);
}
/* Put the elements inside */
final JComboBox date = new JComboBox();
for (int i=1; i<=31; i++) {
date.addItem(dates[i]);
}
date.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
selectedDate = date.getSelectedItem();
}
}
);
/* This is to generate elements for JComboBox */
String[] months = new String[13];
for (int i=1; i<=12; i++) {
months[i] = Integer.toString(i);
}
/* Put the elements inside */
final JComboBox month = new JComboBox();
for (int i=1; i<=12; i++) {
month.addItem(dates[i]);
}
month.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
selectedMonth = month.getSelectedItem();
}
}
);
/* The zone for the birthday */
JPanel infoBirth = new JPanel();
infoBirth.add(date);
infoBirth.add(month);
infoBirth.add(birthday);
inputs.add(infoBirth);
JLabel infoEmail = new JLabel();
infoEmail.setText("Email Address: ");
email.setPreferredSize(new Dimension(250,40));
inputs.add(infoEmail);
inputs.add(email);
JLabel infoAddress = new JLabel();
infoAddress.setText("Address: ");
address.setPreferredSize(new Dimension(300,40));
inputs.add(infoAddress);
inputs.add(address);
/* When the input has been finished, save it! */
JButton done = new JButton();
done.setText("Done");
done.setPreferredSize(new Dimension(30, 40));
done.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
/* Get all the input information */
String fName = firstName.getText();
String lName = lastName.getText();
String numberString = number.getText();
String tBirthday = birthday.getText();
String tEmail = email.getText();
String tAddress = address.getText();
String tImage = imageName;
/* Avoid the empty input */
if (fName.equals("")) {
fName = "#";
}
if (lName.equals("")) {
lName = "#";
}
if (numberString.equals("")) {
numberString = "#";
}
if (tImage == null) {
tImage = "#";
}
if (selectedDate == null) {
selectedDate = "1";
}
if (selectedMonth == null) {
selectedMonth = "1";
}
openFile();
addToList(fName, lName, numberString, (String) selectedDate, (String) selectedMonth, tBirthday, tEmail, tAddress, tImage);
saveFile();
try {
ContactsBook newOpen = new ContactsBook();
} catch (URISyntaxException | IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
java.net.URL completeURL = this.getClass().getResource(
"/comp2100/ass1/Transfer_Complete.wav");
APPLibrary.playSound(completeURL);
dispose();
}
});
JButton saveJson = new JButton("Save as Json");
saveJson.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Eric");
//Refer to Eric McCreath, u4033585
File f = new File(APPLibrary.WHERE_CONTACTS_JSON_FILE);
JSONObject obj = new JSONObject();
/* Get all the input information */
String fName = firstName.getText();
String lName = lastName.getText();
String numberString = number.getText();
String tBirthday = birthday.getText();
String tEmail = email.getText();
String tAddress = address.getText();
String tImage = imageName;
/* Avoid the empty input */
if (fName.equals("")) {
fName = "#";
}
if (lName.equals("")) {
lName = "#";
}
if (numberString.equals("")) {
numberString = "#";
}
if (tImage == null) {
tImage = "#";
}
if (selectedDate == null) {
selectedDate = "1";
}
if (selectedMonth == null) {
selectedMonth = "1";
}
addToList(fName, lName, numberString, (String) selectedDate, (String) selectedMonth, tBirthday, tEmail, tAddress, tImage);
for (Person element : persons) {
obj.put("FirstName", element.getFirstName());
obj.put("LastName", element.getLastName());
obj.put("Number", element.getNumber());
obj.put("Date", element.getDate());
obj.put("Month", element.getMonth());
obj.put("Year", element.getYear());
obj.put("Email", element.getEmail());
obj.put("Address", element.getAddress());
obj.put("Image", element.getImage());
}
FileWriter out;
try {
out = new FileWriter(f);
obj.writeJSONString(out);
out.close();
} catch (IOException e1) {
e1.printStackTrace();
}
imageName = null;
}
});
JButton close = new JButton("Cancel");
close.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
ContactsBook newOpen = new ContactsBook();
} catch (URISyntaxException | IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
dispose();
}
});
/* The Buttons at the buttom */
JPanel buttons = new JPanel(new GridLayout(0, 4));
buttons.add(done);
buttons.add(saveJson);
buttons.add(addImage);
buttons.add(close);
JPanel below = new JPanel(new BorderLayout());
below.add(inputs, BorderLayout.CENTER);
below.add(buttons, BorderLayout.PAGE_END);
container.add(headings, BorderLayout.PAGE_START);
container.add(below, BorderLayout.CENTER);
/* When close the window, the application terminates */
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public void openFile() {
/* Open the original file first */
try {
FileInputStream fileIn = new FileInputStream(APPLibrary.WHERE_CONTACTS_FILE);
ObjectInputStream in = new ObjectInputStream(fileIn);
persons = (ArrayList<Person>) in.readObject();
in.close();
fileIn.close();
} catch(Exception exc) {
System.out.println("A new file will be generated");
}
}
public void saveFile() {
/* Write to the file */
try{
FileOutputStream fout = new FileOutputStream(APPLibrary.WHERE_CONTACTS_FILE);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(persons);
oos.close();
System.out.println("Done");
} catch(Exception ex) {
ex.printStackTrace();
}
}
public void addToList(String fName, String lName, String numberString, String selectedDate, String selectedMonth, String tBirthday, String tEmail, String tAddress, String tImage) {
/* New object to add */
Person toAdd = new Person(fName, lName, numberString, (String) selectedDate, (String) selectedMonth, tBirthday, tEmail, tAddress, tImage);
persons.add(toAdd);
}
public static void main(String[] args) {
AddContacts launch = new AddContacts();
launch.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
} | kfzyqin/The-Personal-Organiser | AddContacts.java | 3,325 | /* Put the words into one panel */ | block_comment | en | true |
229883_1 | import contactBook.Contact;
import contactBook.ContactBook;
import java.util.Scanner;
public class Main {
//Constantes que definem os comandos
public static final String ADD_CONTACT = "AC";
public static final String REMOVE_CONTACT = "RC";
public static final String GET_PHONE = "GP";
public static final String GET_EMAIL = "GE";
public static final String SET_PHONE = "SP";
public static final String SET_EMAIL = "SE";
public static final String LIST_CONTACTS = "LC";
public static final String SEARCH_PHONE = "GN";
public static final String QUIT = "Q";
public static final String EQUAL_PHONE_NR = "EP";
//Constantes que definem as mensagens para o utilizador
public static final String CONTACT_EXISTS = "contactBook.Contact already exists.";
public static final String NAME_NOT_EXIST = "contactBook.Contact does not exist.";
public static final String CONTACT_ADDED = "contactBook.Contact added.";
public static final String CONTACT_REMOVED = "contactBook.Contact removed.";
public static final String CONTACT_UPDATED = "contactBook.Contact updated.";
public static final String BOOK_EMPTY = "contactBook.Contact book empty.";
public static final String CONTACT_NOT_EXISTS = "Phone number does not exist.";
public static final String QUIT_MSG = "Goodbye!";
public static final String COMMAND_ERROR = "Unknown command.";
public static final String HAS_EQUAL_NUMBER = "There are contacts that share phone numbers.";
public static final String NO_EQUAL_NUMBER = "All contacts have different phone numbers.";
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ContactBook cBook = new ContactBook();
String comm = getCommand(in);
while (!comm.equals(QUIT)){
switch (comm) {
case ADD_CONTACT:
addContact(in,cBook);
break;
case REMOVE_CONTACT:
deleteContact(in,cBook);
break;
case GET_PHONE:
getPhone(in,cBook);
break;
case GET_EMAIL:
getEmail(in,cBook);
break;
case SET_PHONE:
setPhone(in,cBook);
break;
case SET_EMAIL:
setEmail(in,cBook);
break;
case LIST_CONTACTS:
listAllContacts(cBook);
break;
case SEARCH_PHONE:
searchPhoneUser(in, cBook);
break;
case EQUAL_PHONE_NR:
hasEqualPhoneNr(cBook);
break;
default:
System.out.println(COMMAND_ERROR);
}
System.out.println();
comm = getCommand(in);
}
System.out.println(QUIT_MSG);
System.out.println();
in.close();
}
private static String getCommand(Scanner in) {
String input;
input = in.nextLine().toUpperCase();
return input;
}
private static void addContact(Scanner in, ContactBook cBook) {
String name, email;
int phone;
name = in.nextLine();
phone = in.nextInt(); in.nextLine();
email = in.nextLine();
if (!cBook.hasContact(name)) {
cBook.addContact(name, phone, email);
System.out.println(CONTACT_ADDED);
}
else System.out.println(CONTACT_EXISTS);
}
private static void deleteContact(Scanner in, ContactBook cBook) {
String name;
name = in.nextLine();
if (cBook.hasContact(name)) {
cBook.deleteContact(name);
System.out.println(CONTACT_REMOVED);
}
else System.out.println(NAME_NOT_EXIST);
}
private static void getPhone(Scanner in, ContactBook cBook) {
String name;
name = in.nextLine();
if (cBook.hasContact(name)) {
System.out.println(cBook.getPhone(name));
}
else System.out.println(NAME_NOT_EXIST);
}
private static void getEmail(Scanner in, ContactBook cBook) {
String name;
name = in.nextLine();
if (cBook.hasContact(name)) {
System.out.println(cBook.getEmail(name));
}
else System.out.println(NAME_NOT_EXIST);
}
private static void setPhone(Scanner in, ContactBook cBook) {
String name;
int phone;
name = in.nextLine();
phone = in.nextInt(); in.nextLine();
if (cBook.hasContact(name)) {
cBook.setPhone(name,phone);
System.out.println(CONTACT_UPDATED);
}
else System.out.println(NAME_NOT_EXIST);
}
private static void setEmail(Scanner in, ContactBook cBook) {
String name;
String email;
name = in.nextLine();
email = in.nextLine();
if (cBook.hasContact(name)) {
cBook.setEmail(name,email);
System.out.println(CONTACT_UPDATED);
}
else System.out.println(NAME_NOT_EXIST);
}
private static void listAllContacts(ContactBook cBook) {
if (cBook.getNumberOfContacts() != 0) {
cBook.initializeIterator();
while( cBook.hasNext() ) {
Contact c = cBook.next();
System.out.println(c.getName() + "; " + c.getEmail() + "; " + c.getPhone());
}
}
else System.out.println(BOOK_EMPTY);
}
private static void hasEqualPhoneNr(ContactBook cBook) {
if (cBook.hasEqualNr() && cBook.getNumberOfContacts() != 0 ) {
System.out.println(HAS_EQUAL_NUMBER);
} else {
System.out.println(NO_EQUAL_NUMBER);
}
}
private static void searchPhoneUser(Scanner in, ContactBook cBook) {
int phone;
phone = in.nextInt(); in.nextLine();
if (cBook.hasContactNumber(phone)) {
System.out.println(cBook.getNameByNumber(phone));
} else System.out.println(CONTACT_NOT_EXISTS);
}
}
| TiagoGuerra001/ContactBookGit | src/Main.java | 1,448 | //Constantes que definem as mensagens para o utilizador | line_comment | en | true |
230263_28 | import java.util.ArrayList;
/**
* Creates a puzzle with a board and a list of puzzle pieces, that can check if
* a given piece fits in a given spot, and solve the puzzle using the given
* pieces. Written: 04/10/15
*
* @author Kaitlyn Li
* @author Kevin Ma
*/
public class Puzzle {
/*
* to define the private variables rows = the number of rows in the board
* cols = the number of columns in the board board = two dimensional array
* to store the solved puzzle pieces unused = the list of available pieces
* not put on the board yet
*/
private Board board;
private int rows;
private int cols;
private ArrayList<Piece> unused;
/**
* Constructs an empty puzzle with a given number of rows and columns
*
* @param rows
* = the number of rows
* @param cols
* = the number of columns
*/
public Puzzle(int rows, int cols) {
board = new Board(rows, cols);
this.rows = rows;
this.cols = cols;
unused = new ArrayList<Piece>();
}
/**
* Constructs a puzzle with a given number of rows and columns and a given
* set of pieces
*
* @param rows
* = the number of rows
* @param cols
* = the number of columns
* @param pieces
* = the array of available/unused pieces
*/
public Puzzle(int rows, int cols, Piece[] pieces) {
board = new Board(rows, cols);
this.rows = rows;
this.cols = cols;
unused = new ArrayList<Piece>();
for (int i = 0; i < pieces.length; i++) {
unused.add(pieces[i]);
}
}
/**
* Constructs a puzzle with a given number of rows and columns and a given
* set of pieces
*
* @param rows
* = the number of rows
* @param cols
* = the number of columns
* @param pieces
* = the ArrayList of available/unused pieces
*/
public Puzzle(int rows, int cols, ArrayList<Piece> pieces) {
board = new Board(rows, cols);
this.rows = rows;
this.cols = cols;
unused = new ArrayList<Piece>();
unused.addAll(pieces);
}
/**
* Constructs a puzzle with a given Board object
*
* @param board
* = the board holding puzzle piece
*/
public Puzzle(Board board) {
this.rows = board.getRows();
this.cols = board.getCols();
this.board = new Board(rows, cols);
unused = new ArrayList<Piece>();
}
/**
* @return the board
*/
public Board getBoard() {
return board;
}
/**
* @return the rows of the puzzle
*/
public int getRows() {
return rows;
}
/**
* @return the cols of the puzzle
*/
public int getCols() {
return cols;
}
/**
*
* @return An ArrayList of all the pieces in this puzzle that are not on the
* board.
*/
public ArrayList<Piece> getUnusedPieces() {
ArrayList<Piece> unusedCopy = new ArrayList<Piece>();
unusedCopy.addAll(unused);
return unusedCopy;
}
/**
* Checks if the side of one piece matches with the opposite side of another
* piece.
*
* @param piece1
* = first piece being compared
* @param piece2
* = second piece being compared
* @param directionFrom1to2
* = the side of first
* @return true if matched, or false if not
*/
public boolean matchEdge(Piece piece1, Piece piece2, int directionFrom1to2) {
if (piece1.getEdge(directionFrom1to2)
+ piece2.getEdge((directionFrom1to2 + 2) % 4) == 0)
return true;
return false;
}
/**
* Checks if the row and column of the board is fit for the specified piece
* at the specified side
*
* @param row
* = the row to fit in
* @param col
* = the col to fit in
* @param direction
* = the side being checked
* @param piece
* = the piece being checked
* @return true if fit, or false if not
*/
private boolean sideFit(int row, int col, int direction, Piece piece) {
if (direction == Piece.NORTH)
row--;
if (direction == Piece.EAST)
col++;
if (direction == Piece.SOUTH)
row++;
if (direction == Piece.WEST)
col--;
if (board.isValid(row, col)) {
if (board.hasPiece(row, col)) {
if (!matchEdge(piece, getPiece(row, col), direction))
return false;
}
}
return true;
}
/*
* to check if each side of the piece fits in the specified tile of the
* board; parameters: row = the row which the piece to be in , col = the
* column which the piece to be in, piece = the piece to fit in returns true
* if fit, or false if not
*/
public boolean doesFit(int row, int col, Piece piece) {
for (int i = 0; i < 4; i++) {
if (!sideFit(row, col, i, piece))
return false;
}
return true;
}
/*
* to check if puzzle is solved, that is, each tile has a piece and is
* fitted; return true if solved, or false if not
*/
public boolean isSolved() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (getPiece(i, j) == null)
return false;
if (!doesFit(i, j, getPiece(i, j)))
return false;
}
}
return true;
}
/*
* to set piece into the specified tile of the board and remove the piece
* from unused list; parameters: row = the row which the piece will be in,
* col = the column which the piece will be in, piece = the piece to set,
* return the original piece at the tile of the board
*/
public Piece setPiece(int row, int col, Piece piece) {
if (!doesFit(row, col, piece))
return null;
else {
Piece a = board.getPiece(row, col);
unused.remove(piece);
board.setPiece(row, col, piece);
return a;
}
}
/*
* to get piece at the specified tile of the board; parameters: row = the
* row which the piece is in , col = the column which the piece is in,
* return the piece at the tile of the board
*/
public Piece getPiece(int row, int col) {
return board.getPiece(row, col);
}
/*
* to remove a piece from the specified tile of the board and add the piece
* to unused list; parameters: row = the row which the piece is in , col =
* the column which the piece is in, return the piece removed
*/
public Piece removePiece(int row, int col) {
if (!board.isValid(row, col) || !board.hasPiece(row, col))
return null;
Piece a = board.getPiece(row, col);
unused.add(board.removePiece(row, col));
return a;
}
/*
* to add the piece to unused list; parameters: piece = the piece to add
*/
public void addPiece(Piece piece) {
unused.add(piece);
}
/*
* to remove all pieces on the board to unused list and clear the board
*/
public void restart() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (board.hasPiece(i, j))
unused.add(board.removePiece(i, j));
}
}
}
/*
* a toString method to convert the puzzle board into printable string
* format; return a string value
*/
public String toString() {
return board.toString();
}
/*
* to solve the puzzle
*/
public void solve() {
restart();
ArrayList<Piece> unusedPieces = getUnusedPieces();
permuteToSolve(unusedPieces, unusedPieces.size());
}
/*
* Find a permutation of unused pieces (by Heap's algorithm), if the
* permutation is a solution, done;Otherwise, reset board and try next
* permutation until all permutations exhausted; parameters: pieces = the
* unused pieces, size = the number of unused pieces
*/
private void permuteToSolve(ArrayList<Piece> pieces, int size) {
if (isSolved())
return;
if (size == 1) {
restart();
ArrayList<Piece> newlyPermuted = new ArrayList<Piece>();
newlyPermuted.addAll(pieces);
solve(0, 0, newlyPermuted);
} else {
for (int i = 0; i < size; i++) {
permuteToSolve(pieces, size - 1);
if (size % 2 == 1)
swap(pieces, 0, size - 1);
else
swap(pieces, i, size - 1);
}
}
}
/*
* Swap two pieces in the array list
*/
private void swap(ArrayList<Piece> pieces, int i, int j) {
Piece tmp = pieces.get(i);
pieces.set(i, pieces.get(j));
pieces.set(j, tmp);
}
/*
* Recursively solve row, col in the board to set fitted piece until no
* fitted piece found or all pieces fitted; parameters: row = the row which
* the piece to be in, col = the column which the piece to be in, pieces =
* current unused pieces
*/
private void solve(int row, int col, ArrayList<Piece> pieces) {
if (pieces.size() == 0 || row >= rows)
return;
// Find a fitted piece to row, col from remaining pieces
Piece fitPiece = null;
for (Piece p : pieces) {
for (int direction = 0; direction < 4; direction++) {
if (doesFit(row, col, p)) {
fitPiece = p;
break;
} else
p.rotate();
}
if (fitPiece != null)
break;
}
// set piece if found fit piece, solve next col or row
if (fitPiece != null) {
setPiece(row, col, fitPiece);
if (col == cols - 1) {
row++;
col = 0;
} else
col++;
pieces.remove(fitPiece);
solve(row, col, pieces);
}
}
// main method
public static void main(String[] args) {
// Test my puzzle pieces
System.out
.println("-------------------Test my pieces---------------------");
Piece[] myPieces = new Piece[3 * 3];
myPieces[0] = new Piece(Piece.HEARTS_IN, Piece.CLUBS_IN,
Piece.HEARTS_OUT, Piece.DIAMONDS_OUT);
myPieces[1] = new Piece(Piece.HEARTS_IN, Piece.HEARTS_IN,
Piece.SPADES_IN, Piece.CLUBS_OUT);
myPieces[2] = new Piece(Piece.SPADES_OUT, Piece.CLUBS_OUT,
Piece.DIAMONDS_IN, Piece.HEARTS_IN);
myPieces[3] = new Piece(Piece.HEARTS_IN, Piece.DIAMONDS_IN,
Piece.SPADES_IN, Piece.HEARTS_IN);
myPieces[4] = new Piece(Piece.HEARTS_IN, Piece.DIAMONDS_IN,
Piece.HEARTS_IN, Piece.CLUBS_IN);
myPieces[5] = new Piece(Piece.SPADES_OUT, Piece.HEARTS_IN,
Piece.HEARTS_IN, Piece.DIAMONDS_OUT);
myPieces[6] = new Piece(Piece.DIAMONDS_OUT, Piece.SPADES_IN,
Piece.HEARTS_IN, Piece.HEARTS_IN);
myPieces[7] = new Piece(Piece.HEARTS_OUT, Piece.CLUBS_OUT,
Piece.HEARTS_IN, Piece.SPADES_OUT);
myPieces[8] = new Piece(Piece.HEARTS_OUT, Piece.HEARTS_IN,
Piece.HEARTS_IN, Piece.CLUBS_IN);
Puzzle myPuzzle = new Puzzle(3, 3, myPieces);
myPuzzle.setPiece(1, 1, myPieces[5]);
myPuzzle.setPiece(2, 1, myPieces[8]);
if (myPuzzle.isSolved())
System.out.println("My puzzle is already solved");
else
System.out.println("My puzzle is unsolved yet");
System.out.println(myPuzzle.toString());
myPuzzle.solve();
System.out.println(myPuzzle.toString());
// Modify my Puzzle pieces so it has no solution
// System.out.println("----Test a puzzle which has no solution----");
// myPieces[4] = new Piece(Piece.HEARTS_IN, Piece.HEARTS_IN,
// Piece.HEARTS_IN, Piece.HEARTS_IN);
// Puzzle myPuzzleB = new Puzzle(3, 3, myPieces);
// myPuzzleB.solve();
// System.out.println(myPuzzleB.toString());
// Test Mr. Marshall's pieces
System.out
.println("----------------Test Mr. Marshall's pieces--------------");
Piece[] pieces = new Piece[3 * 3];
pieces[0] = new Piece(Piece.CLUBS_OUT, Piece.HEARTS_OUT,
Piece.DIAMONDS_IN, Piece.CLUBS_IN);
pieces[1] = new Piece(Piece.SPADES_OUT, Piece.DIAMONDS_OUT,
Piece.SPADES_IN, Piece.HEARTS_IN);
pieces[2] = new Piece(Piece.HEARTS_OUT, Piece.SPADES_OUT,
Piece.SPADES_IN, Piece.CLUBS_IN);
pieces[3] = new Piece(Piece.HEARTS_OUT, Piece.DIAMONDS_OUT,
Piece.CLUBS_IN, Piece.CLUBS_IN);
pieces[4] = new Piece(Piece.SPADES_OUT, Piece.SPADES_OUT,
Piece.HEARTS_IN, Piece.CLUBS_IN);
pieces[5] = new Piece(Piece.HEARTS_OUT, Piece.DIAMONDS_OUT,
Piece.DIAMONDS_IN, Piece.HEARTS_IN);
pieces[6] = new Piece(Piece.SPADES_OUT, Piece.DIAMONDS_OUT,
Piece.HEARTS_IN, Piece.DIAMONDS_IN);
pieces[7] = new Piece(Piece.CLUBS_OUT, Piece.HEARTS_OUT,
Piece.SPADES_IN, Piece.HEARTS_IN);
pieces[8] = new Piece(Piece.CLUBS_OUT, Piece.CLUBS_IN,
Piece.DIAMONDS_IN, Piece.DIAMONDS_OUT);
Puzzle tPuzzle = new Puzzle(3, 3, pieces);
tPuzzle.solve();
System.out.println(tPuzzle.toString());
}
}
| KZcheese/Puzzle-Project | src/Puzzle.java | 3,927 | // Modify my Puzzle pieces so it has no solution | line_comment | en | false |
230305_5 | import java.util.Scanner;
public class JavaLab6 {
public static void main(String[] args) {
// 1.)
Scanner scanner = new Scanner(System.in);
System.out.println("1.) Enter a number: ");
int num = scanner.nextInt();
System.out.println("Enter another number: ");
int num2 = scanner.nextInt();
System.out.println(multiple(num,num2));
// 2.)
int number1;
int number2;
Scanner scanner2 = new Scanner(System.in);
System.out.println("2.) Enter a number: ");
number1 = scanner2.nextInt();
System.out.println("Enter another number: ");
number2 = scanner2.nextInt();
lcd(number1, number2);
// 3.)
int num1;
Scanner scanner3 = new Scanner(System.in);
System.out.println("3.) Enter a number: ");
num1 = scanner3.nextInt();
System.out.println(palindrome(num1));
// 4.)
char print = 'x';
matrix(print);
}
// 1. Write a method multiple that determines, for a pair of integers, whether the second integer is a multiple of the first.
// The method should take two integer arguments, return true if the second is a multiple of the first, and return false otherwise.
public static boolean multiple(int num, int num2){
if(num % num2 == 0){
return true;
} else {
return false;
}
}
// 2. Write a method LCD that returns the least common divisor of two integers (the number that evenly divides both).
// This method should take two integer arguments, and return the LCD of those numbers.
public static void lcd(int number1, int number2) {
int lcd = Math.max(number1, number2);
while (true) {
if (lcd % number1 == 0 && lcd % number2 == 0) {
System.out.println(lcd);
break;
}
++lcd;
}
}
// 3. A non-negative integer is called a palindrome if it reads forward and backward in the same way. For example, the numbers 5, 121, 3443, and 123454321 are palindromes.
// Write a method that takes as input a nonnegative integer and returns true if the number is a palindrome; otherwise, it returns false.
public static boolean palindrome(int num1){
int oNum = num1;
int revNum = 0;
while (num1 != 0){
revNum = revNum * 10 + num1 % 10;
num1 = num1 / 10;
}
if (oNum == revNum){
return true;
}else{
return false;
}
}
// 4. Write a method that draws a matrix of 3 by 4 (3 rows of 4 columns) with x as the element. Hint: Use two for loops
public static void matrix(char print)
{
int r = 3;
int c = 4;
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
System.out.print( print + "\t");
}
System.out.println();
}
}
}
| RachelCVerastique/COSC1337 | JavaLab6.java | 796 | // The method should take two integer arguments, return true if the second is a multiple of the first, and return false otherwise. | line_comment | en | true |
230311_8 | /**
* Escreve no LCD usando a interface de 8 bits
*/
public class Lcd {
public static final int LINES = 2, COLS = 16; //Dimensão do display
/**
* Envia a sequência de inicio do LCD
* Inicia na memória gráfica as configurações dos caracteres especiais
*/
public static void init(){
writeCMD(0b00110000);
Kit.sleep(5);
writeCMD(0b00110000);
writeCMD(0b00110000);
writeCMD(0b00111000);
writeCMD(0b00001000);
writeCMD(0b00000001);
writeCMD(0b00000110);
/*Escrita das configurações para caracteres especiais na GRAM do lcd
writeCMD(0b01000000); //€, on 0x00 address
writeDATA(0b00000110);
writeDATA(0b00001001);
writeDATA(0b00011100);
writeDATA(0b00001000);
writeDATA(0b00011100);
writeDATA(0b00001001);
writeDATA(0b00000110);
writeCMD(0b01000001); //ã, on 0x01 address
writeDATA(0b00001101);
writeDATA(0b00010010);
writeDATA(0b00001110);
writeDATA(0b00000001);
writeDATA(0b00001111);
writeDATA(0b00010001);
writeDATA(0b00001111);
writeCMD(0b01000010); //ç, on 0x02 address
writeDATA(0b00000000);
writeDATA(0b00001110);
writeDATA(0b00010000);
writeDATA(0b00010000);
writeDATA(0b00001110);
writeDATA(0b00000100);
writeDATA(0b00001100);
writeDATA(0b00000000);
writeCMD(0b01000011); //â, on 0x03 address
writeDATA(0b00000100);
writeDATA(0b00001010);
writeDATA(0b00001110);
writeDATA(0b00000001);
writeDATA(0b00001111);
writeDATA(0b00010001);
writeDATA(0b00001111);
writeDATA(0b00000000);
writeCMD(0b01000100); //é, on 0x04 address
writeDATA(0b00000001);
writeDATA(0b00000010);
writeDATA(0b00000100);
writeDATA(0b00001110);
writeDATA(0b00010001);
writeDATA(0b00011111);
writeDATA(0b00010000);
writeDATA(0b00001110);
writeDATA(0b00000000);
*/
writeCMD(0b00001111);
}
/**
* Escreve um caracter na posição actual do cursor
* @param c Caracter a escrever
*/
public static void write(char c){
/*switch (c){
case '€':
writeDATA(0);
break;
case 'ã':
writeDATA(1);
break;
case 'ç':
writeDATA(2);
break;
case 'â':
writeDATA(3);
break;
case 'é':
writeDATA(4);
break;
default: writeDATA(c);
}*/
writeDATA(c);
}
/**
* Escreve uma string na posição actual do cursor
*/
public static void write(String txt){
for (int i = 0; i < txt.length(); i++) {
write(txt.charAt(i));
}
}
/**
* Escreve um comando/dados no LCD
* @param rs bit de controlo true:dados false:comando
* @param data informação de dados/comando
*/
private static void writeByte(boolean rs, int data){
data <<= 1;
if(rs)
data |= 1;
SerialEmitter.send(true, data);
}
/**
* Envia um comando para o LCD
* @param data codigo do comando
*/
private static void writeCMD(int data){
writeByte(false, data);
}
/**
* Envia dados de escrita no LCD
* @param data codigo do caracter ASCII
*/
private static void writeDATA(int data){
writeByte(true, data);
}
/**
* Retorna o cursor ao endereço 0
*/
public static void returnHome(){
writeCMD(0b00000010);
}
/**
* Define o endereço do cursor com a posição desejada
* @param line
* @param col
*/
public static void setCursor(int line, int col){
if (line == 2)
col += 64;
writeCMD(128 | (col));
}
}
| paulopiriquito/TMachine | src/Lcd.java | 1,420 | /**
* Envia um comando para o LCD
* @param data codigo do comando
*/ | block_comment | en | true |
Subsets and Splits