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 |
---|---|---|---|---|---|---|---|---|
91201_0 | import java.awt.Point;
public class King extends Piece{
/**
* Constructor
*
*@param p - initial starting position of king
*
**/
public King(Point p, boolean isWhite){
super(p, isWhite);
}
/**
* makeMove
* makes sure move is legal and moves king
*
* @param p - point you want to move king to
*/
public void makeMove(Point p){
int x = (int)(p.getX());
int y = (int)(p.getY());
if(Math.abs(x-getX()) <= 1 && Math.abs(y-getY()) <= 1){
move(p);
}else{
return;
}
}
} | The-Pheonix21/Chess-1 | King.java | 191 | /**
* Constructor
*
*@param p - initial starting position of king
*
**/ | block_comment | en | false |
91403_1 | /*
* 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 br.gov.serpro.certificate.ui.user;
import java.io.File;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.UnrecoverableKeyException;
import javax.swing.JOptionPane;
import br.gov.frameworkdemoiselle.certificate.signer.factory.PKCS7Factory;
import br.gov.frameworkdemoiselle.certificate.signer.pkcs7.PKCS7Signer;
import br.gov.frameworkdemoiselle.certificate.signer.pkcs7.bc.policies.ADRBCMS_2_1;
import br.gov.frameworkdemoiselle.certificate.ui.action.AbstractFrameExecute;
import br.gov.frameworkdemoiselle.certificate.ui.util.ConectionException;
import br.gov.frameworkdemoiselle.certificate.ui.util.Utils;
import br.gov.frameworkdemoiselle.certificate.ui.view.Principal;
/**
*
* @author 07721825741
*/
public class App extends AbstractFrameExecute {
String jnlpIdentifier = "";
String jnlpService = "";
/**
* Carrega as variaveis do arquivo jnlp
*/
public App() {
jnlpIdentifier = System.getProperty("jnlp.identifier");
jnlpService = System.getProperty("jnlp.service");
System.out.println("jnlp.identifier..: " + jnlpIdentifier);
System.out.println("jnlp.service.....: " + jnlpService);
}
@Override
public void execute(KeyStore ks, String alias, Principal principal) {
try {
if (jnlpIdentifier == null || jnlpIdentifier.isEmpty()) {
JOptionPane.showMessageDialog(principal, "A variavel \"jnlp.identifier\" não está configurada.", "Erro", JOptionPane.ERROR_MESSAGE);
return;
}
if (jnlpService == null || jnlpService.isEmpty()) {
JOptionPane.showMessageDialog(principal, "A variavel \"jnlp.service\" não está configurada.", "Erro", JOptionPane.ERROR_MESSAGE);
return;
}
/* Parametrizando o objeto doSign */
PKCS7Signer signer = PKCS7Factory.getInstance().factoryDefault();
signer.setCertificates(ks.getCertificateChain(alias));
signer.setPrivateKey((PrivateKey) ks.getKey(alias, null));
signer.setSignaturePolicy(new ADRBCMS_2_1());
signer.setAttached(true);
/* Realiza a assinatura do conteudo */
System.out.println("Efetuando a assinatura do conteudo");
Utils utils = new Utils();
//Faz o download do conteudo a ser assinado
String conexao = jnlpService.concat("/download/").concat(jnlpIdentifier);
System.out.println("Conectando em....: " + conexao);
byte[] content = utils.downloadFromUrl(conexao);
byte[] signed = signer.signer(content);
// Grava o conteudo assinado no disco para verificar o resultado
utils.writeContentToDisk(signed, System.getProperty("user.home").concat(File.separator).concat("resultado.p7s"));
//Faz o upload do conteudo assinado
// utils.uploadToURL(signed, jnlpService.concat("/upload/").concat(jnlpIdentifier));
utils.uploadToURL(signed, jnlpService.concat("/upload/"));
JOptionPane.showMessageDialog(principal, "O arquivo foi assinado com sucesso.", "Mensagem", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
} catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | ConectionException ex) {
JOptionPane.showMessageDialog(principal, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
}
@Override
public void cancel(KeyStore ks, String alias, Principal principal) {
/* Seu codigo customizado aqui... */
System.out.println("br.gov.serpro.certificate.ui.user.App.cancel()");
principal.setVisible(false); //you can't see me!
principal.dispose(); //Destroy the JFrame object
}
}
| demoiselle/certificate | impl/desktop/user/App.java | 1,015 | /**
*
* @author 07721825741
*/ | block_comment | en | true |
91701_2 | package com.wzx.beauty;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class Beauty0305 {
public static void main(String[] args) {
String[] article = {"the", "but", "but", "public", "could", "add", "and", "but", "and", "subtract", "but", "to", "divide"};
String[] words = {"and", "but"};
System.out.println(Arrays.toString(shortestAbstract(article, words)));
}
public static int[] shortestAbstract(String[] article, String[] words) {
int begin = 0;
int end = 0;
int distance = 0x7fffffff;
int shortBegin = 0;
int shortEnd = 0;
Map<String, Integer> wordsTable = new HashMap<>();
int totalCountWords = 0;
for (String word : words
) {
totalCountWords++;
Integer times;
wordsTable.put(word, (times = wordsTable.get(word)) == null ? 1 : times + 1);
}
while (begin < article.length && end < article.length) {
while (totalCountWords > 0 && end < article.length) {
if (wordsTable.containsKey(article[end])) {
if (wordsTable.get(article[end]) > 0) {
totalCountWords--;
}
// save result of word times in article subtract times in words
// if result less equal than 0, means the sequence contains all words
wordsTable.put(article[end], wordsTable.get(article[end]) - 1);
}
end++;
}
while (totalCountWords == 0 && begin < end) {
if (end - begin < distance) {
distance = end - begin;
shortBegin = begin;
shortEnd = end;
}
if (wordsTable.containsKey(article[begin])) {
if (wordsTable.get(article[begin]) == 0) {
totalCountWords++;
}
// save result of word times in article subtract times in words
// if result less equal than 0, means the sequence contains all words
wordsTable.put(article[begin], wordsTable.get(article[begin]) + 1);
}
begin++;
}
}
return new int[]{shortBegin, shortEnd - 1};
}
}
| wangz1x/beauty_of_programming | chapter3/Beauty0305.java | 553 | // save result of word times in article subtract times in words | line_comment | en | true |
92245_1 | package scheduler;
import java.io.FileNotFoundException;
import java.util.HashMap;
import parser.VTParser;
import time.Time;
import time.TimeException;
/**
* ScheduleMaker generates a list of schedules
* can only be called in a static way
*
* @author Phillip Ngo
*/
public class ScheduleMaker {
private LinkedList<Schedule> schedules;
private HashMap<String, LinkedList<VTCourse>> listings;
private HashMap<String, LinkedList<VTCourse>> pass;
private HashMap<String, LinkedList<VTCourse>> fail;
private LinkedList<VTCourse> crnCourses;
/**
* Constructor creates all schedule combinations and compiles data
* @param term the term to parse
* @param subjects subjects of the classes. index corresponds to numbers, types, and profs
* @param numbers numbers of the classes. index corresponds to subjects, types, and profs
* @param types types of the classes. index corresponds to subjects, numbers, and profs
* @param start start time restriction
* @param end end time restriction
* @param freeDays free days restriction
* @param crns the crns to add
* @param profs the prof preferences of the classes. index corresponds to subjetcs, numbers, and types
* @throws Exception
*/
public ScheduleMaker(String term, LinkedList<String> subjects, LinkedList<String> numbers, LinkedList<String> types,
String start, String end, String[] freeDays, LinkedList<String> crns, LinkedList<String> profs) throws Exception {
listings = new HashMap<>();
pass = new HashMap<>();
fail = new HashMap<>();
crnCourses = new LinkedList<>();
schedules = generateSchedule(term, subjects, numbers, types, start, end, freeDays, crns, profs);
}
/**
* List of possible schedules
* @return schedules
*/
public LinkedList<Schedule> getSchedules() {
return schedules;
}
/**
* Listings found for the classes inputted
* @return listings
*/
public HashMap<String, LinkedList<VTCourse>> getListings() {
return listings;
}
/**
* The listings of specific crns
* @return crnCourses
*/
public LinkedList<VTCourse> getCrns() {
return crnCourses;
}
/**
* The classes that failed the restrictions sorted by course numbers
* @return fail
*/
public HashMap<String, LinkedList<VTCourse>> getFailed() {
return fail;
}
/**
* The classes that passed the restrictions sorted by course numbers
* @return pass
*/
public HashMap<String, LinkedList<VTCourse>> getPassed() {
return pass;
}
/**
* Generates all possible schedules with the given parameter
*
* @param term the term value
* @param subjects array of subjects where the indices correspond to the indices of numbers
* @param numbers array of numbers where the indices correspond to the indices of subjects
* @param types array of class types where the indices correspond
* @param onlineAllowed array of booleans noting whether online for a class is allowed
* @param start the earliest time allowed
* @param end the latest time allowed
* @param freeDay freeDay if there is one
* @param crns any specific crns
* @return the LinkedList of all the schedules
* @throws Exception
*/
private LinkedList<Schedule> generateSchedule(String term, LinkedList<String> subjects, LinkedList<String> numbers, LinkedList<String> types,
String start, String end, String[] freeDays, LinkedList<String> crns, LinkedList<String> profs) throws Exception {
LinkedList<Schedule> schedules = new LinkedList<>();
LinkedList<LinkedList<VTCourse>> classes = new LinkedList<>();
HashMap<String, HashMap<String, LinkedList<VTCourse>>> map = null;
VTParser parser = null;
try {
//throw new FileNotFoundException(); //debugging
map = VTParser.parseTermFile(term);
}
catch (FileNotFoundException e) {
parser = new VTParser(term);
}
for (int i = 0; i < subjects.size(); i++) {
LinkedList<VTCourse> curr = null;
String type = types.get(i);
String subj = subjects.get(i);
String num = numbers.get(i);
try {
if (map != null) {
LinkedList<VTCourse> find = map.get(subj).get(num);
listings.put(type + subj + " " + num, find.createCopy());
curr = find.createCopy();
}
else {
LinkedList<VTCourse> find = parser.parseCourse(subj, num);
listings.put(type + subj + " " + num, find);
curr = find.createCopy();
}
}
catch (Exception e) {
throw new Exception(subj + " " + num + " does not exist on the timetable");
}
LinkedList<VTCourse> failed = new LinkedList<>();
for (VTCourse c : curr) {
if (!checkRestrictions(c, start, end, type, freeDays, profs.get(i))) {
curr.remove(c);
if (!c.getClassType().equals(type)) {
listings.get(type + subj + " " + num).remove(c);
}
else {
failed.add(c);
}
}
}
pass.put(types.get(i) + subjects.get(i) + " " + numbers.get(i), curr);
fail.put(types.get(i) + subjects.get(i) + " " + numbers.get(i), failed);
classes.add(curr);
}
if (crns.size() != 0) {
for (String crn : crns) {
LinkedList<VTCourse> curr = new LinkedList<>();
outerloop:
for (String subj : map.keySet()) {
HashMap<String, LinkedList<VTCourse>> subject = map.get(subj);
for (String numb : subject.keySet()) {
LinkedList<VTCourse> list = subject.get(numb);
for (VTCourse c : list) {
if (crn.equals(c.getCRN())) {
curr.add(c);
crnCourses.add(c);
for (VTCourse c2 : list) {
if (!c2.getClassType().equals(c.getClassType())) {
list.remove(c2);
}
}
listings.put(c.getClassType() + subj + " " + numb, list);
break outerloop;
}
}
}
}
classes.add(curr);
}
}
try {
createSchedules(classes, new Schedule(), 0, schedules);
} catch (Exception e) {}
return schedules;
}
/**
* Creates all valid schedules
*
* @param classListings A list holding a list for each class
* @param schedule the schedule to add to schedules
* @param classIndex current index in classListings
* @param schedules the list of possible schedules
* @throws Exception
*/
private void createSchedules(LinkedList<LinkedList<VTCourse>> classListings, Schedule schedule,
int classIndex, LinkedList<Schedule> schedules) throws Exception {
for (VTCourse course : classListings.get(classIndex)) {
Schedule copy = schedule;
if (classIndex == classListings.size() - 1) {
copy = schedule.createCopy();
}
try {
copy.add(course);
}
catch (TimeException e) {
continue;
}
if (classIndex == classListings.size() - 1) {
if (schedules.size() >= 201) {
throw new Exception("Too Many Schedules");
}
schedules.add(copy);
}
else {
createSchedules(classListings, copy, classIndex + 1, schedules);
schedule.remove(course);
}
}
}
/**
* Checks if a course meets the given restrictions
*
* @param course the class to check
* @param start the start time restriction
* @param end the end time restriction
* @param freeDay the free day restriction
* @return true if the course meets the restrictions
* @throws TimeException
*/
private boolean checkRestrictions(VTCourse course, String start, String end, String type, String[] freeDays,
String prof) throws TimeException {
Time time = course.getTimeSlot();
if (!type.equals("A") && !type.equals(course.getClassType())) {
return false;
}
if (!prof.equals("A") && !(prof).equals(course.getProf().replace("-", " "))) {
return false;
}
if (time == null) {
return true;
}
int startTime = Time.timeNumber(start);
int endTime = Time.timeNumber(end);
if (freeDays != null) {
for (String d : freeDays) {
for (String d2 : course.getDays()) {
if (d.equals(d2)) {
return false;
}
}
}
}
if (time.getStartNum() < startTime || time.getEndNum() > endTime) {
return false;
}
time = course.getAdditionalTime();
if (time == null) {
return true;
}
startTime = Time.timeNumber(start);
endTime = Time.timeNumber(end);
if (freeDays != null) {
for (String d : freeDays) {
for (String d2 : course.getAdditionalDays()) {
if (d.equals(d2)) {
return false;
}
}
}
}
if (time.getStartNum() < startTime || time.getEndNum() > endTime) {
return false;
}
return true;
}
}
| stephentuso/pScheduler | src/scheduler/ScheduleMaker.java | 2,252 | /**
* Constructor creates all schedule combinations and compiles data
* @param term the term to parse
* @param subjects subjects of the classes. index corresponds to numbers, types, and profs
* @param numbers numbers of the classes. index corresponds to subjects, types, and profs
* @param types types of the classes. index corresponds to subjects, numbers, and profs
* @param start start time restriction
* @param end end time restriction
* @param freeDays free days restriction
* @param crns the crns to add
* @param profs the prof preferences of the classes. index corresponds to subjetcs, numbers, and types
* @throws Exception
*/ | block_comment | en | false |
92278_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 entity;
import java.util.ArrayList;
/**
*
* @author juanc
*/
public class CinemApp {
/**
* @param args the command line arguments
*/
private Theater cinema;
private ArrayList<Movie> listings;
public CinemApp(Theater cinema) {
this.cinema = cinema;
}
public Theater getCinema() {
return cinema;
}
public void setCinema(Theater cinema) {
this.cinema = cinema;
}
}
| Edprietov/CinemaTickets | src/entity/CinemApp.java | 174 | /*
* 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 |
92468_1 | import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*****************************************************************
* The panel is used to create the layout of the game.
* @author William Minshew, Jeffrey Siebach, and Michael Howard
******************************************************************/
public class Panel extends JPanel
{
/******************************************************************
* Creates a panel with a Panel2() and a BattlePanel1()
******************************************************************/
public Panel()
{
Labels x = new Labels();
Scoreboard y = new Scoreboard();
BattlePanel1 bp = new BattlePanel1(x, y);
setLayout(new BorderLayout());
add(new Panel2(bp, x, y), BorderLayout.LINE_START);
add(bp, BorderLayout.CENTER);
}
}
| snickelfritz/chinpokomon | Panel.java | 173 | /******************************************************************
* Creates a panel with a Panel2() and a BattlePanel1()
******************************************************************/ | block_comment | en | false |
92856_0 | import units.HeroBase;
import java.util.Collections;
public class View {
private static int step = 1;
private static int l = 0;
private static final String top10 = formatDiv("a") + String.join("", Collections.nCopies(9, formatDiv("-b"))) + formatDiv("-c");
private static final String midl10 = formatDiv("d") + String.join("", Collections.nCopies(9, formatDiv("-e"))) + formatDiv("-f");
private static final String bottom10 = formatDiv("g") + String.join("", Collections.nCopies(9, formatDiv("-h"))) + formatDiv("-i");
private static void tabSetter(int cnt, int max){
int dif = max - cnt + 2;
if (dif>0) System.out.printf("%" + dif + "s", ":\t"); else System.out.print(":\t");
}
private static String formatDiv(String str) {
return str.replace('a', '\u250c')
.replace('b', '\u252c')
.replace('c', '\u2510')
.replace('d', '\u251c')
.replace('e', '\u253c')
.replace('f', '\u2524')
.replace('g', '\u2514')
.replace('h', '\u2534')
.replace('i', '\u2518')
.replace('-', '\u2500');
}
private static String getChar(int x, int y){
String out = "| ";
for (HeroBase human: Main.heroOrder) {
if (human.getPosition()[0] == x && human.getPosition()[1] == y){
if (human.getHp() == 0) {
out = "|" + (AnsiColors.ANSI_RED + human.getType().charAt(0) + AnsiColors.ANSI_RESET);
break;
}
if (Main.darkSide.contains(human)) out = "|" + (AnsiColors.ANSI_GREEN + human.getType().charAt(0) + AnsiColors.ANSI_RESET);
if (Main.lightSide.contains(human)) out = "|" + (AnsiColors.ANSI_BLUE + human.getType().charAt(0) + AnsiColors.ANSI_RESET);
break;
}
}
return out;
}
public static void view() {
if (step == 1 ){
System.out.print(AnsiColors.ANSI_RED + "First step" + AnsiColors.ANSI_RESET);
} else {
System.out.print(AnsiColors.ANSI_RED + "Step:" + step + AnsiColors.ANSI_RESET);
}
step++;
Main.heroOrder.forEach((v) -> l = Math.max(l, v.toString().length()));
System.out.print("_".repeat(l*2));
System.out.println();
System.out.print(top10 + " ");
System.out.print("Light side");
//for (int i = 0; i < l[0]-9; i++)
System.out.print(" ".repeat(l-10));
System.out.println(":\tDark side");
for (int i = 1; i < 11; i++) {
System.out.print(getChar(1, i));
}
System.out.print("| ");
System.out.print(Main.lightSide.get(0));
tabSetter(Main.lightSide.get(0).toString().length(), l);
System.out.println(Main.darkSide.get(0));
System.out.println(midl10);
for (int i = 2; i < 10; i++) {
for (int j = 1; j < 11; j++) {
System.out.print(getChar(i, j));
}
System.out.print("| ");
System.out.print(Main.lightSide.get(i-1));
tabSetter(Main.lightSide.get(i-1).toString().length(), l);
System.out.println(Main.darkSide.get(i-1));
System.out.println(midl10);
}
for (int j = 1; j < 11; j++) {
System.out.print(getChar(10, j));
}
System.out.print("| ");
System.out.print(Main.lightSide.get(9));
tabSetter(Main.lightSide.get(9).toString().length(), l);
System.out.println(Main.darkSide.get(9));
System.out.println(bottom10);
}
}
| AItemerbek/GB_Java_HeroTypeGame | View.java | 1,103 | //for (int i = 0; i < l[0]-9; i++) | line_comment | en | true |
93084_0 | package cop5556sp18.AST;
/**
* This code is for the class project in COP5556 Programming Language Principles
* at the University of Florida, Spring 2018.
*
* This software is solely for the educational benefit of students
* enrolled in the course during the Spring 2018 semester.
*
* This software, and any software derived from it, may not be shared with others or posted to public web sites,
* either during the course or afterwards.
*
* @Beverly A. Sanders, 2018
*/
import cop5556sp18.Scanner.Token;
import cop5556sp18.Types.Type;
public abstract class Expression extends ASTNode {
private Type t;
public Type getType(){
return t;
}
public void setType(Type t1){
t=t1;
}
public Expression(Token firstToken) {
super(firstToken);
}
} | prateek1192/COP5556-Project | AST/Expression.java | 249 | /**
* This code is for the class project in COP5556 Programming Language Principles
* at the University of Florida, Spring 2018.
*
* This software is solely for the educational benefit of students
* enrolled in the course during the Spring 2018 semester.
*
* This software, and any software derived from it, may not be shared with others or posted to public web sites,
* either during the course or afterwards.
*
* @Beverly A. Sanders, 2018
*/ | block_comment | en | true |
93319_5 | import java.io.RandomAccessFile;
import java.time.format.DateTimeFormatter;
public class Util {
/**
* Recebe (parâmetro) dois produtos e atributo a ser comparado. Compara ambos os produtos com base no atributo fornecido utilizando funções da classe Util.
* @param f
* @return Retorna um array de bytes que representa o float f.
*/
public static byte[] getByteArray(float f) {
int bits = Float.floatToIntBits(f);
byte[] bytes = new byte[] {
(byte) (bits >> 24),
(byte) (bits >> 16),
(byte) (bits >> 8),
(byte) bits,
};
return bytes;
}
/**
* Recebe (parâmetro) um array de bytes e retorna um float.
* @param bArr
* @return Retorna um float que representa o array de bytes bArr.
*/
public static byte[] getByteArray(String str) {
byte[] bArr = str.getBytes();
short len = (short) bArr.length;
byte[] res = new byte[bArr.length + 2];
res[0] = (byte) (len >> 8);
res[1] = (byte) len;
for (int i = 0; i < bArr.length; i++) {
res[i + 2] = bArr[i];
}
return res;
}
/**
* Recebe (parâmetro) um array de bytes e retorna um float.
* @param bArr
* @return Retorna um float que representa o array de bytes bArr.
*/
public static byte[] getLongByteArray(String str) {
byte[] bArr = str.getBytes();
int len = bArr.length;
byte[] res = new byte[bArr.length + 4];
res[0] = (byte) (len >> 24);
res[1] = (byte) (len >> 16);
res[2] = (byte) (len >> 8);
res[3] = (byte) len;
for (int i = 0; i < bArr.length; i++) {
res[i + 4] = bArr[i];
}
return res;
}
/**
* Recebe (parâmetro) um array de bytes e retorna um float.
* @param bArr
* @return Retorna um float que representa o array de bytes bArr.
*/
public static byte[] getByteArray(String str, int len) {
byte[] bArr = str.getBytes();
byte[] res = new byte[len];
for (int i = 0; i < bArr.length; i++) {
if (i >= len) break;
res[i] = bArr[i];
}
return res;
}
/**
* Recebe (parâmetro) um array de bytes e retorna um float.
* @param bArr
* @return Retorna um float que representa o array de bytes bArr.
*/
public static byte[] getByteArray(long l) {
byte[] res = new byte[8];
for (int i = 7; i >= 0; i--) {
res[i] = (byte) l;
l = l >> 8;
}
return res;
}
/**
* Recebe (parâmetro) um array de bytes e retorna um float.
* @param bArr
* @return Retorna um float que representa o array de bytes bArr.
*/
public static byte[] getByteArray(int n) {
byte[] res = new byte[4];
for (int i = 3; i >= 0; i--) {
res[i] = (byte) n;
n = n >> 8;
}
return res;
}
/**
* Recebe (parâmetro) um array de bytes e retorna um float.
* @param bArr
* @return Retorna um float que representa o array de bytes bArr.
*/
public static byte[] getByteArray(boolean b, byte option1, byte option2) {
byte[] res = new byte[1];
res[0] = b ? option1 : option2;
return res;
}
/**
* Recebe (parâmetro) um array de bytes e retorna um float.
* @param bArr
* @return Retorna um float que representa o array de bytes bArr.
*/
public static String combineStrings(String[] strs) {
String res = "";
for (int i = 0; i < strs.length; i++) {
res += strs[i];
if (i < strs.length - 1) res += ';';
}
return res;
}
/**
* Recebe (parâmetro) um array de bytes e retorna um float.
* @param bArr
* @return Retorna um float que representa o array de bytes bArr.
*/
public static byte[] combineByteArrays(byte[]... byteArrs) {
int len = 0;
for (byte[] ba : byteArrs) {
len += ba.length;
}
byte[] res = new byte[len];
int k = 0;
for (int i = 0; i < byteArrs.length; i++) {
for (int j = 0; j < byteArrs[i].length; j++) {
res[k] = byteArrs[i][j];
k++;
}
}
return res;
}
public static float getFloat(byte[] bArr) {
int bits = 0;
for (int i = 0; i < 4; i++) {
bits = bits << 8;
bits = bits | (bArr[i] & 0xFF);
}
return Float.intBitsToFloat(bits);
}
public static long getUTC(String str) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
"yyyy-MM-dd'T'HH:mm:ss.SSSSSS"
);
return java.time.LocalDateTime
.parse(str, formatter)
.toEpochSecond(java.time.ZoneOffset.UTC);
}
/**
* Recebe (parâmetro) dois produtos e atributo a ser comparado. Compara ambos os produtos com base no atributo fornecido utilizando funções da classe Util.
* @param n
* @param operator
* @param n2
* @return Retorna true se a comparação for verdadeira e false caso contrário.
*/
public static boolean compareNumber(double n, String operator, double n2) {
switch (operator) {
case "=":
return n == n2;
case "<":
return n < n2;
case ">":
return n > n2;
case "<=":
return n <= n2;
case ">=":
return n >= n2;
case "!=":
return n != n2;
default:
return false;
}
}
/**
* Recebe (parâmetro) dois produtos e atributo a ser comparado. Compara ambos os produtos com base no atributo fornecido utilizando funções da classe Util.
* @param b
* @param operator
* @param b2
* @return Retorna true se a comparação for verdadeira e false caso contrário.
*/
public static boolean compareBoolean(boolean b, String operator, boolean b2) {
switch (operator) {
case "=":
return b == b2;
case "!=":
return b != b2;
default:
return false;
}
}
/**
* Recebe (parâmetro) dois produtos e atributo a ser comparado. Compara ambos os produtos com base no atributo fornecido utilizando funções da classe Util.
* @param str1
* @param str2
* @return Retorna -1 se str1 < str2, 1 se str1 > str2 e 0 se str1 == str2.
*/
public static int cmpStrings(String str1, String str2) {
int i = 0;
while (i < str1.length() && i < str2.length()) {
if (str1.charAt(i) < str2.charAt(i)) {
return -1;
}
if (str1.charAt(i) > str2.charAt(i)) {
return 1;
}
i++;
}
if (str1.length() < str2.length()) {
return -1;
}
if (str1.length() > str2.length()) {
return 1;
}
return 0;
}
/**
* Recebe (parâmetro) um array de produtos, índices esquerdo e direito e atributo a ser comparado. Ordena o array com base no atributo fornecido utilizando o algoritmo de ordenação quicksort.
* @param arr
* @param esq
* @param dir
* @param property
*/
public static Produto[] removeEndingNulls(Produto[] arr) {
int i = arr.length - 1;
while (i >= 0 && arr[i] == null) {
i--;
}
Produto[] res = new Produto[i + 1];
for (int j = 0; j <= i; j++) {
res[j] = arr[j];
}
return res;
}
/**
* Recebe (parâmetro) um array de produtos, índices esquerdo e direito e atributo a ser comparado. Ordena o array com base no atributo fornecido utilizando o algoritmo de ordenação quicksort.
* @param raf
* @return Produto - produto lido do arquivo.
* @throws Exception
*/
public static Produto rawReadProduto(RandomAccessFile raf) throws Exception {
raf.readByte();
int len = raf.readInt();
raf.seek(raf.getFilePointer() - 5);
byte[] bArr = new byte[len + 5];
raf.read(bArr);
Produto p = new Produto(bArr);
return p;
}
public static Produto[] quicksort(Produto[] arr) {
quicksort(arr, 0, arr.length - 1);
return arr;
}
public static void quicksort(Produto[] arr, int esq, int dir) {
if (esq < dir) {
int p = partition(arr, esq, dir);
quicksort(arr, esq, p - 1);
quicksort(arr, p + 1, dir);
}
}
public static int partition(Produto[] arr, int esq, int dir) {
Produto pivot = arr[dir];
int i = esq - 1;
for (int j = esq; j < dir; j++) {
if (arr[j].getId() < pivot.getId()) {
i++;
Produto temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
Produto temp = arr[i + 1];
arr[i + 1] = arr[dir];
arr[dir] = temp;
return i + 1;
}
public static Produto[] mergeArrays(
Produto[] arr1,
Produto[] arr2,
boolean inclusive
) {
//retorna um array de produtos que é a união dos arrays arr1 e arr2 caso inclusive seja true
//ou a interseção dos arrays arr1 e arr2 caso inclusive seja false
//remover duplicatas
//retornar array ordenado
Produto[] res = new Produto[arr1.length + arr2.length];
arr1 = quicksort(arr1);
arr2 = quicksort(arr2);
if (inclusive) {
int i = 0;
int j = 0;
int k = 0;
while (i < arr1.length && j < arr2.length) {
if (arr1[i].getId() < arr2[j].getId()) {
res[k] = arr1[i];
i++;
} else if (arr1[i].getId() > arr2[j].getId()) {
res[k] = arr2[j];
j++;
} else {
res[k] = arr1[i];
i++;
j++;
}
k++;
}
while (i < arr1.length) {
res[k] = arr1[i];
i++;
k++;
}
while (j < arr2.length) {
res[k] = arr2[j];
j++;
k++;
}
return removeEndingNulls(res);
} else {
int i = 0;
int j = 0;
int k = 0;
while (i < arr1.length && j < arr2.length) {
if (arr1[i].getId() < arr2[j].getId()) {
i++;
} else if (arr1[i].getId() > arr2[j].getId()) {
j++;
} else {
res[k] = arr1[i];
i++;
j++;
k++;
}
}
return removeEndingNulls(res);
}
}
}
| j0taaa/tp3aeds3 | Util.java | 3,110 | /**
* Recebe (parâmetro) um array de bytes e retorna um float.
* @param bArr
* @return Retorna um float que representa o array de bytes bArr.
*/ | block_comment | en | true |
93670_2 |
import java.util.*;
public class KStar {
public static void main(String [] args)
{
Scanner scan=new Scanner(System.in);
System.out.println("range of steps n is from 0 to: ");
int input_n=scan.nextInt();
System.out.println("range of e is from 0 to: ");
int input_e=scan.nextInt();
long sb;
boolean done;
SBN sb1=new SBN(input_n,input_e);
sb1.calculate_combination();
int a;//SB increment
long left;
long right;
long test;
for(int i=0;i<=input_e;i++)
{
for(int j=1;j<=input_n;j++)
{
if(j<=i)
System.out.print("1\t");
else
{
done=false;
sb=sb1.sbk(j, i); // SB is returning SB value for specific e and n value
a=0;
while(!done)
{
test=sb-2+(long)Math.pow(2.0,a+1); // test=sb, test=sb+3, test=sb+7, test=sb+15.....
if(obj2(test,j,i))
{
right=test; //right=SB-2+2^(i+1)
left=sb-1+(long)Math.pow(2.0,a); //Left=SB-1+2^i
System.out.print(search(left,right,j,i)+"\t");
done=true;
}
else
{
a++;
}
}
}
}
System.out.println(); // generate new line after a row is completed.
}
}
public static long search(long left,long right,int n,int e)
{
long mid=(long)Math.floor((left+right)/2.0);
if(left==right)
return left;
else if(obj2(mid,n,e))
return search(left,mid,n,e);
else
return search(mid+1,right,n,e);
}
// minM paul wins KStar
public static boolean obj2(long m,int n,int e)// return true when paul wins
{
State_Vector object=new State_Vector(m,n);
for(int i=0;i<n;i++)
{
object.move1();
}
if(object.posi1()<=e) // if 1st chip survives-> paul wins
return true;
else
return false;
}
}
| 3ancho/LGenerator | src/KStar.java | 676 | // test=sb, test=sb+3, test=sb+7, test=sb+15..... | line_comment | en | true |
93997_0 | /*
140. Word Break II
Given a string s and a dictionary of strings wordDict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
Example 1:
Input: s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"]
Output: ["cats and dog","cat sand dog"]
Example 2:
Input: s = "pineapplepenapple", wordDict = ["apple","pen","applepen","pine","pineapple"]
Output: ["pine apple pen apple","pineapple pen apple","pine applepen apple"]
Explanation: Note that you are allowed to reuse a dictionary word.
Example 3:
Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
Output: []
Constraints:
1 <= s.length <= 20
1 <= wordDict.length <= 1000
1 <= wordDict[i].length <= 10
s and wordDict[i] consist of only lowercase English letters.
All the strings of wordDict are unique.
Input is generated in a way that the length of the answer doesn't exceed 105.
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
class Day136 {
// Function to find all possible sentences from string 's' using words from 'wordDict'
public List<String> wordBreak(String s, List<String> wordDict) {
// Convert wordDict to a set for O(1) lookups
Set<String> wordSet = new HashSet<>(wordDict);
// Create a memoization map to store results for substrings
Map<String, List<String>> mem = new HashMap<>();
// Call the helper function with the initial string 's'
return wordBreak(s, wordSet, mem);
}
// Helper function for the recursive word break process
private List<String> wordBreak(final String s, Set<String> wordSet,
Map<String, List<String>> mem) {
// If the result for the current string 's' is already computed, return it
if (mem.containsKey(s))
return mem.get(s);
// Initialize a list to store possible sentences
List<String> ans = new ArrayList<>();
// Loop through all possible prefixes of 's'
// 1 <= prefix.length() < s.length() ensures that prefix is not empty and not the whole string
for (int i = 1; i < s.length(); ++i) {
// Extract the prefix from the start to the current index 'i'
final String prefix = s.substring(0, i);
// Extract the suffix from the current index 'i' to the end
final String suffix = s.substring(i);
// If the prefix is a valid word, recursively process the suffix
if (wordSet.contains(prefix))
// Concatenate prefix with each valid sentence from the suffix and add to the result
for (final String word : wordBreak(suffix, wordSet, mem))
ans.add(prefix + " " + word);
}
// If the whole string 's' is a valid word, add it to the result
if (wordSet.contains(s))
ans.add(s);
// Memoize the result for the current string 's'
mem.put(s, ans);
// Return the list of possible sentences for the current string 's'
return ans;
}
}
| sugaryeuphoria/LeetCode-100-Days-of-Code | Day136.java | 844 | /*
140. Word Break II
Given a string s and a dictionary of strings wordDict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
Example 1:
Input: s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"]
Output: ["cats and dog","cat sand dog"]
Example 2:
Input: s = "pineapplepenapple", wordDict = ["apple","pen","applepen","pine","pineapple"]
Output: ["pine apple pen apple","pineapple pen apple","pine applepen apple"]
Explanation: Note that you are allowed to reuse a dictionary word.
Example 3:
Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
Output: []
Constraints:
1 <= s.length <= 20
1 <= wordDict.length <= 1000
1 <= wordDict[i].length <= 10
s and wordDict[i] consist of only lowercase English letters.
All the strings of wordDict are unique.
Input is generated in a way that the length of the answer doesn't exceed 105.
*/ | block_comment | en | true |
94587_0 | /* NumberSolitaire
In a given array, find the subset of maximal sum in which the distance between consecutive elements is at most 6.
Task Score 100%, Correctness 100%, Performance 100%
A game for one player is played on a board consisting of N consecutive squares, numbered from 0 to N − 1. There is a number written on each square. A non-empty array A of N integers contains the numbers written on the squares. Moreover, some squares can be marked during the game.
At the beginning of the game, there is a pebble on square number 0 and this is the only square on the board which is marked. The goal of the game is to move the pebble to square number N − 1.
During each turn we throw a six-sided die, with numbers from 1 to 6 on its faces, and consider the number K, which shows on the upper face after the die comes to rest. Then we move the pebble standing on square number I to square number I + K, providing that square number I + K exists. If square number I + K does not exist, we throw the die again until we obtain a valid move. Finally, we mark square number I + K.
After the game finishes (when the pebble is standing on square number N − 1), we calculate the result. The result of the game is the sum of the numbers written on all marked squares.
For example, given the following array:
A[0] = 1
A[1] = -2
A[2] = 0
A[3] = 9
A[4] = -1
A[5] = -2
one possible game could be as follows:
the pebble is on square number 0, which is marked;
we throw 3; the pebble moves from square number 0 to square number 3; we mark square number 3;
we throw 5; the pebble does not move, since there is no square number 8 on the board;
we throw 2; the pebble moves to square number 5; we mark this square and the game ends.
The marked squares are 0, 3 and 5, so the result of the game is 1 + 9 + (−2) = 8. This is the maximal possible result that can be achieved on this board.
Write a function:
class Solution { public int solution(int[] A); }
that, given a non-empty array A of N integers, returns the maximal result that can be achieved on the board represented by array A.
Assume that:
N is an integer within the range [2..100,000];
each element of array A is an integer within the range [−10,000..10,000].
Complexity:
expected worst-case time complexity is O(N);
expected worst-case space complexity is O(N) (not counting the storage required for input arguments). */
class Solution {
/* We create an array with the same size of the main array,
where we will keep the maximum sum so far: from the
beginning up to the current cell of the A. For counting
next cell of this dynamic sum array we add value of
corresponding value of A to maximum value of previous
6 cells of the dynamic sum array */
public int solution(int[] A) {
int n = A.length;
int[] dynamicSum = new int[n];
dynamicSum[0] = A[0];
int maxCurrent;
for (int i = 1; i < n; i++) {
maxCurrent = dynamicSum[i-1];
for (int j = 1; j <= 6; j++)
if (i - j >= 0)
maxCurrent = Math.max(dynamicSum[i-j], maxCurrent);
dynamicSum[i] = maxCurrent + A[i];
}
return dynamicSum[n-1];
}
} | vilasha/Codility-Lessons-Java8 | task32.java | 930 | /* NumberSolitaire
In a given array, find the subset of maximal sum in which the distance between consecutive elements is at most 6.
Task Score 100%, Correctness 100%, Performance 100%
A game for one player is played on a board consisting of N consecutive squares, numbered from 0 to N − 1. There is a number written on each square. A non-empty array A of N integers contains the numbers written on the squares. Moreover, some squares can be marked during the game.
At the beginning of the game, there is a pebble on square number 0 and this is the only square on the board which is marked. The goal of the game is to move the pebble to square number N − 1.
During each turn we throw a six-sided die, with numbers from 1 to 6 on its faces, and consider the number K, which shows on the upper face after the die comes to rest. Then we move the pebble standing on square number I to square number I + K, providing that square number I + K exists. If square number I + K does not exist, we throw the die again until we obtain a valid move. Finally, we mark square number I + K.
After the game finishes (when the pebble is standing on square number N − 1), we calculate the result. The result of the game is the sum of the numbers written on all marked squares.
For example, given the following array:
A[0] = 1
A[1] = -2
A[2] = 0
A[3] = 9
A[4] = -1
A[5] = -2
one possible game could be as follows:
the pebble is on square number 0, which is marked;
we throw 3; the pebble moves from square number 0 to square number 3; we mark square number 3;
we throw 5; the pebble does not move, since there is no square number 8 on the board;
we throw 2; the pebble moves to square number 5; we mark this square and the game ends.
The marked squares are 0, 3 and 5, so the result of the game is 1 + 9 + (−2) = 8. This is the maximal possible result that can be achieved on this board.
Write a function:
class Solution { public int solution(int[] A); }
that, given a non-empty array A of N integers, returns the maximal result that can be achieved on the board represented by array A.
Assume that:
N is an integer within the range [2..100,000];
each element of array A is an integer within the range [−10,000..10,000].
Complexity:
expected worst-case time complexity is O(N);
expected worst-case space complexity is O(N) (not counting the storage required for input arguments). */ | block_comment | en | true |
94696_2 | /*
* 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 net.candhcapital.Graphing;
import java.awt.Color;
import java.awt.Rectangle;
import java.text.DecimalFormat;
/**
*
* @author Corporate
*/
public class Block {
/**
* Need to know if red for different brightener.
*/
private boolean red;
/**
* The start time.
*/
private ZonedStockDateTime beginning;
/**
* The value of our block.
*/
private double value;
/**
* The color of the block (based on candles).
*/
private final Color blockColor;
/**
* The rectangle we are going to draw.
*/
private Rectangle block;
/**
* Needs a way to see if we can graph this.
*/
private boolean gotBlock = false;
/**
* A formatted string with our volume.
*/
private final String formattedValue;
/**
* The Candle UP color.
*/
private static final Color CANDLEUPCOLOR = new Color(0, 153, 0);
/**
* The Candle NEUTRAL color.
*/
private static final Color CANDLENEUTRALCOLOR = new Color(255, 255, 0);
/**
* The Candle DOWN color.
*/
private static final Color CANDLEDOWNCOLOR = new Color(204, 0, 0);
/**
* Takes a block and sets the color.
* @param start the time this block starts at.
* @param pDifference the difference of the last volume and first.
* @param pColor a double so we know what color to make this block.
*/
public Block(final ZonedStockDateTime start,
final double pvalue, final double pColor) {
beginning = start;
DecimalFormat formatter = new DecimalFormat("#,###");
formattedValue = "Volume: " + formatter.format(pvalue) + "M";
value = pvalue;
if (pColor > 0) {
blockColor = CANDLEUPCOLOR;
} else if (pColor == 0) {
blockColor = CANDLENEUTRALCOLOR;
} else {
blockColor = CANDLEDOWNCOLOR;
red = true;
}
}
/**
* Once we know the dimensions of the window we can calculate the location
* of the rectangle we are going to draw.
* @param start The start time of our window.
* @param pixelWeight The number of seconds per pixel.
* @param candleWidth The width of our candles.
* @param bottom The lowy value.
* @param top The highy value.
* @param pixelHeight The number of pixels of our graph.
*/
public final void setRectangles(final ZonedStockDateTime start,
final double pixelWeight, final int candleWidth,
final double bottom, final double top, final int pixelHeight,
final int topMargin) {
int x1 = (int)
Math.round(start.getMarketSecondsUntil(beginning)
/ pixelWeight);
ZonedStockDateTime end = beginning.getCopy();
end.addSeconds(candleWidth);
int x2 = (int)
Math.round(start.getMarketSecondsUntil(end) / pixelWeight) - 1;
double valueHeight = top - bottom;
int y1 = (int) Math.round(pixelHeight
- (pixelHeight / valueHeight * (0 - bottom))) + topMargin;
int y2 = (int) Math.round(pixelHeight
- (pixelHeight / valueHeight * (value - bottom))) + topMargin;
if (y1 - y2 >= 0) {
block = new Rectangle(x1, y2, x2 - x1, y1 - y2);
} else {
block = new Rectangle(x1, y1, x2 - x1, y2 - y1);
}
gotBlock = true;
}
/**
* public block's start X value.
* @return **the x-value to start at**
*/
public final int getX() {
if (gotBlock) {
return (int) block.getX();
} else {
return -1;
}
}
/**
* public block's start Y value.
* @return **the y-value to start at**
*/
public final int getY() {
if (gotBlock) {
return (int) block.getY();
} else {
return -1;
}
}
/**
* public block's width.
* @return **the width of our block**
*/
public final int getWidth() {
if (gotBlock) {
return (int) block.getWidth();
} else {
return -1;
}
}
/**
* public block's height.
* @return **the height of our block**
*/
public final int getHeight() {
if (gotBlock) {
return (int) block.getHeight();
} else {
return -1;
}
}
/**
* Gets the color of our block.
* @return **the color of our block**
*/
public final Color getColor() {
return blockColor;
}
/**
* Checks to see if our candle should be red.
* @return true for red.
*/
public final boolean isRed() {
return red;
}
/**
* Checks to see if the mouse is in that block.
* @param x **The x-value our mouse is currently at**
* @return **True if the mouse is contained**
*/
public final boolean matchMouseX(final int x) {
return (x >= getX() && x <= getX() + getWidth());
}
/**
* simple toString() function.
* @return **The value formatted with commas**
*/
@Override
public final String toString() {
return formattedValue;
}
public final double getValue() {
return value;
}
}
| BenAychh/java-graphing | Block.java | 1,389 | /**
* Need to know if red for different brightener.
*/ | block_comment | en | false |
95473_12 | // public class myProgram1{
// public static void main(String[] args) {
// System.out.println("Hello, World!");
// int age= 47;
// System.out.println("my age is "+ age );
// }
// }
// Lab1a.java
// This short class has several bugs for practice.
// Authors: Carol Zander, Rob Nash, Clark Olson, you
public class Lab1a {
public static void main(String[] args) {
compareNumbers();
calculateDist();
}
public static void compareNumbers() { //space after public
int firstNum = 5;
int secondNum = 2; //do we need to define second num?
System.out.println( "Sum is: "+ firstNum + secondNum ); //missing parenthesis close after : and secondNum hasn't been initialized above
System.out.println( "Difference is: " + (firstNum - secondNum));//add ) to complete expression
System.out.println( "Product is: " + firstNum * secondNum ); //typo nuM
}
public static void calculateDist() {//need to shorten name to calculateDist
int velocity = 10; //miles-per-hour
int time = 2, //hoursint
distance = velocity * time;//missing semicolon and from the new line System.out.println
System.out.println( "Total distance is: " + distance); //typo distAnce and missing +
}
} | impeterbol/CSS142 | Lab1a.java | 343 | //missing parenthesis close after : and secondNum hasn't been initialized above | line_comment | en | false |
95490_1 | // Practice
// 계산기 덧셈의 여러 타입 오버로딩
class Calculator {
public int sum(int a, int b) {
return a + b;
}
public double sum(double a, double b) {
return a + b;
}
public double sum(String a, String b) {
return Double.parseDouble(a) + Double.parseDouble(b);
}
public int sum(int a, int b, int c) {
return a + b + c;
}
}
public class Class4 {
public static void main(String[] args) {
// Test code
Calculator c = new Calculator();
System.out.println(c.sum(1, 2));
System.out.println(c.sum(1.0, 2.0));
System.out.println(c.sum("1", "2"));
System.out.println(c.sum(1, 2, 3));
}
}
| KYUWON1/JAVA | Class4.java | 230 | // 계산기 덧셈의 여러 타입 오버로딩 | line_comment | en | true |
95524_0 | package week3.day2;
public interface HardWare {
void hardwareResources();
/**
* Hardware Resources details
*/
}
| krishnabharathi123/week3.day2 | HardWare.java | 34 | /**
* Hardware Resources details
*/ | block_comment | en | true |
96112_3 | ///usr/bin/env jbang "$0" "$@" ; exit $?
// Update the Quarkus version to what you want here or run jbang with
// `-Dquarkus.version=<version>` to override it.
//DEPS io.quarkus:quarkus-bom:${quarkus.version:2.8.0.Final}@pom
//DEPS io.quarkus:quarkus-resteasy-reactive-qute
//DEPS io.quarkus:quarkus-mutiny
//JAVAC_OPTIONS -parameters
//FILES templates/Main/index.html=index.html
//FILES templates/Main/board.html=board.html
//FILES templates/Main/chats.html=chats.html
//SOURCES *.java
package yolo.chatapp.controllers;
import io.quarkus.qute.CheckedTemplate;
import io.quarkus.qute.TemplateInstance;
import io.smallrye.mutiny.Multi;
import org.jboss.resteasy.reactive.RestSseElementType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import yolo.chatapp.model.Chat;
import yolo.chatapp.model.Message;
import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.time.Instant;
@Path("/chat")
public class Main {
private static final Logger logger = LoggerFactory.getLogger(Main.class);
@Inject
Chat chat;
@CheckedTemplate
public static class Templates {
public static native TemplateInstance index(Chat chat);
public static native TemplateInstance board(Chat chat);
public static native TemplateInstance chats(Chat chat);
}
@GET
@Produces(MediaType.TEXT_HTML)
public TemplateInstance get() {
logger.info("New client");
return Templates.index(chat);
}
@POST
@Path("send")
@Produces(MediaType.TEXT_HTML)
public TemplateInstance newMessage(@FormParam("newMessage") String newMessage) {
if (newMessage.isBlank()) {
logger.info("Blank message, discarding");
} else {
logger.info("New message: {}", newMessage);
chat.push(new Message(Instant.now(), newMessage));
}
return Templates.board(chat);
}
@GET
@Path("updates")
@Produces(MediaType.SERVER_SENT_EVENTS)
@RestSseElementType(MediaType.TEXT_HTML)
public Multi<String> updates() {
logger.info("New SSE client");
return chat.updatesBroadcaster()
.onItem().invoke(() -> logger.info("Pushing updates"))
.onItem().transform(tick -> Templates.chats(chat).render());
}
}
| maxandersen/testqute | Main.java | 620 | //DEPS io.quarkus:quarkus-bom:${quarkus.version:2.8.0.Final}@pom | line_comment | en | true |
96285_5 | package Final;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import Final.Final;
/*
* this class contains only static methods intended to be used for building and working with UI components
*
*/
public class UIService {
//appends message to main TextArea
public static void appendMessage(String message){
Final.mainPane.textArea.appendText(message + '\n');
}
//standard validation used application-wide for a user-entered value that will be used in a query
public static boolean isValidSearch(String id){
boolean isValid = true;
String regex = "[0-9]+"; //allow only numbers
if(id == null || id.equals("") || !id.matches(regex)){isValid = false;}
return isValid;
}
//generically designed method for iterating over a map of properties in a TableModel instance,
//this function will return a new grid pane containing each property's key and a text field object
//which is automatically bound to the data model object's observable property value
public static GridPane buildGrid(TableModel model){
GridPane grid = new GridPane();
int i = 0;
for(String propName : model.properties.keySet()){
grid.add(new Label(propName), 0, i);
TextField textField = new TextField();
textField.textProperty().bindBidirectional(model.properties.get(propName));
grid.add(textField, 1, i);
i++;
}
Button search = new Button("Search by " + model.searchKey);
search.setOnAction((e) -> {
try {
String resultText = model.search();
appendMessage(resultText);
} catch (Exception e1) {
model.clear();
e1.printStackTrace();
}
});
grid.add(search, 0, i);
return grid;
}
}
| cornelius-k/Library-Catalog | UIService.java | 588 | //this function will return a new grid pane containing each property's key and a text field object | line_comment | en | false |
96345_0 | /*(7)
Write an application that accepts marks of three different subject from user.
Marks should be between 0 to 100, if marks of any of the subject is not belong
to this range, generate custom exception out of RangeException. If marks of
each subjects are greater than or equal to 40 then display message "PASS" along
with percentage, otherwise display message "FAIL". Also write exception
handling code to catch all the possible runtime exceptions likely to be generated
in the program.
*/
class RangeException extends Exception
{
RangeException(int i)
{
super("RangeException: Marks is not valid:"+i);
}
}
class u3_7
{
public static void main(String args[])
{
int a[]=new int[3];
int sum=0;
float per;
for(int i=0;i<3;i++)
{
try
{
a[i]=Integer.parseInt(args[i]);
if(a[i]<0 || a[i]>100)
{
throw new RangeException(a[i]);
}
else if(a[i]>=40)
{
sum=sum+a[i];
System.out.println("\n Pass in subject:"+i);
}
}
catch(RangeException e1)
{
System.out.println("Error:"+e1.getMessage());
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index Exception occurs");
}
catch(NumberFormatException e)
{
System.out.println("NumberFormatException");
}
}
per=(float)sum/3;
System.out.println("\n Percentage is:"+per);
}
}
/*OUTPUT=>>javac u3_7.java
java u3_7 10 45 99
Pass in subject:1
Pass in subject:2
Percentage is:48.0
C:\Users\sneha\OneDrive\Desktop\package>java u3_7 10 45 102
Pass in subject:1
Error:RangeException: Marks is not valid:102
Percentage is:15.0
*/ | sneha2o/JAVA | u3_7.java | 551 | /*(7)
Write an application that accepts marks of three different subject from user.
Marks should be between 0 to 100, if marks of any of the subject is not belong
to this range, generate custom exception out of RangeException. If marks of
each subjects are greater than or equal to 40 then display message "PASS" along
with percentage, otherwise display message "FAIL". Also write exception
handling code to catch all the possible runtime exceptions likely to be generated
in the program.
*/ | block_comment | en | true |
96393_0 |
/*
rPeanut - is a simple simulator of the rPeANUt computer.
Copyright (C) 2011 Eric McCreath
Copyright (C) 2012 Joshua Worth
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/>.
*/
public class D {
static final boolean debug = false;
static public void p(String s) {
if (debug) System.out.println(s);
}
static public void p(Object s) {
if (debug) System.out.println(s.toString());
}
}
| bnjf/rpeanut | src/D.java | 270 | /*
rPeanut - is a simple simulator of the rPeANUt computer.
Copyright (C) 2011 Eric McCreath
Copyright (C) 2012 Joshua Worth
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/>.
*/ | block_comment | en | true |
97050_0 | /* QB-262:
Sports tournament organizer:
Write a program that simulates a sports tournament using a PriorityQueue. The program
should allow the user to input team names and their win-loss records. The program should
then prioritize teams based on their win-loss records and add them to the PriorityQueue.
When it's time for the next match, the program should remove the two highest priority
teams from the PriorityQueue and display their names.
*/
import java.util.*;
class Team {
String name;
int win;
int loss;
public Team(String name, int win, int loss) {
this.name = name;
this.win = win;
this.loss = loss;
}
public String toString() {
return name;
}
public int getWinLossRatio() {
return win - loss;
}
}
class SportsTournament {
public static void main(String[] args) {
PriorityQueue<Team> TeamList = new PriorityQueue<>(Comparator.comparing(Team::getWinLossRatio).reversed());
Scanner sc = new Scanner(System.in);
System.out.println("Enter No.of Teams: ");
int team = sc.nextInt();
sc.nextLine();
// To input team names and their win-loss records
for (int i = 0; i < team; i++) {
System.out.println("Enter Team name for " + (i + 1) + " th: ");
String teamname = sc.nextLine();
System.out.println("Enter number of wins: of " + teamname + "'s Team: ");
int win = sc.nextInt();
System.out.println("Enter number of loss: of " + teamname + "'s Team: ");
int loss = sc.nextInt();
sc.nextLine();
Team t = new Team(teamname, win, loss);
TeamList.add(t);
}
// Next-Match Maker
System.out.println("~~~NEXT-MATCH~~~");
if (!TeamList.isEmpty()) {
Team t1 = TeamList.poll();
Team t2 = TeamList.poll();
System.out.println(t1 + " VS " + t2);
} else {
System.out.println("Not Enough Teams to Start the match (Min:2 Req.)");
}
}
}
| ishanshah018/java-Sem-II-Ques-Bank | qb262.java | 536 | /* QB-262:
Sports tournament organizer:
Write a program that simulates a sports tournament using a PriorityQueue. The program
should allow the user to input team names and their win-loss records. The program should
then prioritize teams based on their win-loss records and add them to the PriorityQueue.
When it's time for the next match, the program should remove the two highest priority
teams from the PriorityQueue and display their names.
*/ | block_comment | en | true |
97067_0 |
public class LossyEx {
public static void main(String[] args) {
byte n1 = 100; // -128 to 127
byte n2 = 50;
byte sum = (byte) (n1+n2);
System.out.println(sum); // lossy conversion
}
}
| Harshine27/CoreJava | LossyEx.java | 87 | // -128 to 127
| line_comment | en | true |
97520_30 | package A3;
import java.util.Random;
/*
* @author Matthew Pan 40135588
*
* Jobs class which represent the processes in the priority queue.
* */
public class Job implements Comparable<Job> {
//"JOB_(arrayIndexNb+1)"
private String jobName;
//needed CPU cycles for this job, randomize between 1 and 70 cycles
private int jobLength;
//remaining job length at any time
private int currentJobLength;
//initial priority, randomize between 1 (highest) and 40
private int jobPriority;
//final priority at termination time
private int finalPriority;
//time of when job entered PQ, set to currentTime when inserted
private long entryTime;
//time of when job terminated, currenTime when executed
private long endTime;
//total amount of wait time before execution, doesn't include execution time
//(endTime - entryTime - jobLength) does not include execution's time, maybe endTime-1
private long waitTime;
//counter to track current time (CPU cycles);
//+1 for every PQ insertion, job execution and search for starved process
private static long currentTime = 0;
/* default constructor */
Job() { }
/* param constructor: initialize job with name, the
* priority is randomized.
*
* @param index the index in the array where the job is */
Job(int index) {
Random prio = new Random();
jobName = "JOB_" + index;
jobPriority = prio.nextInt(41) + 1;
finalPriority = jobPriority;
jobLength = prio.nextInt(71) + 1;
currentJobLength = jobLength;
entryTime = 0;
endTime = 0;
waitTime = 0;
};
//test constructor for non-random priority------------------------
Job(int index, int priority) {
Random prio = new Random();
jobName = "JOB_" + index;
jobPriority = priority;
finalPriority = jobPriority;
jobLength = prio.nextInt(71) + 1;
currentJobLength = jobLength;
entryTime = 0;
endTime = 0;
waitTime = 0;
};
/**
* decrements job length, sets end time and wait time.
* @return true if the job has terminated completely, false otherwise
*/
public boolean execute() {
if(currentJobLength > 0) {
currentJobLength--;
System.out.print(" -> Now executing ");
System.out.println(this.toString());
}
//if job terminated
if(currentJobLength <= 0) {
endTime = currentTime;
waitTime = endTime - entryTime - jobLength;
currentTime++;
return true;
}
//if job needs to be put back in PQ
else {
currentTime++;
return false;
}
}
/**
* compares the priority of two jobs, if same = FIFO order
* @return -1 if this job is higher priority or equal to the passed one (no swap)
*/
public int compareTo(Job o) {
if(this.finalPriority < o.getFinalPriority())
return -1;
else if(this.finalPriority == o.getFinalPriority())
return 0;
else
return 1;
}
/**
* @param o job to compare with
* @return true if they are the same job
*/
public boolean equals(Job o) {
return jobName.equals(o.getJobName());
}
/** print the job */
public String toString() {
return jobName + ": [Job length - " + jobLength + " cycles]" + " [Remaining length - " + currentJobLength + " cycles]"
+ " [Initial priority - " +Integer.toString(jobPriority) + "]" + " [Current priority - " + finalPriority + "]" + " [Current time - " + currentTime + "]";
}
/**
* @return the jobName
*/
public String getJobName() {
return jobName;
}
/**
* @param jobName the jobName to set
*/
public void setJobName(String jobName) {
this.jobName = jobName;
}
/**
* @return the jobLength
*/
public int getJobLength() {
return jobLength;
}
/**
* @param jobLength the jobLength to set
*/
public void setJobLength(int jobLength) {
this.jobLength = jobLength;
}
/**
* @return the currentJobLength
*/
public int getCurrentJobLength() {
return currentJobLength;
}
/**
* @param currentJobLength the currentJobLength to set
*/
public void setCurrentJobLength(int currentJobLength) {
this.currentJobLength = currentJobLength;
}
/**
* @return the jobPriority
*/
public int getJobPriority() {
return jobPriority;
}
/**
* @param jobPriority the jobPriority to set
*/
public void setJobPriority(int jobPriority) {
this.jobPriority = jobPriority;
}
/**
* @return the finalPriority
*/
public int getFinalPriority() {
return finalPriority;
}
/**
* @param finalPriority the finalPriority to set
*/
public void setFinalPriority(int finalPriority) {
this.finalPriority = finalPriority;
}
/**
* @return the entryTime
*/
public long getEntryTime() {
return entryTime;
}
/**
* @param entryTime the entryTime to set
*/
public void setEntryTime(long entryTime) {
this.entryTime = entryTime;
}
/**
* @return the endTime
*/
public long getEndTime() {
return endTime;
}
/**
* @param endTime the endTime to set
*/
public void setEndTime(long endTime) {
this.endTime = endTime;
}
/**
* @return the waitTime
*/
public long getWaitTime() {
return waitTime;
}
/**
* @param waitTime the waitTime to set
*/
public void setWaitTime(long waitTime) {
this.waitTime = waitTime;
}
/**
* @return the currentTime
*/
public static long getCurrentTime() {
return currentTime;
}
public static void setCurrentTime(long n) {
currentTime = n;
}
}
| Fryingpannn/DataStructures-Algorithms | A3/Job.java | 1,599 | /**
* @param finalPriority the finalPriority to set
*/ | block_comment | en | false |
97548_0 | package complexability.motionmusicv2;
import android.util.Log;
/**
* Created by Sorawis on 2/1/2016.
*/
public class Hands {
/**
* id
* 0 = forward-back
* 1 = up-down
* 2 = left-right
* 3 = pitch (tilt forward)
* 4 = roll (tilt LR)
*/
private static final int NONE = 0;
private static final int VOLUME = 1;
private static final int FREQUENCY = 2;
private static final int REVERB = 3;
private static final int DELAY = 4;
private static final int FLANGER = 5;
private static final int DISTORTION = 6;
private static final int ROTARY = 7;
private static final int SPACY = 1000;
private static final int GUITAR = 1001;
private static final int FLUTE = 1002;
private int[] Effects;
private int Instrument;
public Hands() {
Effects = new int[5];
Instrument = 1000;
Effects[0] = 0;
Effects[1] = 0;
Effects[2] = 0;
Effects[3] = 0;
Effects[4] = 0;
}
public void setInstrument(int instrument){
Instrument = instrument;
}
public int getInstrument(){
return Instrument;
}
public void setEffects(int id, int effect){
Effects[id] = effect;
}
public int getEffect(int id){
return Effects[id];
}
public int[] getAllEffect(){
return Effects;
}
public void showSelected(){
for(int i = 0 ; i < Effects.length; i++){
Log.d("TEST ","Effect["+ effectType(i) + "]: " + getDefinedString(Effects[i]) );
}
//Log.d("Hands ", getDefinedString(Instrument));
}
public String getDefinedString(int data){
switch (data){
case NONE:
return "None";
case VOLUME:
return "Volume";
case FREQUENCY:
return "Frequency";
case REVERB:
return "Reverb";
case DELAY:
return "Delay";
case FLANGER:
return "Flanger";
case DISTORTION:
return "Distortion";
case ROTARY:
return "Rotary";
case SPACY:
return "Spacy";
case GUITAR:
return "Guitar";
case FLUTE:
return "Flute";
default:
return null;
}
}
public String effectType(int type){
switch(type){
case 0:
return "PITCH";
case 1:
return "ROLL";
case 2:
return "Y-AXIS";
case 3:
return "Z-AXIS";
case 4:
return "X-AXIS";
default:
return "NONE";
}
}
}
| bosorawis/MotionMusicV2 | Hands.java | 723 | /**
* Created by Sorawis on 2/1/2016.
*/ | block_comment | en | true |
97799_2 | public class comments {
public static void main(String[] A) {
// When comments are short we use the single-line syntax: //
// When comments are long we use the multi-line syntax: /* and */
/*
* We chose to store information across multiple databases to
* minimize the possibility of data loss. We'll need to be careful
* to make sure it does not go out of sync!
*/
/**
* Another type of commenting option is the Javadoc comment which is represented by
* Javadoc comments are used to create documentation for APIs (Application Programming Interfaces).
* When writing Javadoc comments, remember that they will eventually be used in the documentation that
* your users might read, so make sure to be especially thoughtful when writing these comments.
*/
}
}
| BANZOM/JAVA_Tutorial | comments.java | 172 | /*
* We chose to store information across multiple databases to
* minimize the possibility of data loss. We'll need to be careful
* to make sure it does not go out of sync!
*/ | block_comment | en | true |
97893_0 |
public class Validator {
//checks to make sure the email being checked is a vaild email based on the standards in the method
public static boolean isEmail(String check){
int count = 0;
for(int i = 0; i < check.length(); i++){
if(check.substring(i, i+1).compareTo("@") == 0) //contains an @ character
count++;
}
if(count == 1){
if(check.length() <= 10)
return false;
else{
//makes sure ending matches one of these internet protocols
if(check.substring(check.length()-4, check.length()).compareTo(".com") == 0 ||
check.substring(check.length()-4, check.length()).compareTo(".net") == 0 ||
check.substring(check.length()-4, check.length()).compareTo(".org") == 0||
check.substring(check.length()-4, check.length()).compareTo(".edu") == 0 ||
check.substring(check.length()-4, check.length()).compareTo(".gov") == 0 ||
check.substring(check.length()-4, check.length()).compareTo(".mil") == 0 ||
check.substring(check.length()-4, check.length()).compareTo(".int") == 0)
return true;
else
return false;
}
}
else
return false;
}
//makes sure the phone number being checked is a valid phone number (contains 10 integers)
public static boolean isPhone(String check){
if(check.length() != 10)
return false;
else{
for(int i = 0; i < check.length(); i++){
if(!check.substring(i, i+1).equals("0") &&
!check.substring(i, i+1).equals("1") &&
!check.substring(i, i+1).equals("2") &&
!check.substring(i, i+1).equals("3") &&
!check.substring(i, i+1).equals("4") &&
!check.substring(i, i+1).equals("5") &&
!check.substring(i, i+1).equals("6") &&
!check.substring(i, i+1).equals("7") &&
!check.substring(i, i+1).equals("8") &&
!check.substring(i, i+1).equals("9"))
return false;
}
return true;
}
}
}
| GWest58/CSE-360-Project | src/Validator.java | 642 | //checks to make sure the email being checked is a vaild email based on the standards in the method | line_comment | en | false |
98649_1 | import java.util.Arrays;
public class LCS {
}
/*
* Tabulation -> Bottom-up
* TC -> O(m*n)
* SC -> O(m*n) + O(m+n)
* Rules:
* 1) Copy the base case
* a) Base case issue coz we cannot store dp[-1] so we do shifting of index
* b) Every i and j will be treated as i-1 and j-1
* c) we will use f(m,n) insted of m-1 and n-1
* d) Base case will be if i==0 || j==0 return 0
* e) In Tabulation
* f) dp[0][j] = 0
* g) dp[i][0] = 0
* h) i = j = 0-m && 0-n
* 2) Write down the changing paramater in opposite direction
* a) i = 1 -> m
* b) j = 1 -> n
* 3) Copy the recurrace
*/
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
int n = text1.length();
int m = text2.length();
int dp[][] = new int[n+1][m+1];
for(int j = 0; j<= m; j++){
dp[0][j] = 0;
}
for(int i = 0; i<= n; i++){
dp[i][0] = 0;
}
for(int i = 1; i<= n; i++){
for(int j = 1; j<= m; j++){
if(text1.charAt(i-1)==text2.charAt(j-1)){
dp[i][j] = 1 + dp[i-1][j-1];
}else{
dp[i][j] =Math.max(dp[i-1][j],dp[i][j-1]);
}
}
}
return dp[n][m];
}
}
/*
* Base shift
* Tabulation -> Bottom-up
* TC -> O(m*n)
* SC -> O(m*n) + O(m+n)
*/
class SolutionBaseShift {
public int longestCommonSubsequence(String text1, String text2) {
int m = text1.length();
int n = text2.length();
int[][] dp = new int[m+1][n+1];
for(int[] d: dp){
Arrays.fill(d,-1);
}
return lcsbaseshift(text1,text2, m, n, dp);
}
private int lcsbaseshift(String str1,String str2, int ind1, int ind2, int[][] dp){
if(ind1 == 0 || ind2 ==0){
return 0;
}
if(dp[ind1][ind2] != -1){
return dp[ind1][ind2];
}
if(str1.charAt(ind1-1) == str2.charAt(ind2-1) ){
return dp[ind1][ind2] = 1+ lcsbaseshift(str1,str2, ind1-1, ind2-1, dp);
}
return dp[ind1][ind2] = Math.max(lcsbaseshift(str1,str2, ind1-1, ind2, dp),lcsbaseshift(str1,str2, ind1, ind2-1, dp));
}
}
/*
* Memoization -> Top-Down
* TC -> O(m*n)
* SC -> O(m*n) + O(m+n)
* Rules:
* 1)
*/
class SolutionDPMemoization {
public int longestCommonSubsequence(String text1, String text2) {
int m = text1.length();
int n = text2.length();
int dp[][] = new int[m][n];
for(int[] d: dp){
Arrays.fill(d,-1);
}
return lcsmemo(text1,text2,m-1,n-1,dp);
}
private int lcsmemo(String s1, String s2, int ind1, int ind2, int[][] dp){
if(ind1 < 0 || ind2 < 0){
return 0;
}
if(dp[ind1][ind2] != -1){
return dp[ind1][ind2];
}
if(s1.charAt(ind1) == s2.charAt(ind2)){
return dp[ind1][ind2] = 1+ lcsmemo(s1,s2,ind1-1,ind2-1,dp);
}
return dp[ind1][ind2] = Math.max(lcsmemo(s1,s2,ind1-1,ind2,dp),lcsmemo(s1,s2,ind1,ind2-1,dp));
}
}
// Recursion
class SolutionRecursion {
public int longestCommonSubsequence(String text1, String text2) {
int m = text1.length();
int n = text2.length();
return lcsmemo(text1,text2,m-1,n-1);
}
private int lcsmemo(String s1, String s2, int ind1, int ind2){
if(ind1 < 0 || ind2 < 0){
return 0;
}
if(s1.charAt(ind1) == s2.charAt(ind2)){
return 1+ lcsmemo(s1,s2,ind1-1,ind2-1);
}
return Math.max(lcsmemo(s1,s2,ind1-1,ind2),lcsmemo(s1,s2,ind1,ind2-1));
}
}
| scorcism/CP | LCS.java | 1,358 | /*
* Base shift
* Tabulation -> Bottom-up
* TC -> O(m*n)
* SC -> O(m*n) + O(m+n)
*/ | block_comment | en | false |
99015_9 | /**
* Represents a customer.
* @author Sol Boucher <[email protected]>
*/
public class Customer extends User
{
/** The name by which cash customers are known. */
public static final String CASH_NAME="Anonymous"; //if this is null, constructor will fail
/** The ID reserved for cash customers. */
public static final int CASH_ID=Integer.MAX_VALUE;
/** The person's account balance. */
private int money;
/**
* Default (cash customer) constructor.
* Creates a special <i>cash</i> customer with the ability to change its balance on the fly.
* The balance starts out at <tt>0</tt>, however, and remains there until funds are added.
* @throws BadArgumentException on internal failure
*/
public Customer() throws BadArgumentException
{
super(CASH_NAME);
try
{
setId(CASH_ID);
}
catch(BadStateException impossible) //we just created the parent, so this can't happen
{
System.err.println("CRITICAL : Model detected a problem not previously thought possible!");
System.err.print(" DUMP : ");
impossible.printStackTrace();
System.err.println();
}
money=0;
}
/**
* Fresh (account-backed customer) constructor.
* Creates an instance with the specified initial balance.
* @param name the <tt>Customer</tt>'s name
* @param money the <tt>Customer</tt>'s initial balance
* @throws BadArgumentException if the <tt>name</tt> is invalid or the <tt>money</tt> is negative
*/
public Customer(String name, int money) throws BadArgumentException
{
super(name);
if(money<0)
throw new BadArgumentException("Money must not be negative");
this.money=money;
}
/**
* Copy constructor.
* Creates a copy of the supplied instance.
* @param existing the instance to clone
*/
public Customer(Customer existing)
{
super(existing);
this.money=existing.money;
}
/**
* Note that <tt>deductMoney(int)</tt> is more appropriate for fulfilling purchases.
* @param money the new balance
* @throws BadArgumentException if a negative value is supplied
*/
public void setMoney(int money) throws BadArgumentException
{
if(money<0)
throw new BadArgumentException("Money must not be negative");
this.money=money;
}
/**
* @return the account balance
*/
public int getMoney()
{
return money;
}
/**
* Deducts the specified amount from the account.
* This amount may be positive, negative, or zero, but must not cause the balance to go negative.
* @param change the value by which to diminish the balance
* @return whether the operation succeeded (i.e. didn't exceed the available funds)
*/
public boolean deductMoney(int change)
{
if(change<=money) //balance wouldn't go negative
{
money-=change;
return true;
}
else
return false;
}
/**
* Indicates whether this customer is a cash customer.
* @return the answer to The Question
*/
public boolean isCashCustomer()
{
try
{
return getId()==CASH_ID;
}
catch(BadStateException noneSet) //ID was unset
{
return false; //not a cash customer
}
}
/**
* Checks whether two instances contain the same data.
* @param another another instance
* @return whether their contents match
*/
@Override
public boolean equals(Object another)
{
if(!(another instanceof Customer))
return false;
Customer other=(Customer)another;
return super.equals(another) && this.money==other.money;
}
/** @inheritDoc */
@Override
public String toString() {
return super.toString() + " " + String.format("%.2f", ((double)money) / 100);
}
}
| bitbanger/hclc_vending_machine | src/Customer.java | 997 | /**
* Note that <tt>deductMoney(int)</tt> is more appropriate for fulfilling purchases.
* @param money the new balance
* @throws BadArgumentException if a negative value is supplied
*/ | block_comment | en | false |
99289_5 | //Problem 1:(https://leetcode.com/problems/design-hashset/) HashSet
// Time Complexity : O(1)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No
// Your code here along with comments explaining your approach: The range of hashset is from 0 to 1000000 so we take bucket as the size of primary array and bucketItems as the size of nested array. We have set the size of the primary array as 1000 by taking a square root of the given range. We create a nested array only when there is a collision.
class MyHashSet {
boolean [][] storage;
int buckets;
int bucketItems;
public MyHashSet() {
this.buckets=1000;
this.bucketItems=1000;
this.storage=new boolean[buckets][];
}
private int hash1(int key)
{
return key%1000;
}
private int hash2(int key)
{
return key/1000;
}
public void add(int key) {
int bucket=hash1(key);
int bucketItem=hash2(key);
if(storage[bucket]==null)
{
if(bucket==0)
{
storage[bucket]=new boolean [bucketItems+1];
}
else
{
storage[bucket]=new boolean [bucketItems];
}
}
storage[bucket][bucketItem]=true;
}
public void remove(int key) {
int bucket=hash1(key);
int bucketItem=hash2(key);
if(storage[bucket]==null) return;
storage[bucket][bucketItem]=false;
}
public boolean contains(int key) {
int bucket=hash1(key);
int bucketItem=hash2(key);
if(storage[bucket]==null) return false;
return storage[bucket][bucketItem];
}
}
/**
* Your MyHashSet object will be instantiated and called as such:
* MyHashSet obj = new MyHashSet();
* obj.add(key);
* obj.remove(key);
* boolean param_3 = obj.contains(key);
*/
// Problem 2: Design MinStack (https://leetcode.com/problems/min-stack/)
// Time Complexity : O(1)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No
// Your code here along with comments explaining your approach : We check if the element coming out of stack is the current minimum, if it is then we update min with the previous minimum. We keep previous minimum as it is until a new minimum is found
class MinStack {
Stack <Integer> st;
int min;
public MinStack() {
this.st=new Stack<>();
this.min=Integer.MAX_VALUE;
}
public void push(int val) {
if(min>=val){
st.push(min);
min=val;
}
st.push(val);
}
public void pop() {
if (st.pop()==min){
min=st.pop();
}
}
public int top() {
return st.peek();
}
public int getMin() {
return min;
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(val);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
| Bency2712/Design-1 | Sample.java | 838 | // Your code here along with comments explaining your approach: The range of hashset is from 0 to 1000000 so we take bucket as the size of primary array and bucketItems as the size of nested array. We have set the size of the primary array as 1000 by taking a square root of the given range. We create a nested array only when there is a collision. | line_comment | en | true |
99293_5 | import java.util.Random;
import java.util.concurrent.locks.*;
import java.util.stream.DoubleStream;
public class Miner extends Builder implements Runnable{
private int ID;
private int interval;
private int storageCapacity;
private int oreType;
private int maxOresCanBeMined;
private int oresInStorage;
private int producedOres;
private boolean isActive;
public Miner(int id, int interval, int storageCapacity, int oreType, int maxOresCanBeMined) {
this.ID = id;
this.interval = interval;
this.storageCapacity = storageCapacity;
this.oreType = oreType;
this.maxOresCanBeMined = maxOresCanBeMined;
this.oresInStorage = 0;
this.producedOres = 0;
this.isActive = true;
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public int getInterval() {
return interval;
}
public void setInterval(int interval) {
this.interval = interval;
}
public int getStorageCapacity() {
return storageCapacity;
}
public void setStorageCapacity(int storageCapacity) {
this.storageCapacity = storageCapacity;
}
public int getOreType() {
return oreType;
}
public void setOreType(int oreType) {
this.oreType = oreType;
}
public int getMaxOresCanBeMined() {
return maxOresCanBeMined;
}
public void setMaxOresCanBeMined(int maxOresCanBeMined) {
this.maxOresCanBeMined = maxOresCanBeMined;
}
@Override
public void run() {
HW2Logger.getInstance().Log(ID, 0, 0, 0, Action.MINER_CREATED);
this.isActive = true;
while (producedOres < maxOresCanBeMined) {
this.WaitCanProduce();
HW2Logger.getInstance().Log(ID, 0, 0, 0, Action.MINER_STARTED);
this.SleepForMining();
this.oresInStorage++;
this.producedOres++;
HW2Logger.getInstance().Log(ID, 0, 0, 0, Action.MINER_FINISHED);
this.OreProduced();
}
this.MinerStopped();
HW2Logger.getInstance().Log(ID, 0, 0, 0, Action.MINER_STOPPED);
}
public void WaitCanProduce() {
while (this.isFull()) {//or if?
this.getLock().lock();
try {
this.getAnItemTakenCondition().await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
this.getLock().unlock();
}
}
}
public void SleepForMining() {
//Sleep a value in range of Interval ± (Interval × 0.01) milliseconds for mining
//duration
Random random = new Random(System.currentTimeMillis());
DoubleStream stream;
stream = random.doubles(1, interval - interval * 0.01, interval + interval * 0.01);
try {
Thread.sleep((long) stream.findFirst().getAsDouble());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void OreProduced() {
this.getLock().lock();
this.getAnItemProduced().signalAll();
this.getLock().unlock();
}
public void MinerStopped() {
this.getLock().lock();
this.isActive = false;
this.getAnItemProduced().signalAll(); //for those transporters waiting the next load.
this.getLock().unlock();
}
public boolean DecreaseOre() {
this.getLock().lock();
if(this.oresInStorage > 0) {
this.oresInStorage--;
this.getLock().unlock();
return true;
}
else{
this.getLock().unlock();
return false;
}
}
@Override
public int OutStorageCount() {
return this.oresInStorage;
}
@Override
public int InStorageCount() { //should not be used
return 0; //does not have ingoing storage. not a subject of any WaitUnload.
}
@Override
public int OutStorageCapacity() {
return this.storageCapacity;
}
@Override
public int InStorageCapacity() {
return 0; //no incoming storage.
}
@Override
public boolean isEmpty() { //
return (oresInStorage==0);
}
@Override
public boolean isFull() { // subject of waitCanProduce.
return oresInStorage == storageCapacity;
}
@Override
public boolean isActive() {
return this.isActive;
}
@Override
public boolean decreaseItem() {
return this.DecreaseOre();
}
@Override
public boolean increaseItem() { // miner has no incoming storage, hence cannot increase it.
return false;
}
@Override
public Type typeOfBuilder() {
return Type.MINER;
}
}
| cenk-arda/Production-Simulation-with-Java | Miner.java | 1,203 | //does not have ingoing storage. not a subject of any WaitUnload. | line_comment | en | true |
99297_21 | package org.fleen.geom_2D;
import java.awt.geom.Point2D;
import java.util.Arrays;
import java.util.List;
/**
* Interpolates points given in the 2D plane. The resulting spline
* is a function s: R -> R^2 with parameter t in [0,1].
*
* this is probably a catmull-rom spline
*
*/
public class DSpline {
/*
* ################################
* CONSTRUCTORS
* ################################
*/
public DSpline(List<? extends DPoint> points) {
int s=points.size();
double[] x=new double[s];
double[] y=new double[s];
for(int i=0;i<s;i++){
x[i]=points.get(i).x;
y[i]=points.get(i).y;}
init(x, y);}
public DSpline(Point2D[] points) {
double[] x=new double[points.length];
double[] y=new double[points.length];
for(int i=0;i<points.length;i++){
x[i]=points[i].getX();
y[i]=points[i].getY();}
init(x, y);}
public DSpline(double[][] points){
double[] x=new double[points.length];
double[] y=new double[points.length];
for(int i=0;i<points.length;i++){
x[i]=points[i][0];
y[i]=points[i][1];}
init(x, y);}
public DSpline(double[] x,double[] y){
init(x,y);}
/*
* ################################
* GEOMETRY
* ################################
*/
/**
* Array representing the relative proportion of the total distance
* of each point in the line ( i.e. first point is 0.0, end point is
* 1.0, a point halfway on line is 0.5 ).
*/
private double[] t;
private Spline splineX;
private Spline splineY;
/**
* Total length tracing the points on the spline
*/
private double length;
private void init(double[] x, double[] y) {
if (x.length != y.length) {
throw new IllegalArgumentException("Arrays must have the same length.");
}
if (x.length < 2) {
throw new IllegalArgumentException("Spline edges must have at least two points.");
}
t = new double[x.length];
t[0] = 0.0; // start point is always 0.0
// Calculate the partial proportions of each section between each set
// of points and the total length of sum of all sections
for (int i = 1; i < t.length; i++) {
double lx = x[i] - x[i-1];
double ly = y[i] - y[i-1];
// If either diff is zero there is no point performing the square root
if ( 0.0 == lx ) {
t[i] = Math.abs(ly);
} else if ( 0.0 == ly ) {
t[i] = Math.abs(lx);
} else {
t[i] = Math.sqrt(lx*lx+ly*ly);
}
length += t[i];
t[i] += t[i-1];
}
for(int i = 1; i< (t.length)-1; i++) {
t[i] = t[i] / length;
}
t[(t.length)-1] = 1.0; // end point is always 1.0
splineX = new Spline(t, x);
splineY = new Spline(t, y);
}
/**
* @param t 0 <= t <= 1
*/
public double[] getPoint(double t) {
double[] result = new double[2];
result[0] = splineX.getValue(t);
result[1] = splineY.getValue(t);
return result;
}
/**
* Used to check the correctness of this spline
*/
public boolean checkValues() {
return (splineX.checkValues() && splineY.checkValues());
}
public double getDx(double t) {
return splineX.getDx(t);
}
public double getDy(double t) {
return splineY.getDx(t);
}
public Spline getSplineX() {
return splineX;
}
public Spline getSplineY() {
return splineY;
}
public double getLength() {
return length;
}
}
/**
* Interpolates given values by B-Splines.
*
*/
class Spline {
private double[] xx;
private double[] yy;
private double[] a;
private double[] b;
private double[] c;
private double[] d;
/** tracks the last index found since that is mostly commonly the next one used */
private int storageIndex = 0;
/**
* Creates a new Spline.
* @param xx
* @param yy
*/
public Spline(double[] xx, double[] yy) {
setValues(xx, yy);
}
/**
* Set values for this Spline.
* @param xx
* @param yy
*/
public void setValues(double[] xx, double[] yy) {
this.xx = xx;
this.yy = yy;
if (xx.length > 1) {
calculateCoefficients();
}
}
/**
* Returns an interpolated value.
* @param x
* @return the interpolated value
*/
public double getValue(double x) {
if (xx.length == 0) {
return Double.NaN;
}
if (xx.length == 1) {
if (xx[0] == x) {
return yy[0];
} else {
return Double.NaN;
}
}
int index = Arrays.binarySearch(xx, x);
if (index > 0) {
return yy[index];
}
index = - (index + 1) - 1;
//TODO linear interpolation or extrapolation
if (index < 0) {
return yy[0];
}
return a[index]
+ b[index] * (x - xx[index])
+ c[index] * Math.pow(x - xx[index], 2)
+ d[index] * Math.pow(x - xx[index], 3);
}
/**
* Returns an interpolated value. To be used when a long sequence of values
* are required in order, but ensure checkValues() is called beforehand to
* ensure the boundary checks from getValue() are made
* @param x
* @return the interpolated value
*/
public double getFastValue(double x) {
// Fast check to see if previous index is still valid
if (storageIndex > -1 && storageIndex < xx.length-1 && x > xx[storageIndex] && x < xx[storageIndex + 1]) {
} else {
int index = Arrays.binarySearch(xx, x);
if (index > 0) {
return yy[index];
}
index = - (index + 1) - 1;
storageIndex = index;
}
//TODO linear interpolation or extrapolation
if (storageIndex < 0) {
return yy[0];
}
double value = x - xx[storageIndex];
return a[storageIndex]
+ b[storageIndex] * value
+ c[storageIndex] * (value * value)
+ d[storageIndex] * (value * value * value);
}
/**
* Used to check the correctness of this spline
*/
public boolean checkValues() {
if (xx.length < 2) {
return false;
} else {
return true;
}
}
/**
* Returns the first derivation at x.
* @param x
* @return the first derivation at x
*/
public double getDx(double x) {
if (xx.length == 0 || xx.length == 1) {
return 0;
}
int index = Arrays.binarySearch(xx, x);
if (index < 0) {
index = - (index + 1) - 1;
}
return b[index]
+ 2 * c[index] * (x - xx[index])
+ 3 * d[index] * Math.pow(x - xx[index], 2);
}
/**
* Calculates the Spline coefficients.
*/
private void calculateCoefficients() {
int N = yy.length;
a = new double[N];
b = new double[N];
c = new double[N];
d = new double[N];
if (N == 2) {
a[0] = yy[0];
b[0] = yy[1] - yy[0];
return;
}
double[] h = new double[N - 1];
for (int i = 0; i < N - 1; i++) {
a[i] = yy[i];
h[i] = xx[i + 1] - xx[i];
// h[i] is used for division later, avoid a NaN
if (h[i] == 0.0) {
h[i] = 0.01;
}
}
a[N - 1] = yy[N - 1];
double[][] A = new double[N - 2][N - 2];
double[] y = new double[N - 2];
for (int i = 0; i < N - 2; i++) {
y[i] =
3
* ((yy[i + 2] - yy[i + 1]) / h[i
+ 1]
- (yy[i + 1] - yy[i]) / h[i]);
A[i][i] = 2 * (h[i] + h[i + 1]);
if (i > 0) {
A[i][i - 1] = h[i];
}
if (i < N - 3) {
A[i][i + 1] = h[i + 1];
}
}
solve(A, y);
for (int i = 0; i < N - 2; i++) {
c[i + 1] = y[i];
b[i] = (a[i + 1] - a[i]) / h[i] - (2 * c[i] + c[i + 1]) / 3 * h[i];
d[i] = (c[i + 1] - c[i]) / (3 * h[i]);
}
b[N - 2] =
(a[N - 1] - a[N - 2]) / h[N
- 2]
- (2 * c[N - 2] + c[N - 1]) / 3 * h[N
- 2];
d[N - 2] = (c[N - 1] - c[N - 2]) / (3 * h[N - 2]);
}
/**
* Solves Ax=b and stores the solution in b.
*/
public void solve(double[][] A, double[] b) {
int n = b.length;
for (int i = 1; i < n; i++) {
A[i][i - 1] = A[i][i - 1] / A[i - 1][i - 1];
A[i][i] = A[i][i] - A[i - 1][i] * A[i][i - 1];
b[i] = b[i] - A[i][i - 1] * b[i - 1];
}
b[n - 1] = b[n - 1] / A[n - 1][n - 1];
for (int i = b.length - 2; i >= 0; i--) {
b[i] = (b[i] - A[i][i + 1] * b[i + 1]) / A[i][i];
}
}
}
| johnalexandergreene/Geom_2D | DSpline.java | 2,833 | /**
* Used to check the correctness of this spline
*/ | block_comment | en | true |
99463_0 | package util;
public final class Constants{
public static final byte PLATFORM_INTEL = 0x01;
public static final byte PLATFORM_POWERPC = 0x02;
public static final byte PLATFORM_MACOSX = 0x03;
public static final byte PRODUCT_STARCRAFT = 0x01;
public static final byte PRODUCT_BROODWAR = 0x02;
public static final byte PRODUCT_WAR2BNE = 0x03;
public static final byte PRODUCT_DIABLO2 = 0x04;
public static final byte PRODUCT_LORDOFDESTRUCTION = 0x05;
public static final byte PRODUCT_JAPANSTARCRAFT = 0x06;
public static final byte PRODUCT_WARCRAFT3 = 0x07;
public static final byte PRODUCT_THEFROZENTHRONE = 0x08;
public static final byte PRODUCT_DIABLO = 0x09;
public static final byte PRODUCT_DIABLOSHAREWARE = 0x0A;
public static final byte PRODUCT_STARCRAFTSHAREWARE= 0x0B;
public static String[] prods = {"STAR", "SEXP", "W2BN", "D2DV", "D2XP", "JSTR", "WAR3", "W3XP", "DRTL", "DSHR", "SSHR"};
public static String[][] IX86files = {
{"IX86/STAR/", "StarCraft.exe", "Storm.dll", "NULL", "STAR.bin"},
{"IX86/STAR/", "StarCraft.exe", "Storm.dll", "NULL", "STAR.bin"},
{"IX86/W2BN/", "Warcraft II BNE.exe", "Storm.dll", "Battle.snp", "W2BN.bin"},
{"IX86/D2DV/", "Game.exe", "NULL", "NULL", "D2DV.bin"},
{"IX86/D2XP/", "Game.exe", "NULL", "NULL", "D2XP.bin"},
{"IX86/JSTR/", "StarcraftJ.exe", "Storm.dll", "Battle.snp", "JSTR.bin"},
{"IX86/WAR3/", "Warcraft III.exe", "NULL", "NULL", "WAR3.bin"},
{"IX86/WAR3/", "Warcraft III.exe", "NULL", "NULL", "WAR3.bin"},
{"IX86/DRTL/", "Diablo.exe", "Storm.dll", "Battle.snp", "DRTL.bin"},
{"IX86/DSHR/", "Diablo_s.exe", "Storm.dll", "Battle.snp", "DSHR.bin"},
{"IX86/SSHR/", "Starcraft.exe", "Storm.dll", "Battle.snp", "SSHR.bin"}
};
public static int[] IX86verbytes = {0xD3, 0xD3, 0x4f, 0x0e, 0x0e, 0xa9, 0x1E, 0x1E, 0x2a, 0x2a, 0xa5};
public static String[] IX86versions = {"", "", "2.0.2.1", "1.14.3.71", "1.14.3.71", "", "", "", "2001, 5, 18, 1", "", ""};
public static String[] IX86certs = {"", "", "", "", "", "", "", "", "", "", ""};
public static String ArchivePath = "DLLs/";
public static String LogFilePath = "./Logs/";
public static String build="Build V3.1 Bug Fixes, SQL Stats tracking. (10-14-07)";
//public static String build="Build V3.0 BotNet Admin, Lockdown, Legacy Clients.(07-07-07)";
//public static String build="Build V2.9 Remote admin, extended admin commands w/ JSTR support.(01/18/06)";
public static int maxThreads=500;
public static int BNLSPort=9367;
public static boolean requireAuthorization=false;
public static boolean trackStatistics=true;
public static int ipAuthStatus=1; //default is IPBans on
public static boolean displayPacketInfo=true;
public static boolean displayParseInfo=false;
public static boolean debugInfo=false;
public static boolean enableLogging = false;
public static int logKeepDuration = 7;
public static boolean RunAdmin = false;
public static String BotNetBotID = "";
public static String BotNetHubPW = "";
public static String BotNetDatabase = "";
public static String BotNetUsername = "";
public static String BotNetPassword = "";
public static String BotNetServer = "www.valhallalegends.com";
public static boolean LogStats = false;
public static String StatsUsername = "";
public static String StatsPassword = "";
public static String StatsDatabase = "";
public static String StatsServer = "localhost";
public static int StatsQueue = 10;
public static boolean StatsLogIps = false;
public static boolean StatsLogCRevs = true;
public static boolean StatsLogBotIDs = true;
public static boolean StatsLogConns = true;
public static boolean StatsCheckSchema = true;
public static String DownloadPath = "./";
public static boolean RunHTTP = true;
public static int HTTPPort = 81;
public static int lngServerVer=0x01;
public static int numOfNews=0;
public static String[] strNews={"", "", "", "", ""};
}
| BNETDocs/JBLS | util/Constants.java | 1,357 | //public static String build="Build V3.0 BotNet Admin, Lockdown, Legacy Clients.(07-07-07)"; | line_comment | en | true |
99632_9 |
import java.io.File;
import java.sql.Connection;
import java.util.Scanner;
import java.text.*;
import java.util.Calendar;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Yunchao
*/
public class Book_Loans {
public static void initiate(Connection conn) {
try{
File file = new File("initialData/book_loans_data_F14.csv");
Scanner input = new Scanner(file);
System.out.println("Does it exist?"+ file.exists());
input.nextLine();
while(input.hasNext()){
String loan_id = input.next();
String book_id = input.next();
String branch_id = input.next();
String card_no = input.next();
String s_date_out = input.next();
String s_due_date = input.next();
String s_date_in = input.next();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date parsed_out = null;
java.util.Date parsed_due = null;
java.util.Date parsed_in = null;
java.sql.Date date_out = null;
java.sql.Date due_date = null;
java.sql.Date date_in = null;
java.util.Date today = Calendar.getInstance().getTime();
double fine=0;
try {
parsed_out = sdf.parse(s_date_out);
parsed_due = sdf.parse(s_due_date);
date_out = new java.sql.Date(parsed_out.getTime());
due_date = new java.sql.Date(parsed_due.getTime());
if(!s_date_in.equals("NULL")){// book not return yet.
// System.out.println(loan_id + ": not null");
parsed_in = sdf.parse(s_date_in);
date_in = new java.sql.Date(parsed_in.getTime());
//System.out.println("insert into book_loans values('" + loan_id + "','" + book_id + "','" + branch_id + "','" + card_no + "','" + date_out +"','" + due_date + "','" + date_in + "'); ");
DBcommander.command("insert into book_loans values('" + loan_id + "','" + book_id + "','" + branch_id + "','" + card_no + "','" + date_out +"','" + due_date + "','" + date_in + "'); ", conn);
//System.out.println();
}
else{
//System.out.println(loan_id + ": null");
//System.out.println("insert into book_loans values('" + loan_id + "','" + book_id + "','" + branch_id + "','" + card_no + "','" + date_out +"','" + due_date + "'); ");
DBcommander.command("insert into book_loans values('" + loan_id + "','" + book_id + "','" + branch_id + "','" + card_no + "','" + date_out +"','" + due_date + "'," + "null); ", conn);
}
System.out.println("loan id:" + loan_id + ",fine:" + fine);
fine = getFine(due_date, date_in, today);
if(fine != 0){
DBcommander.command("insert into fines values('" + loan_id + "','" + fine + "', false);",conn);
}
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//System.out.println("loan_id: " + loan_id + ", book_id: " + book_id + ",branch_id: " + branch_id + ",card_no:" + card_no + ",date_out:" + date_out + ",due_date:"+ due_date + ",date_in:"+ date_in);
//System.out.println("book_id: " + book_id +"' branch_id:" + branch_id + " no_of_copies: " + no_of_copies);
//DBcommander.command("insert into book values('" + book_id + "', 'title');" , conn);
//DBcommander.command("insert into book_loans values('" + loan_id + "','" + book_id + "','" + branch_id + "','" + card_no + "','" + date_out +"','" + due_date + "','" + date_in + "'); ", conn);
//DBcommander.command("insert into book_authors values('" + book_id + "', 'author_name', 'fname', 'minit','lname');" , conn);
}
//ResultSet rs = DBquerier.query("SELECT * FROM employee;", conn);
//String ssn = rs.getString("ssn");
//System.out.println(ssn);
input.close();
}
catch(Exception e){
System.out.println("DB-Error in opening book_loans_data_F14.csv: " + e.getMessage());
}
}
public static double getFine(java.sql.Date due_date, java.sql.Date date_in, java.util.Date today){
double fine = 0;
long dueday_in_diff = 0;
long dueday_today_diff = (due_date.getTime() - today.getTime())/ (24 * 60 * 60 * 1000);
System.out.println("diff:" + dueday_today_diff);
if(dueday_today_diff < 0){//check due book
if(date_in == null){//book not returned yet
fine = -(double)dueday_today_diff * 0.25;
//DBcommander.command("", conn);
System.out.println("fine:" + fine);
}
else{
dueday_in_diff = (due_date.getTime() - date_in.getTime())/ (24 * 60 * 60 * 1000);
System.out.println("book has been returned");
if(dueday_in_diff < 0){// turn in date is later than due_date
fine = -(double)dueday_in_diff * 0.25;
System.out.println("fine:" + fine);
}
}
}
return fine;
}
}
| LanceKnight/Library-Management-System | src/Book_Loans.java | 1,591 | //System.out.println("loan_id: " + loan_id + ", book_id: " + book_id + ",branch_id: " + branch_id + ",card_no:" + card_no + ",date_out:" + date_out + ",due_date:"+ due_date + ",date_in:"+ date_in);
| line_comment | en | true |
100514_0 | import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
public class Commit
{
/*A prerequisite of a commit is that you need a Tree's SHA1 file location. In order to get this you you must...
create a Tree object and save it to the objects folder
(Trees can be blank and have no entries for this part of the code)
A Commit also has a few other entries
String 'summary'
String 'author'
String 'date'
A commit constructor takes an optional String of the SHA1 of a parent Commit, and two Strings for author and summary
A commit contains a method to generate a SHA1 String
The inputs for the SHA1 are the SUBSET OF FILE CONTENTS file:
Summary, Date, Author, Tree, and (possibly null) pointer to parent Commit file
(so all the file contents except line 3)
Has a method getDate()
It gets the date as a String in whatever format you like
Has a method to create a Tree which is used in the constructor
Returns the SHA1 of the Tree*/
String summary, author, date, parent, sha;
File commit;
public Commit (String summary, String author, String date) throws Throwable
{
//commit is stored in the objects folder
//create tree in constructor
Tree tree = new Tree();
tree.addTree("");
sha = tree.getCurrentFileName();
this.author = author;
this.date = date;
this.summary = summary;
parent = tree.getCurrentFileName();
File path = new File ("objects");
path.mkdirs();
FileOutputStream stream = new FileOutputStream(new File(path , "Commit"));
//File commit = new File("Commit");
FileWriter writer - new FileWriter("Commit");
wri
writer.close();
}
public Commit (String summary, String author, String date, String parent) throws Throwable
{
Tree tree = new Tree();
tree.addTree("");
sha = tree.getCurrentFileName();
this.summary = summary;
this.author = author;
this.date = date;
this.parent = parent;
File path = new File ("objects");
path.mkdirs();
FileOutputStream stream = new FileOutputStream(new File(path , "Commit"));
//File commit = new File("Commit");
}
public void generateShaString() throws IOException
{
int line = 1;
String contents = "";
String sha1;
BufferedReader reader = new BufferedReader(new FileReader("Commit"));
while (reader.ready())
{
if (line == 3)
{
reader.readLine();
}
else
{
contents += reader.readLine();
}
line++;
}
reader.close();
try
{
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(contents.getBytes("UTF-8"));
sha1 = byteToHex(crypt.digest());
}
catch(NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch(UnsupportedEncodingException e)
{
e.printStackTrace();
}
//return sha1;
}
private static String byteToHex(final byte[] hash)
{
Formatter formatter = new Formatter();
for (byte b : hash)
{
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}
public String getDate()
{
return date;
}
} | mgober1/BlobAndIndex-MG | Commit.java | 835 | /*A prerequisite of a commit is that you need a Tree's SHA1 file location. In order to get this you you must...
create a Tree object and save it to the objects folder
(Trees can be blank and have no entries for this part of the code)
A Commit also has a few other entries
String 'summary'
String 'author'
String 'date'
A commit constructor takes an optional String of the SHA1 of a parent Commit, and two Strings for author and summary
A commit contains a method to generate a SHA1 String
The inputs for the SHA1 are the SUBSET OF FILE CONTENTS file:
Summary, Date, Author, Tree, and (possibly null) pointer to parent Commit file
(so all the file contents except line 3)
Has a method getDate()
It gets the date as a String in whatever format you like
Has a method to create a Tree which is used in the constructor
Returns the SHA1 of the Tree*/ | block_comment | en | false |
100812_8 | import java.util.List;
/**
* This file is part of the Predator-Prey Simulation.
*
* An PoisonBerry plant present in the simulation.
*
* @author Ubayd Khan (k20044237) and Omar Ahmad (k21052417)
* @version 2022.03.02
*/
public class PoisonBerry extends Plant {
// define fields
private static final double MAX_SIZE = 10.0;
private static final int MAX_AGE = 20;
private static final int BREEDING_AGE = 16;
private static final double LOW_BREEDING_PROBABILITY = 0.104;
private static final double HIGH_BREEDING_PROBABILITY = 0.2;
private static final int MAX_LITTER_SIZE = 3;
private static final double DEFAULT_SIZE = 1.00;
private static final int DEFAULT_FOOD_VALUE = 5;
private static final double DEFAULT_GROWTH_RATE = 1.2;
/**
* Constructor for a plant in the simulation.
*
* @param foodValue The food value of this plant.
* @param size The initial size of this plant.
* @param randomAge Whether the animal should have a random age or not.
* @param field The field in which the plant resides.
* @param location The location in which the plant spawns into.
*/
public PoisonBerry(int foodValue, double size, boolean randomAge, Field field, Location location) {
super(true, foodValue, size, randomAge, field, location);
setGrowthRate(DEFAULT_GROWTH_RATE);
setBreedingProbability(LOW_BREEDING_PROBABILITY);
}
/**
* Getter method for the maximum age of the berry.
*
* @return An integer value representing the maximum age.
*/
@Override
public int getMaxAge() {
return MAX_AGE;
}
/**
* Getter method for the age of breeding of the berry.
*
* @return A double value representing the breeding age.
*/
@Override
public int getBreedingAge() {
return BREEDING_AGE;
}
/**
* Create a new instance of this berry.
* @param field The field in which the spawn will reside in.
* @param location The location in which the spawn will occupy.
* @return A new PoisonBerry instance.
*/
@Override
protected Organism createNewOrganism(Field field, Location location) {
return new PoisonBerry(DEFAULT_FOOD_VALUE, DEFAULT_SIZE, true, field, location);
}
/**
* Abstract method for what the PoisonBerry does, i.e. what is always run at every step.
*
* @param newBerries A list of all newborn berries in this simulation step.
* @param weather The current state of weather in the simulation.
* @param time The current state of time in the simulation.
*/
@Override
public void act(List<Entity> newBerries, Weather weather, TimeOfDay time) {
if (isAlive()) {
setBreedingProbability(LOW_BREEDING_PROBABILITY);
//If it has recently rained or is snowy, grow at a higher growth rate
if (weather.getRecentWeather().contains(WeatherType.RAIN) ||
weather.getRecentWeather().contains(WeatherType.SNOW)){
setBreedingProbability(HIGH_BREEDING_PROBABILITY);
}
grow();
giveBirth(newBerries);
}
}
/**
* Get maximum size of the berry.
*
* @return A double representing maximum size.
*/
@Override
public double getMaxSize() {
return MAX_SIZE;
}
/**
* Getter method for the maximum litter size of the berry's newborns.
*
* @return An integer value representing the maximum allowed litter size.
*/
@Override
public int getMaxLitterSize() {
return MAX_LITTER_SIZE;
}
}
| ubkh/PPA-CW3 | PoisonBerry.java | 952 | /**
* Get maximum size of the berry.
*
* @return A double representing maximum size.
*/ | block_comment | en | false |
100837_0 | import java.time.LocalTime;
import java.util.*;
public class Order
{
List<Pizza> pizzas;
LocalTime time;
String notes;
boolean status;
public Order(List<Pizza>pizzas, LocalTime time, String notes, boolean status)
{
this.pizzas = pizzas;
this.time = time;
this.notes = notes;
this.status = status;
}
public List<Pizza> getPizza()
{
return pizzas;
}
public LocalTime getTime()
{
return time;
}
public String getNotes()
{
return notes;
}
public boolean getStatus()
{
return status;
}
public double getPrice()
{
double sum =0;
for (Pizza pizzas: pizzas)
{
sum+= pizzas.getPrice();
}
return sum;
}
public void setPizzas()
{
this.pizzas = pizzas;
}
public void setTime()
{
this.time = time;
}
public void setNotes()
{
this.notes = notes;
}
public void setStatus(Boolean status)
{
this.status = status;
}
public void toPrint()
{
String statusText = status ? "Færdiggjort" : "Ikke færdig";
for(Pizza pizza: pizzas)
{
pizza.toPrint();
}
System.out.println("Ordren skal være klar til: " +time);
if(!notes.isEmpty())
{
System.out.println("Note: \""+notes+"\"");
}
System.out.println("Status: "+statusText);
}
public String toString()
{
String statusText = status ? "Færdiggjort" : "Ikke færdig";
StringBuilder builder = new StringBuilder();
for(Pizza pizza:pizzas)
{
builder.append(pizza.toString()).append("\n");
}
builder.append("Ordren skal være færdig: ").append(time).append("\n");
builder.append("Status: ").append(statusText);
//String nameTrimmed = name.substring(0,name.length()-1);
return builder.toString();
}
} | Lasse-OT/Pizzaria-tv-rfagligt | Order.java | 597 | //String nameTrimmed = name.substring(0,name.length()-1); | line_comment | en | true |
101542_0 | public class SimpleRNG {
/**
Implementation of a 32-bit 'Xorshift' Random Number Generator,
based on the work of George Marsaglia (www.jstatsoft.org/v08/i14/paper , doi:10.18637/jss.v008.i14)
NOTE: This is _not_ a cryptographically secure random number generator.
Also, be aware that '0' should not be used as a seed, because in this case, the output of the RNG will always be '0'.
Author: Wiebe-Marten Wijnja (Qqwy)
Date: 2018-09-15
Usage instructions:
1. use `rng = new SimpleRNG(luckyNumber)` to seed the RNG to a desired 32-bit unsigned integer.
2. Call `rng.rand()` to get a new random 32-bit unsigned integer.
3. Repeat step (2) as often as you'd like.
Re-seeding can be done using `rng.seed(someOtherNumber)`
Be warned that although the library returns `longs`, the RNG will only ever output values between 0 and 2^32.
*/
private static long max_32bit = (long) 1 << 32;
long rng_state;
public SimpleRNG(long seed) {
this.seed(seed);
}
public long rand() {
long num = this.rng_state;
num ^= (num << 13) % max_32bit;
num ^= (num >> 17) % max_32bit;
num ^= (num << 5) % max_32bit;
this.rng_state = num;
return num;
}
public void seed(long seed) {
this.rng_state = seed;
}
}
| Qqwy/SimpleRNG | java/SimpleRNG.java | 434 | /**
Implementation of a 32-bit 'Xorshift' Random Number Generator,
based on the work of George Marsaglia (www.jstatsoft.org/v08/i14/paper , doi:10.18637/jss.v008.i14)
NOTE: This is _not_ a cryptographically secure random number generator.
Also, be aware that '0' should not be used as a seed, because in this case, the output of the RNG will always be '0'.
Author: Wiebe-Marten Wijnja (Qqwy)
Date: 2018-09-15
Usage instructions:
1. use `rng = new SimpleRNG(luckyNumber)` to seed the RNG to a desired 32-bit unsigned integer.
2. Call `rng.rand()` to get a new random 32-bit unsigned integer.
3. Repeat step (2) as often as you'd like.
Re-seeding can be done using `rng.seed(someOtherNumber)`
Be warned that although the library returns `longs`, the RNG will only ever output values between 0 and 2^32.
*/ | block_comment | en | true |
101589_0 | package com.tgt.igniteplus;
/* program to replace ‘a’ with ‘$’ in the following String
“I am always ready to learn although I do not always like being taught.” */
public class replaceQ20 {
public static void main(String[] args){
String str ="I am always ready to learn although I do not always like being taught";
System.out.println("the initial string is :"+str);
String s=str.replace('a','$');
System.out.println("the replaced string is :"+s);
}
}
/*OUTPUT:
the initial string is :I am always ready to learn although I do not always like being taught
the replaced string is :I $m $lw$ys re$dy to le$rn $lthough I do not $lw$ys like being t$ught
*/ | IgnitePlus2020/javachallenges-ramya | replaceQ20.java | 194 | /* program to replace ‘a’ with ‘$’ in the following String
“I am always ready to learn although I do not always like being taught.” */ | block_comment | en | true |
101614_8 | package AStar;
import java.util.*;
/**
* This is the class for representing a single state of the rush hour puzzle.
* Methods are provided for constructing a state, for accessing information
* about a state, for printing a state, and for expanding a state (i.e.,
* obtaining a list of all states immediately reachable from it).
* <p>
* Every car is constrained to only move horizontally or vertically. Therefore,
* each car has one dimension along which it is fixed, and another dimension
* along which it can be moved. This variable dimension is stored here as part
* of the state. A link to the puzzle with which this state is associated is
* also stored. Note that the goal car is always assigned index 0.
* <p>
* To make it easier to use <tt>State</tt> objects with some of the data
* structures provided as part of the Standard Java Platform, we also have
* provided <tt>hashCode</tt> and <tt>equals</tt> methods. You probably will not
* need to access these methods directly, but they are likely to be used
* implicitly if you take advantage of the Java Platform. These methods define
* two <tt>State</tt> objects to be equal if they refer to the same
* <tt>Puzzle</tt> object, and if they indicate that the cars have the identical
* variable positions in both states. The hashcode is designed to satisfy the
* general contract of the <tt>Object.hashCode</tt> method that it overrides,
* with regard to the redefinition of <tt>equals</tt>.
*/
public class State {
private Puzzle puzzle;
private int varPos[];
/**
* The main constructor for constructing a state. You probably will never
* need to use this constructor.
*
* @param puzzle
* the puzzle that this state is associated with
* @param varPos
* the variable position of each of the cars in this state
*/
public State(Puzzle puzzle, int varPos[]) {
this.puzzle = puzzle;
this.varPos = varPos;
computeHashCode();
}
/** Returns true if and only if this state is a goal state. */
public boolean isGoal() {
return (varPos[0] == puzzle.getGridSize() - 1);
}
/** Returns the variable position of car <tt>v</tt>. */
public int getVariablePosition(int v) {
return varPos[v];
}
/** Returns the puzzle associated with this state. */
public Puzzle getPuzzle() {
return puzzle;
}
/**
* Prints to standard output a primitive text representation of the state.
*/
public void print() {
int grid[][] = getGrid();
int gridsize = puzzle.getGridSize();
System.out.print("+-");
for (int x = 0; x < gridsize; x++) {
System.out.print("--");
}
System.out.println("+");
for (int y = 0; y < gridsize; y++) {
System.out.print("| ");
for (int x = 0; x < gridsize; x++) {
int v = grid[x][y];
if (v < 0) {
System.out.print(". ");
} else {
int size = puzzle.getCarSize(v);
if (puzzle.getCarOrient(v)) {
System.out.print((y == varPos[v] ? "^ " : ((y == varPos[v] + size - 1) ? "v " : "| ")));
} else {
System.out.print(x == varPos[v] ? "< " : ((x == varPos[v] + size - 1) ? "> " : "- "));
}
}
}
System.out.println(
(puzzle.getCarOrient(0) || y != puzzle.getFixedPosition(0)) ? "|" : (isGoal() ? ">" : " "));
}
System.out.print("+-");
for (int x = 0; x < gridsize; x++) {
System.out.print(
(!puzzle.getCarOrient(0) || x != puzzle.getFixedPosition(0)) ? "--" : (isGoal() ? "v-" : " -"));
}
System.out.println("+");
}
/**
* Computes a grid representation of the state. In particular, an nxn
* two-dimensional integer array is computed and returned, where n is the
* size of the puzzle grid. The <tt>(i,j)</tt> element of this grid is equal
* to -1 if square <tt>(i,j)</tt> is unoccupied, and otherwise contains the
* index of the car occupying this square. Note that the grid is recomputed
* each time this method is called.
*/
public int[][] getGrid() {
int gridsize = puzzle.getGridSize();
int grid[][] = new int[gridsize][gridsize];
for (int i = 0; i < gridsize; i++)
for (int j = 0; j < gridsize; j++)
grid[i][j] = -1;
int num_cars = puzzle.getNumCars();
for (int v = 0; v < num_cars; v++) {
boolean orient = puzzle.getCarOrient(v);
int size = puzzle.getCarSize(v);
int fp = puzzle.getFixedPosition(v);
if (v == 0 && varPos[v] + size > gridsize)
size--;
if (orient) {
for (int d = 0; d < size; d++)
grid[fp][varPos[v] + d] = v;
} else {
for (int d = 0; d < size; d++)
grid[varPos[v] + d][fp] = v;
}
}
return grid;
}
/**
* Computes all of the states immediately reachable from this state and
* returns them as an array of states. You probably will not need to use
* this method directly, since ordinarily you will be expanding
* <tt>Node</tt>s, not <tt>State</tt>s.
*/
public State[] expand() {
int gridsize = puzzle.getGridSize();
int grid[][] = getGrid();
int num_cars = puzzle.getNumCars();
ArrayList new_states = new ArrayList();
for (int v = 0; v < num_cars; v++) {
int p = varPos[v];
int fp = puzzle.getFixedPosition(v);
boolean orient = puzzle.getCarOrient(v);
for (int np = p - 1; np >= 0 && (orient ? grid[fp][np] : grid[np][fp]) < 0; np--) {
int[] newVarPos = (int[]) varPos.clone();
newVarPos[v] = np;
new_states.add(new State(puzzle, newVarPos));
}
int carsize = puzzle.getCarSize(v);
for (int np = p + carsize; (np < gridsize && (orient ? grid[fp][np] : grid[np][fp]) < 0)
|| (v == 0 && np == gridsize); np++) {
int[] newVarPos = (int[]) varPos.clone();
newVarPos[v] = np - carsize + 1;
new_states.add(new State(puzzle, newVarPos));
}
}
puzzle.incrementSearchCount(new_states.size());
return (State[]) new_states.toArray(new State[0]);
}
private int hashcode;
private void computeHashCode() {
hashcode = puzzle.hashCode();
for (int i = 0; i < varPos.length; i++)
hashcode = 31 * hashcode + varPos[i];
}
/**
* Returns a hash code value for this <tt>State</tt> object. Although you
* probably will not need to use it directly, this method is provided for
* the benefit of hashtables given in the Java Platform. See documentation
* on <tt>Object.hashCode</tt>, which this method overrides, for the general
* contract that <tt>hashCode</tt> methods must satisfy.
*/
public int hashCode() {
return hashcode;
}
/**
* Returns <tt>true</tt> if and only if this state is considered equal to
* the given object. In particular, equality is defined to hold if the given
* object is also a <tt>State</tt> object, if it is associated with the same
* <tt>Puzzle</tt> object, and if the cars in both states are in the
* identical positions. This method overrides <tt>Object.equals</tt>.
*/
public boolean equals(Object o) {
State s;
try {
s = (State) o;
} catch (ClassCastException e) {
return false;
}
if (hashcode != s.hashcode || !puzzle.equals(s.puzzle))
return false;
for (int i = 0; i < varPos.length; i++)
if (varPos[i] != s.varPos[i])
return false;
return true;
}
}
| saschazar21/rushhour | AStar/State.java | 2,251 | /**
* Returns a hash code value for this <tt>State</tt> object. Although you
* probably will not need to use it directly, this method is provided for
* the benefit of hashtables given in the Java Platform. See documentation
* on <tt>Object.hashCode</tt>, which this method overrides, for the general
* contract that <tt>hashCode</tt> methods must satisfy.
*/ | block_comment | en | false |
101876_0 | package script;
/**
* This enum class represents all genres available
* @author yueyin
*
*/
public enum Genre {
ACTION,ADVENTURE, ANIMATION, COMEDY, CRIME, DRAMA, FAMILY, FANTASY,
FILMNOIR{
public String toString() {
return "FILM-NOIR";
}
}
, HORROR, MUSICAL, MYSTERY, ROMANCE,
SCIFI{
public String toString() {
return "SCI-FI";
}
},SHORT, THRILLER,WAR,WESTERN
}
| cit-upenn/cit-591-fall-2017-project-scriptvisualization | src/script/Genre.java | 155 | /**
* This enum class represents all genres available
* @author yueyin
*
*/ | block_comment | en | true |
102683_0 | package bn.rest;
import com.squareup.moshi.Moshi;
/*
{
"symbol": "BNBBTC",
"id": 28...,
"orderId": 10...,
"orderListId": -1, //Unless OCO, the value will always be -1
"price": "4.00000100",
"qty": "12.00000000",
"quoteQty": "48.000012",
"commission": "10.10000000",
"commissionAsset": "BNB",
"time": 149...,
"isBuyer": true,
"isMaker": false,
"isBestMatch": true
}
*/
public class Trade {
public String symbol, price, qty, quoteQty, commission, commissionAsset;
public long id, orderId, orderListId, time;
public boolean isBuyer, isMaker, isBestMatch;
public String toString() {
return new Moshi.Builder().build().adapter(Trade.class).toJson(this);
}
}
| knoppixmeister/Binance-Candler | src/bn/rest/Trade.java | 289 | /*
{
"symbol": "BNBBTC",
"id": 28...,
"orderId": 10...,
"orderListId": -1, //Unless OCO, the value will always be -1
"price": "4.00000100",
"qty": "12.00000000",
"quoteQty": "48.000012",
"commission": "10.10000000",
"commissionAsset": "BNB",
"time": 149...,
"isBuyer": true,
"isMaker": false,
"isBestMatch": true
}
*/ | block_comment | en | true |
103508_1 | // Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
public final class np
{
public static final class a
{
public static final int slide_in_from_bottom = 0x7f05002f;
public static final int slide_in_from_top = 0x7f050031;
public static final int slide_out_to_bottom = 0x7f05003d;
public static final int slide_out_to_top = 0x7f05003e;
}
public static final class b
{
public static final int header_footer_left_right_padding = 0x7f0c00ba;
public static final int header_footer_top_bottom_padding = 0x7f0c00bb;
public static final int indicator_corner_radius = 0x7f0c00bf;
public static final int indicator_internal_padding = 0x7f0c00c0;
public static final int indicator_right_padding = 0x7f0c00c2;
public static final int pullToRefresh_icon_margin = 0x7f0c0134;
public static final int pullToRefresh_progressbar_height = 0x7f0c0135;
public static final int pullToRefresh_progressbar_width = 0x7f0c0136;
}
public static final class c
{
public static final int arrow_down = 0x7f020052;
public static final int arrow_up = 0x7f020053;
public static final int default_ptr_drawable = 0x7f0201ba;
public static final int default_ptr_flip = 0x7f0201bb;
public static final int default_ptr_rotate = 0x7f0201bc;
public static final int ic_launcher = 0x7f02027c;
public static final int indicator_arrow = 0x7f020322;
public static final int indicator_bg_bottom = 0x7f020323;
public static final int indicator_bg_top = 0x7f020324;
}
public static final class d
{
public static final int both = 0x7f0d0051;
public static final int disabled = 0x7f0d0026;
public static final int fl_inner = 0x7f0d064f;
public static final int flip = 0x7f0d0057;
public static final int gridview = 0x7f0d000c;
public static final int id_tag_index = 0x7f0d000e;
public static final int manualOnly = 0x7f0d0052;
public static final int pullDownFromTop = 0x7f0d0053;
public static final int pullFromEnd = 0x7f0d0054;
public static final int pullFromStart = 0x7f0d0055;
public static final int pullUpFromBottom = 0x7f0d0056;
public static final int pull_to_refresh_image = 0x7f0d064e;
public static final int pull_to_refresh_progress = 0x7f0d0650;
public static final int pull_to_refresh_sub_text = 0x7f0d064d;
public static final int pull_to_refresh_text = 0x7f0d064c;
public static final int rotate = 0x7f0d0058;
public static final int scrollview = 0x7f0d0015;
public static final int selected_view = 0x7f0d0018;
public static final int webview = 0x7f0d0021;
}
public static final class e
{
public static final int pull_to_refresh_header = 0x7f0401aa;
public static final int pull_to_refresh_header_horizontal = 0x7f0401ab;
public static final int pull_to_refresh_header_vertical = 0x7f0401ac;
}
public static final class f
{
public static final int app_name = 0x7f0f002e;
public static final int check_network_no_available_network_message = 0x7f0f0061;
public static final int check_network_no_available_network_title = 0x7f0f0062;
public static final int click_to_refresh_messages = 0x7f0f0067;
public static final int hello = 0x7f0f018c;
public static final int last_update = 0x7f0f021b;
public static final int media_ejected = 0x7f0f022e;
public static final int network_settings = 0x7f0f02b1;
public static final int pull_to_refresh_end_label = 0x7f0f0344;
public static final int pull_to_refresh_from_bottom_end_label = 0x7f0f0345;
public static final int pull_to_refresh_from_bottom_load_label = 0x7f0f0346;
public static final int pull_to_refresh_from_bottom_load_more = 0x7f0f0347;
public static final int pull_to_refresh_from_bottom_pull_label = 0x7f0f0348;
public static final int pull_to_refresh_from_bottom_refreshing_label = 0x7f0f0349;
public static final int pull_to_refresh_from_bottom_release_label = 0x7f0f034a;
public static final int pull_to_refresh_load_label = 0x7f0f034b;
public static final int pull_to_refresh_load_more = 0x7f0f034c;
public static final int pull_to_refresh_new_messages = 0x7f0f034d;
public static final int pull_to_refresh_pull_label = 0x7f0f034e;
public static final int pull_to_refresh_refreshing_label = 0x7f0f034f;
public static final int pull_to_refresh_release_label = 0x7f0f0350;
public static final int set_label_local_albums = 0x7f0f037e;
public static final int switch_off = 0x7f0f042e;
public static final int switch_on = 0x7f0f042f;
public static final int unit_mm = 0x7f0f04e9;
}
public static final class g
{
public static final int PullToRefresh[] = {
0x7f0100e8, 0x7f0100e9, 0x7f0100ea, 0x7f0100eb, 0x7f0100ec, 0x7f0100ed, 0x7f0100ee, 0x7f0100ef, 0x7f0100f0, 0x7f0100f1,
0x7f0100f2, 0x7f0100f3, 0x7f0100f4, 0x7f0100f5, 0x7f0100f6, 0x7f0100f7, 0x7f0100f8, 0x7f0100f9, 0x7f0100fa
};
public static final int PullToRefresh_ptrAdapterViewBackground = 16;
public static final int PullToRefresh_ptrAnimationStyle = 12;
public static final int PullToRefresh_ptrDrawable = 6;
public static final int PullToRefresh_ptrDrawableBottom = 18;
public static final int PullToRefresh_ptrDrawableEnd = 8;
public static final int PullToRefresh_ptrDrawableStart = 7;
public static final int PullToRefresh_ptrDrawableTop = 17;
public static final int PullToRefresh_ptrHeaderBackground = 1;
public static final int PullToRefresh_ptrHeaderSubTextColor = 3;
public static final int PullToRefresh_ptrHeaderTextAppearance = 10;
public static final int PullToRefresh_ptrHeaderTextColor = 2;
public static final int PullToRefresh_ptrListViewExtrasEnabled = 14;
public static final int PullToRefresh_ptrMode = 4;
public static final int PullToRefresh_ptrOverScroll = 9;
public static final int PullToRefresh_ptrRefreshableViewBackground = 0;
public static final int PullToRefresh_ptrRotateDrawableWhilePulling = 15;
public static final int PullToRefresh_ptrScrollingWhileRefreshingEnabled = 13;
public static final int PullToRefresh_ptrShowIndicator = 5;
public static final int PullToRefresh_ptrSubHeaderTextAppearance = 11;
}
}
| gdkjrygh/CompSecurity | alibaba/np.java | 2,332 | // Jad home page: http://www.geocities.com/kpdus/jad.html | line_comment | en | true |
104031_0 | // IM1003 2022-2023 Q1a
/**
* Q1a
*/
public class Q1a {
public static void main(String[] args) {
char[] a1 = {'J','O', 'V', 'I', 'A', 'L'};
char[] a2 = foo(a1);
System.out.println(bar(a2));
}
public static char[] foo(char[] inArr) {
if (inArr.length < 2) throw new IllegalArgumentException();
char[] outArr = new char[inArr.length - 2];
for (int i = 1; i < inArr.length -1; ++i) {
outArr[i - 1] = inArr[i];
System.out.println("i=" + i + ",inArr[i]=" + inArr[i]);
}
return outArr;
}
public static String bar(char[] arr) {
String str = "";
for (int i = arr.length - 1; i >= 0; --i) str += arr[i];
return str;
}
} | raysonoon/java-projects | Q1a.java | 261 | // IM1003 2022-2023 Q1a | line_comment | en | true |
104834_1 | package vendingmachine;
public class CoinSum {
int[] coinValues = {200,100,50,20,10,5,2,1};
int[] coins = new int[8];
public CoinSum(int onep, int twop, int fivep, int tenp, int twentyp, int fiftyp, int onePound, int twoPounds) {
coins[0] = twoPounds;
coins[1] = onePound;
coins[2] = fiftyp;
coins[3] = twentyp;
coins[4] = tenp;
coins[5] = fivep;
coins[6] = twop ;
coins[7] = onep;
}
public CoinSum getSum() {
return this;
}
public Integer getTotalValue() {
Integer total = 0;
for (int i = 0; i < coins.length; i++) {
total += coins[i]*coinValues[i];
}
return total;
}
public CoinSum exchange(int price, int totalReceived) {
CoinSum possibleSum = new CoinSum(0,0,0,0,0,0,0,0);
int amountToReturn = totalReceived - price;
//Specific case where we enter exactly the amount
if (amountToReturn == 0) {
return possibleSum;
}
// We're going to decompose the price in coins to add it to vending machine
for (int i = 0; i < coinValues.length; i++) {
if (amountToReturn > 0){
float division = amountToReturn / coinValues[i];
//The amount due can be returned with this type of coin
if (division >= 1) {
int coinsNeeded = Math.round(division);
// We check the change available has enough coin
if (coinsNeeded <= this.coins[i]){
// We remove the coins that were used
int removeValue = coinsNeeded * coinValues[i];
//If there is enough money
if (amountToReturn >= removeValue){
amountToReturn -= removeValue;
possibleSum.coins[i] = coinsNeeded;
this.coins[i] += coinsNeeded;
}
}
}
}
}
// We haven't decompose the price fully
if (amountToReturn > 0) {
return null;
}
return possibleSum;
}
public String showCoins() {
StringBuilder strCoins = new StringBuilder();
for (int i = 0; i < coinValues.length; i++) {
String coinQuantity = Integer.toString(coins[i]);
float coinValue = (float) coinValues[i]/100 ;
String coinValueStr = String.format("%.02f", coinValue);
strCoins.append( coinQuantity + " of £" + coinValueStr);
strCoins.append("\n");
}
return strCoins.toString();
}
}
| H3ll3m4/Vending-Machine | CoinSum.java | 739 | // We're going to decompose the price in coins to add it to vending machine | line_comment | en | false |
105123_0 | package com.etiaro.facebook;
import android.support.annotation.NonNull;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
/**
* Created by jakub on 21.03.18.
*/
public class Message implements Comparator<Message>, Comparable<Message>{
public String text, senderID, __typename, message_id, offline_threading_id, conversation_id, sender_email;
public int ttl;
public Long timestamp_precise;
public boolean sent = false, delivered = false, unread, is_sponsored; //Delivered and sent are supported not by counstructor
public ArrayList<Attachment> attachments = new ArrayList<>();
public Message(JSONObject json) throws JSONException {
update(json);
}
public void update(JSONObject json) throws JSONException {
if(json.has("irisSeqId")){
text = json.has("body") ?
json.getString("body") : "";
senderID = json.getJSONObject("messageMetadata").getString("actorFbId");
message_id = json.getJSONObject("messageMetadata").getString("messageId");
offline_threading_id = json.getJSONObject("messageMetadata").getString("offlineThreadingId");
if(json.getJSONObject("messageMetadata").getJSONObject("threadKey").has("threadFbId"))
conversation_id = json.getJSONObject("messageMetadata").getJSONObject("threadKey").getString("threadFbId");
else if(json.getJSONObject("messageMetadata").getJSONObject("threadKey").has("otherUserFbId"))
conversation_id = json.getJSONObject("messageMetadata").getJSONObject("threadKey").getString("otherUserFbId");
timestamp_precise = Long.valueOf(json.getJSONObject("messageMetadata").getString("timestamp"));
unread = true;
return;
}
if(!json.has("message_id")) {
text = json.getString("snippet");
senderID = json.getJSONObject("message_sender").getJSONObject("messaging_actor").getString("id");
}else{
if(json.has("__typename"))
__typename = json.getString("__typename");
message_id = json.getString("message_id");
offline_threading_id = json.getString("offline_threading_id"); //???
senderID = json.getJSONObject("message_sender").getString("id");
if(json.getJSONObject("message_sender").has("email"))
sender_email = json.getJSONObject("message_sender").getString("email");
if(json.has("ttl"))
ttl = json.getInt("ttl");
unread = json.getBoolean("unread");
if(json.has("is_sponsored"))
is_sponsored = json.getBoolean("is_sponsored");
if(json.has("message") && json.getJSONObject("message").has("text"))
text = json.getJSONObject("message").getString("text");
}
if(json.has("blob_attachments") && json.getJSONArray("blob_attachments").length() > 0) {
for(int i = 0; i < json.getJSONArray("blob_attachments").length(); i++){
attachments.add(new Attachment(json.getJSONArray("blob_attachments").getJSONObject(i)));
}
}
if(json.has("sent") && json.has("delivered")) {
sent = json.getBoolean("sent");
delivered = json.getBoolean("delivered");
}
timestamp_precise = Long.valueOf(json.getString("timestamp_precise"));
}
public JSONObject toJSON(){
JSONObject obj = null;
try {
obj = new JSONObject().put("message", new JSONObject().put("text", text)).put("senderID", senderID)
.put("__typename", __typename).put("message_sender", new JSONObject()
.put("email", sender_email).put("id", senderID)
.put("messaging_actor", new JSONObject()
.put("id", senderID)))
.put("message_id", message_id)
.put("offline_threading_id", offline_threading_id).put("ttl", ttl)
.put("sent", sent).put("delivered", delivered).put("unread", unread).put("is_sponsored", is_sponsored)
.put("timestamp_precise", timestamp_precise).put("snippet", text)
.put("messageMetadata", new JSONObject().put("threadKey", new JSONObject().put("threadFbId", conversation_id)));
JSONArray arr = new JSONArray();
Iterator<Attachment> it = attachments.iterator();
while(it.hasNext())
arr.put(it.next().toJSON());
obj.put("blob_attachments", arr);
} catch (JSONException e) {
e.printStackTrace();
}
return obj;
}
public String toString(){
return toJSON().toString();
}
@Override
public int compare(Message m1, Message m2) {
return (int)(m1.timestamp_precise - m2.timestamp_precise);
}
@Override
public int compareTo(@NonNull Message msg) {
return (int)(this.timestamp_precise - msg.timestamp_precise);
}
}
/*{
"commerce_message_type":null,
"customizations":[],
"tags_list":[
"source:messenger:web",
"hot_emoji_size:small",
"inbox"
],
"platform_xmd_encoded":null,
"message_source_data":null,
"montage_reply_data":null,
TODO "message_reactions":[], <-------
"message":{"ranges":[]},
"extensible_attachment":null,
"sticker":null,
}*/ | etiaro/facebook-chat | Message.java | 1,306 | /**
* Created by jakub on 21.03.18.
*/ | block_comment | en | false |
105364_0 | /*Write a Java program to create a Package ―SY‖ which has a class SYMarks (members – ComputerTotal,
MathsTotal, and ElectronicsTotal). Create another package TY which has a class TYMarks (members –
Theory, Practicals). Create n objects of Student class (having rollNumber, name, SYMarks and TYMarks).
Add the marks of SY and TY computer subjects and calculate the Grade (‗A‘ for >= 70, ‗B‘ for >= 60 ‗C‘ for
>= 50 , Pass Class for > =40 else ‗FAIL‘) and display the result of the student in proper format. */
public class MainA
{
public static void main(String[] args) {
// Creating SYMarks objects
SYMarks syMarks1 = new SYMarks(80, 75, 85);
SYMarks syMarks2 = new SYMarks(70, 65, 75);
// Creating TYMarks objects
TYMarks tyMarks1 = new TYMarks(85, 90);
TYMarks tyMarks2 = new TYMarks(75, 80);
// Creating Student objects
Student student1 = new Student(1, "John", syMarks1, tyMarks1);
Student student2 = new Student(2, "Alice", syMarks2, tyMarks2);
// Calculating the grades
calculateGrade(student1);
calculateGrade(student2);
// Displaying results
displayResult(student1);
displayResult(student2);
}
public static void calculateGrade(Student student) {
SYMarks syMarks = student.getSyMarks();
TYMarks tyMarks = student.getTyMarks();
int computerTotal = syMarks.getComputerTotal() + tyMarks.getPracticals();
String grade;
if (computerTotal >= 70) {
grade = "A";
} else if (computerTotal >= 60) {
grade = "B";
} else if (computerTotal >= 50) {
grade = "C";
} else if (computerTotal >= 40) {
grade = "Pass Class";
} else {
grade = "FAIL";
}
student.setGrade(grade);
}
public static void displayResult(Student student) {
System.out.println("Roll Number: " + student.getRollNumber());
System.out.println("Name: " + student.getName());
System.out.println("Grade: " + student.getGrade());
System.out.println();
}
}
class Student {
private int rollNumber;
private String name;
private SYMarks syMarks;
private TYMarks tyMarks;
private String grade;
public Student(int rollNumber, String name, SYMarks syMarks, TYMarks tyMarks) {
this.rollNumber = rollNumber;
this.name = name;
this.syMarks = syMarks;
this.tyMarks = tyMarks;
}
// Getters and setters
public int getRollNumber() {
return rollNumber;
}
public void setRollNumber(int rollNumber) {
this.rollNumber = rollNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public SYMarks getSyMarks() {
return syMarks;
}
public void setSyMarks(SYMarks syMarks) {
this.syMarks = syMarks;
}
public TYMarks getTyMarks() {
return tyMarks;
}
public void setTyMarks(TYMarks tyMarks) {
this.tyMarks = tyMarks;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
}
class SYMarks {
private int computerTotal;
private int mathsTotal;
private int electronicsTotal;
public SYMarks(int computerTotal, int mathsTotal, int electronicsTotal) {
this.computerTotal = computerTotal;
this.mathsTotal = mathsTotal;
this.electronicsTotal = electronicsTotal;
}
// Getters and setters
public int getComputerTotal() {
return computerTotal;
}
public void setComputerTotal(int computerTotal) {
this.computerTotal = computerTotal;
}
public int getMathsTotal() {
return mathsTotal;
}
public void setMathsTotal(int mathsTotal) {
this.mathsTotal = mathsTotal;
}
public int getElectronicsTotal() {
return electronicsTotal;
}
public void setElectronicsTotal(int electronicsTotal) {
this.electronicsTotal = electronicsTotal;
}
}
class TYMarks {
private int theory;
private int practicals;
public TYMarks(int theory, int practicals) {
this.theory = theory;
this.practicals = practicals;
}
// Getters and setters
public int getTheory() {
return theory;
}
public void setTheory(int theory) {
this.theory = theory;
}
public int getPracticals() {
return practicals;
}
public void setPracticals(int practicals) {
this.practicals = practicals;
}
}
| sohambhandari4/new-java | ass-2/MainA.java | 1,211 | /*Write a Java program to create a Package ―SY‖ which has a class SYMarks (members – ComputerTotal,
MathsTotal, and ElectronicsTotal). Create another package TY which has a class TYMarks (members –
Theory, Practicals). Create n objects of Student class (having rollNumber, name, SYMarks and TYMarks).
Add the marks of SY and TY computer subjects and calculate the Grade (‗A‘ for >= 70, ‗B‘ for >= 60 ‗C‘ for
>= 50 , Pass Class for > =40 else ‗FAIL‘) and display the result of the student in proper format. */ | block_comment | en | true |
105876_4 | /**
* TVSeries is a subclass of Media. The objects of TVSeries contain information about a TV Series.
* Title, series, episode, publish year, rating, genre can be stored in to the objects.
*
* @author Juha Hirvasniemi <[email protected]>, Tapio Korvala <[email protected]>
* @version 1.0
* @since 2013-12-30
*/
public class TVSeries extends Media {
static final long serialVersionUID = 53L;
String episode;
String season;
private int id;
/**
* Constructor for TVSeries class which can store the information about TV series
* without using any setters.
*
* @param title title for the tv series.
* @param season season name for the series or a number.
* @param episode name of the episode or a number.
* @param publishYear the year the current episode was produced.
* @param rating the rating of the episode, 1-10.
* @param genre the genre for the tv series e.x. Action.
*/
public TVSeries(String title, String season, String episode, int publishYear, int rating, String genre) {
super.increaseId();
this.id = super.getId();
super.setTitle(title);
this.season = season;
this.episode = episode;
super.setPublishYear(publishYear);
super.setRating(rating);
super.setGenre(genre);
}
/**
* Returns id of the created object.
*
* @return id id of the current object.
*/
public int getId() {
return id;
}
/**
* Sets the episode name to the wanted value.
*
* @param episode value to set as episode name.
*/
public void setEpisode(String episode) {
this.episode = episode;
}
/**
* Returns the name of the episode.
*
* @return name of the episode.
*/
public String getEpisode() {
return this.episode;
}
/**
* Sets the name of the season.
*
* @param season value to be set as name of the season.
*/
public void setSeason(String season) {
this.season = season;
}
/**
* Returns the name of the season.
*
* @return name of the season.
*/
public String getSeason() {
return season;
}
public void print() {
System.out.println("-------------");
System.out.println("title: " + getTitle() + ", Series: " + getSeason() + ", Episode: " + getEpisode() + ", PublishYear: " + getPublishYear() + ", Rating: " + getRating() + ", Genre: " + getGenre());
System.out.println("-------------");
}
/**
* Returns all the values of the TV Series as string array.
*
* @return values of tv series.
*/
public String[] getRow() {
String [] row = { Integer.toString(getId()), super.getTitle(), season, episode, Integer.toString(super.getPublishYear()), Integer.toString(super.getRating()), super.getGenre() };
return row;
}
}
| korvatap/MediaCollector | src/TVSeries.java | 813 | /**
* Returns the name of the episode.
*
* @return name of the episode.
*/ | block_comment | en | false |
106210_0 |
/**
* @ClassName: HeldStock
* @Author: Junyang Li
* @Description:
* @Date: Dec 2021
*/
public class HeldStock {
private Stock stock;
private int amount;
private float cost;
public HeldStock(Stock stock, int amount, float cost) {
this.stock = stock;
this.amount = amount;
this.cost = cost;
}
public Stock getStock() {
return this.stock;
}
public int getAmount() {
return this.amount;
}
public int setAmount(int amount) {
return this.amount = amount;
}
public float getCost() {
return this.cost;
}
public void setCost(float cost) {
this.cost = cost;
}
public float getTotalCost() {
return this.cost * this.amount;
}
}
| ohhwhynot/BankATM | HeldStock.java | 204 | /**
* @ClassName: HeldStock
* @Author: Junyang Li
* @Description:
* @Date: Dec 2021
*/ | block_comment | en | true |
107148_0 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Lock here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Lock extends Tile
{
String kleur;
public Lock(String image, int width, int height, String kleur) {
super(image, width, height);
this.kleur = kleur;
}
}
| ROCMondriaanTIN/project-greenfoot-game-BrahimOosterveen | Lock.java | 116 | // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) | line_comment | en | true |
107385_0 | import android.animation.Keyframe;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.os.Build.VERSION;
import android.text.format.Time;
import android.view.View;
public final class aom
{
public static int a(int paramInt)
{
switch (paramInt)
{
default:
throw new IllegalArgumentException("Argument must be between Calendar.SUNDAY and Calendar.SATURDAY");
case 1:
return 0;
case 2:
return 1;
case 3:
return 2;
case 4:
return 3;
case 5:
return 4;
case 6:
return 5;
}
return 6;
}
public static int a(int paramInt1, int paramInt2)
{
switch (paramInt1)
{
default:
throw new IllegalArgumentException("Invalid Month");
case 0:
case 2:
case 4:
case 6:
case 7:
case 9:
case 11:
return 31;
case 3:
case 5:
case 8:
case 10:
return 30;
}
if (paramInt2 % 4 == 0) {
return 29;
}
return 28;
}
public static ObjectAnimator a(View paramView, float paramFloat1, float paramFloat2)
{
Keyframe localKeyframe1 = Keyframe.ofFloat(0.0F, 1.0F);
Keyframe localKeyframe2 = Keyframe.ofFloat(0.275F, paramFloat1);
Keyframe localKeyframe3 = Keyframe.ofFloat(0.69F, paramFloat2);
Keyframe localKeyframe4 = Keyframe.ofFloat(1.0F, 1.0F);
paramView = ObjectAnimator.ofPropertyValuesHolder(paramView, new PropertyValuesHolder[] { PropertyValuesHolder.ofKeyframe("scaleX", new Keyframe[] { localKeyframe1, localKeyframe2, localKeyframe3, localKeyframe4 }), PropertyValuesHolder.ofKeyframe("scaleY", new Keyframe[] { localKeyframe1, localKeyframe2, localKeyframe3, localKeyframe4 }) });
paramView.setDuration(544L);
return paramView;
}
public static void a(View paramView, CharSequence paramCharSequence)
{
if ((paramView != null) && (paramCharSequence != null)) {
paramView.announceForAccessibility(paramCharSequence);
}
}
public static boolean a()
{
return Build.VERSION.SDK_INT >= 21;
}
public static int b(int paramInt1, int paramInt2)
{
int i = 4 - paramInt2;
paramInt2 = i;
if (i < 0) {
paramInt2 = i + 7;
}
paramInt1 = (paramInt1 - (2440588 - paramInt2)) / 7;
Time localTime = new Time("UTC");
localTime.setJulianDay(paramInt1 * 7 + 2440585);
return localTime.getWeekNumber();
}
}
/* Location:
* Qualified Name: aom
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | reverseengineeringer/com.google.android.gm | src/aom.java | 783 | /* Location:
* Qualified Name: aom
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | block_comment | en | true |
107659_0 | /*
* Solution to Project Euler problem 205
* Copyright (c) Project Nayuki. All rights reserved.
*
* https://www.nayuki.io/page/project-euler-solutions
* https://github.com/nayuki/Project-Euler-solutions
*/
public final class p205 implements EulerSolution {
public static void main(String[] args) {
System.out.println(new p205().run());
}
private static final int[] PYRAMIDAL_DIE_PDF = {0, 1, 1, 1, 1};
private static final int[] CUBIC_DIE_PDF = {0, 1, 1, 1, 1, 1, 1};
public String run() {
int[] ninePyramidalPdf = {1};
for (int i = 0; i < 9; i++)
ninePyramidalPdf = convolve(ninePyramidalPdf, PYRAMIDAL_DIE_PDF);
int[] sixCubicPdf = {1};
for (int i = 0; i < 6; i++)
sixCubicPdf = convolve(sixCubicPdf, CUBIC_DIE_PDF);
long count = 0;
for (int i = 0; i < ninePyramidalPdf.length; i++)
count += (long)ninePyramidalPdf[i] * sum(sixCubicPdf, 0, i);
return String.format("%.7f", count / Math.pow(4, 9) / Math.pow(6, 6));
}
private static int[] convolve(int[] a, int[] b) {
int[] c = new int[a.length + b.length - 1];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b.length; j++)
c[i + j] += a[i] * b[j];
}
return c;
}
private static int sum(int[] array, int from, int to) {
int sum = 0;
for (int i = from; i < to; i++)
sum += array[i];
return sum;
}
}
| Rekhaaravind/Project-Euler-solutions | java/p205.java | 554 | /*
* Solution to Project Euler problem 205
* Copyright (c) Project Nayuki. All rights reserved.
*
* https://www.nayuki.io/page/project-euler-solutions
* https://github.com/nayuki/Project-Euler-solutions
*/ | block_comment | en | true |
108330_0 | package OOP1;
public interface BB {
/*
* no method body only method declaration.
* not static method;
* variable by default static.
* can not create and object of an interface.
* No costrutor;
* 100% abstraction can be achieve.
*
*/
int branch = 5;
public void credit();
public void loan();
public void mortgage();
public void can_not_cell_doller();
public void can_accept_russian_rubel();
}
| sourovbm21/TestingBEEJulySession | src/main/java/OOP1/BB.java | 136 | /*
* no method body only method declaration.
* not static method;
* variable by default static.
* can not create and object of an interface.
* No costrutor;
* 100% abstraction can be achieve.
*
*/ | block_comment | en | true |
108366_12 | /**
* Tiles Class
* Author: Cody Thompson
*
* Contains all the methods to represent the Board Tiles
*/
package model;
public class Tiles {
private int cost;
private int rent;
private int numHouses;
private boolean hasHotel;
private int mortgage;
private String name;
private boolean mortgaged;
private Colors color;
private Player owner;
private boolean owned;
/**
* Tiles constructor
* @param name name of tile
* @param cost cost of tile
* @param rent rent for tile
* @param mortgage mortgage for tile
*/
public Tiles(String name, int cost, int rent, int mortgage, Colors color){
this.name = name;
this.cost = cost;
this.rent = rent;
this.mortgage = mortgage;
this.numHouses = 0;
this.hasHotel = false;
this.mortgaged = false;
this.color = color;
this.owner = null;
}
/**
* Gets the cost of the tile
* @return cost
*/
public int getCost(){
return this.cost;
}
/**
* Gets the rent for the tile
* @return rent
*/
public int getRent(){
return this.rent;
}
/**
* Sets the new rent amount (based on numHouses)
* @param newRentAmount
*/
public void setRent(int newRentAmount){
this.rent = newRentAmount;
}
/**
* Checks to see if the tile has a hotel
* @return true if yes or false if no
*/
public boolean hasHotel(){
return this.hasHotel;
}
/**
* Sets tiles status to has a hotel
* @param hasHotel
*/
public void setHotel(boolean hasHotel){
this.hasHotel = hasHotel;
}
/**
* Gets number of houses the tile has
* @return numHouses
*/
public int getNumHouses(){
return this.numHouses;
}
/**
* Sets the number of houses the tile has
* @param numHouses the number of houses
*/
public void setNumHouses(int numHouses){
this.numHouses = numHouses;
}
/**
* Gets the mortgage amount for the tile
* @return mortgage
*/
public int getMortgage(){
return this.mortgage;
}
/**
* Gets the name of the tile
* @return name
*/
public String getName(){
return this.name;
}
/**
* Checks to see if the tile has been mortgaged
* @return true if yes or false if no
*/
public boolean mortgaged(){
return this.mortgaged;
}
/**
* Sets the tiles status to mortgaged or not mortgaged
* @param mortgaged true or false
*/
public void setMortgage(boolean mortgaged){
this.mortgaged = mortgaged;
}
/**
* Gets the color of the tile
* @return color
*/
public Colors getColor(){
return this.color;
}
/**
* Sets an owner to the tile
* @param owner
*/
public void setOwner(Player owner){
this.owner = owner;
this.owned = true;
}
/**
* Gets the owner of the Tile
* @return
*/
public Player getOwner(){
return this.owner;
}
/**
* Checks to see if the tile is owned already or not
* @return
*/
public boolean owned(){
return this.owned;
}
/**
* Checks to see if a tile is equal to another
*/
@Override
public boolean equals(Object obj) {
boolean result = false;
if(obj instanceof Tiles){
Tiles tile = (Tiles) obj;
if(this.name.equals(tile.name)){
result = true;
}
}
return result;
}
/**
* String representation of a tile
*/
@Override
public String toString() {
return super.toString();
}
} | cat7137/Monopoly | src/model/Tiles.java | 934 | /**
* Sets the tiles status to mortgaged or not mortgaged
* @param mortgaged true or false
*/ | block_comment | en | true |
108398_0 | package com.redhat.bpms.examples.mortgage;
/**
* This class was automatically generated by the data modeler tool.
*/
@javax.persistence.Entity
public class Application implements java.io.Serializable
{
static final long serialVersionUID = 1L;
@javax.persistence.GeneratedValue(strategy = javax.persistence.GenerationType.AUTO, generator = "APPLICATION_ID_GENERATOR")
@javax.persistence.Id
@javax.persistence.SequenceGenerator(sequenceName = "APPLICATION_ID_SEQ", name = "APPLICATION_ID_GENERATOR")
private Long id;
@javax.persistence.ManyToOne(cascade = { javax.persistence.CascadeType.ALL }, fetch = javax.persistence.FetchType.EAGER)
@org.kie.api.definition.type.Label(value = "Applicant")
private com.redhat.bpms.examples.mortgage.Applicant applicant;
@javax.persistence.ManyToOne(cascade = { javax.persistence.CascadeType.ALL }, fetch = javax.persistence.FetchType.EAGER)
@org.kie.api.definition.type.Label(value = "Property")
private com.redhat.bpms.examples.mortgage.Property property;
@javax.persistence.ManyToOne(cascade = { javax.persistence.CascadeType.ALL }, fetch = javax.persistence.FetchType.EAGER)
@org.kie.api.definition.type.Label(value = "Appraisal")
private com.redhat.bpms.examples.mortgage.Appraisal appraisal;
@org.kie.api.definition.type.Label(value = "Down Payment")
private Integer downPayment;
@org.kie.api.definition.type.Label(value = "Mortgage Amortization")
private Integer amortization;
@org.kie.api.definition.type.Label(value = "Mortgage Amount")
private Integer mortgageAmount;
@org.kie.api.definition.type.Label(value = "Mortgage Interest APR")
private Double apr;
@javax.persistence.OneToMany(cascade = { javax.persistence.CascadeType.ALL }, fetch = javax.persistence.FetchType.EAGER)
@org.kie.api.definition.type.Label(value = "Validation Errors")
private java.util.List<com.redhat.bpms.examples.mortgage.ValidationError> validationErrors;
public Application()
{
}
public Long getId()
{
return this.id;
}
public void setId(Long id)
{
this.id = id;
}
public com.redhat.bpms.examples.mortgage.Applicant getApplicant()
{
return this.applicant;
}
public void setApplicant(
com.redhat.bpms.examples.mortgage.Applicant applicant)
{
this.applicant = applicant;
}
public com.redhat.bpms.examples.mortgage.Property getProperty()
{
return this.property;
}
public void setProperty(com.redhat.bpms.examples.mortgage.Property property)
{
this.property = property;
}
public com.redhat.bpms.examples.mortgage.Appraisal getAppraisal()
{
return this.appraisal;
}
public void setAppraisal(
com.redhat.bpms.examples.mortgage.Appraisal appraisal)
{
this.appraisal = appraisal;
}
public Integer getDownPayment()
{
return this.downPayment;
}
public void setDownPayment(Integer downPayment)
{
this.downPayment = downPayment;
}
public Integer getAmortization()
{
return this.amortization;
}
public void setAmortization(Integer amortization)
{
this.amortization = amortization;
}
public Integer getMortgageAmount()
{
return this.mortgageAmount;
}
public void setMortgageAmount(Integer mortgageAmount)
{
this.mortgageAmount = mortgageAmount;
}
public Double getApr()
{
return this.apr;
}
public void setApr(Double apr)
{
this.apr = apr;
}
public java.util.List<com.redhat.bpms.examples.mortgage.ValidationError> getValidationErrors()
{
return this.validationErrors;
}
public void setValidationErrors(
java.util.List<com.redhat.bpms.examples.mortgage.ValidationError> validationErrors)
{
this.validationErrors = validationErrors;
}
public Application(
Long id,
com.redhat.bpms.examples.mortgage.Applicant applicant,
com.redhat.bpms.examples.mortgage.Property property,
com.redhat.bpms.examples.mortgage.Appraisal appraisal,
Integer downPayment,
Integer amortization,
Integer mortgageAmount,
Double apr,
java.util.List<com.redhat.bpms.examples.mortgage.ValidationError> validationErrors)
{
this.id = id;
this.applicant = applicant;
this.property = property;
this.appraisal = appraisal;
this.downPayment = downPayment;
this.amortization = amortization;
this.mortgageAmount = mortgageAmount;
this.apr = apr;
this.validationErrors = validationErrors;
}
} | RHsyseng/BPMS-OCP | ocp-mortgage-rules/src/main/java/com/redhat/bpms/examples/mortgage/Application.java | 1,248 | /**
* This class was automatically generated by the data modeler tool.
*/ | block_comment | en | true |
108472_0 | /*
Vertex class for Euclid 21 program. Holds all information for a visible vertex.
Copyright (C) 2014 Mary Boman
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 java.util.*;
import java.lang.*;
import java.io.*;
//Class holds all the information for a visible vertex.
//The actual vertex will be drawn by a display class that extends JComponent.
public class Vertex
{
private int x = 0;
private int y = 0;
private String name;
private Node node;
public boolean clicked = false;
private ArrayList<Edge> edgeList;
public Vertex(Node n)
{
node = n;
name = node.getBookNum() + "." + node.getPropNum();
edgeList = new ArrayList<Edge>();
}
public Node getNode()
{
return node;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public void setX(int newX)
{
x = newX;
}
public void setY(int newY)
{
y = newY;
}
public void setCoordinates(int newX, int newY)
{
x = newX;
y = newY;
}
public String getName()
{
return name;
}
public String toString()
{
return node.toString();
}
public void addEdge(Edge e)
{
edgeList.add(e);
}
public ArrayList<Edge> getEdges()
{
return edgeList;
}
}
| neilpa/Euclid21 | Vertex.java | 557 | /*
Vertex class for Euclid 21 program. Holds all information for a visible vertex.
Copyright (C) 2014 Mary Boman
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/>.
*/ | block_comment | en | true |
108561_0 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
public class Silver extends Mover {
public Silver() {
GreenfootImage image = getImage();
image.scale(image.getWidth() + 10, image.getHeight() + 10);
setImage(image);
}
public void act() {
}
}
| ROCMondriaanTIN/project-greenfoot-game-Velarion | Silver.java | 86 | // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) | line_comment | en | true |
108779_0 | import java.io.*;
import java.util.*;
public class GetIndex {
public static void main(String [] args) throws IOException{
Scanner initialScan;
ArrayList<String> tokens = new ArrayList<String>();
String wordToken = "";
if (args.length == 0 || args.length < 2 || args.length > 3) {
System.out.println("Enter the sbv.txt, srt.txt, or vtt.txt file for which you wish to scan through.");
System.out.println("Then enter what the type of the file is: either it is sbv, srt, or vtt");
System.out.println("OPTIONAL Enter a fileWithWords.txt or some file that contains a list of words that you wish to scan through");
System.exit(1);
}
if (args.length == 3) { // if a file with just words to find, each word seperated with a new line was given
try {
File fileWithWords = new File(args[2]);
initialScan = new Scanner(fileWithWords);
while(initialScan.hasNextLine()) {
wordToken = initialScan.nextLine();
wordToken = wordToken.toLowerCase();
tokens.add(wordToken);
}
}
catch (FileNotFoundException e) {
System.out.println("File not Found");
}
}
else {
Scanner console = new Scanner(System.in);
System.out.println();
System.out.println();
System.out.println("Enter all words you wish to find.");
System.out.println("Type IAMDONE if you are finished with adding words.");
System.out.println();
String userInput = "";
while(!(userInput.equals("IAMDONE"))) {
if (userInput.equals("IAMDONE")) {
}
else {
userInput = console.nextLine();
tokens.add(userInput);
}
}
}
String info = "";
String info2 = "";
String timeStamp = "";
String testWord = "";
String line = "";
int bmSearch = 0;
BoyerMoore bm = new BoyerMoore();
ArrayList<String> listOfTimeStamps = new ArrayList<String>();
File f = new File(args[0]); // get the fileName
Scanner scan; // scan through file
System.out.println();
System.out.println();
System.out.println("This is your index");
System.out.println();
for (int i = 0; i < tokens.size(); i++) {
scan = new Scanner(f); // reset the scanner's position to the top of file.
testWord = tokens.get(i); // patternToSearch = testWord
if (args[1].equals("sbv")) {
listOfTimeStamps = scanSBV(info, info2, timeStamp, testWord, line, bmSearch, bm, listOfTimeStamps, scan);
}
else if (args[1].equals("srt")) {
listOfTimeStamps = scanSRT(info, info2, timeStamp, testWord, line, bmSearch, bm, listOfTimeStamps, scan);
}
else if (args[1].equals("vtt")) {
listOfTimeStamps = scanVTT(info, info2, timeStamp, testWord, line, bmSearch, bm, listOfTimeStamps, scan, f);
}
showIndex(listOfTimeStamps, testWord);
testWord="";
listOfTimeStamps.clear();
}
}
public static ArrayList<String> scanVTT(String info, String info2, String timeStamp, String testWord,
String line, int bmSearch, BoyerMoore bm,
ArrayList<String> listOfTimeStamps, Scanner scan, File f)
{
testWord = testWord.toLowerCase();
// Check to see if the WEBVTT three lines are on top.
// If so, skip through them, then do normal scanning.
// otherwise, just do normal scanning.
String checkWebVTT = scan.nextLine();
if (checkWebVTT.equals("WEBVTT")) {
scan.nextLine(); // kind: captions
scan.nextLine(); // language: end
scan.nextLine(); // new line space
}
else {
try{
scan = new Scanner(f);
}
catch(FileNotFoundException e) {
System.out.println("Error");
System.exit(0);
}
}
while(scan.hasNextLine()) {
timeStamp = scan.nextLine();
timeStamp = timeStamp.replaceAll(" -->", ","); // replaces all arrows with commas to keep consistency
info = scan.nextLine();
line = info.replaceAll("[\\p{Punct}]", "");
line = line.toLowerCase(); // text = line
bmSearch = bm.findPattern(line, testWord);
if (bmSearch == 1) {
// then match this word that is found with its timestamp.
listOfTimeStamps.add(timeStamp);
}
if (scan.hasNextLine()) {
info2 = scan.nextLine();
}
// want to check if info2 is a whitespace,
// or more words
// if its a whitespace, move on
// if its more words, then run the check for tokens loop again
if (info2.matches("[0-9]+") == false && info2.length() > 0) {
line = info2.replaceAll("[\\p{Punct}]", "");
//line = line.replaceAll("\\s","");
line = line.toLowerCase();
bmSearch = bm.findPattern(line, testWord);
if (bmSearch == 1) {
// then match this word that is found with its timestamp.
listOfTimeStamps.add(timeStamp);
}
if (scan.hasNextLine()) {
scan.nextLine();
}
}
} // end of searching through file
return listOfTimeStamps;
}
public static ArrayList<String> scanSRT(String info, String info2, String timeStamp, String testWord,
String line, int bmSearch, BoyerMoore bm,
ArrayList<String> listOfTimeStamps, Scanner scan)
{
String skipInt = "";
testWord = testWord.toLowerCase();
while(scan.hasNextLine()) {
skipInt = scan.nextLine();
timeStamp = scan.nextLine();
timeStamp = timeStamp.replaceAll(" -->", ","); // replaces all arrows with commas to keep consistency
info = scan.nextLine();
line = info.replaceAll("[\\p{Punct}]", "");
//line = line.replaceAll("\\s","");
line = line.toLowerCase(); // text = line
bmSearch = bm.findPattern(line, testWord);
if (bmSearch == 1) {
// then match this word that is found with its timestamp.
listOfTimeStamps.add(timeStamp);
}
if (scan.hasNextLine()) {
info2 = scan.nextLine();
}
// want to check if info2 is a whitespace,
// or more words
// if its a whitespace, move on
// if its more words, then run the check for tokens loop again
if (info2.matches("[0-9]+") == false && info2.length() > 0) {
line = info2.replaceAll("[\\p{Punct}]", "");
//line = line.replaceAll("\\s","");
line = line.toLowerCase();
bmSearch = bm.findPattern(line, testWord);
if (bmSearch == 1) {
// then match this word that is found with its timestamp.
listOfTimeStamps.add(timeStamp);
}
if (scan.hasNextLine()) {
scan.nextLine();
}
}
} // end of searching through file
return listOfTimeStamps;
}
public static ArrayList<String> scanSBV(String info, String info2, String timeStamp, String testWord,
String line, int bmSearch, BoyerMoore bm,
ArrayList<String> listOfTimeStamps, Scanner scan)
{
testWord = testWord.toLowerCase();
while(scan.hasNextLine()) {
timeStamp = scan.nextLine();
info = scan.nextLine();
line = info.replaceAll("[\\p{Punct}]", "");
//line = line.replaceAll("\\s","");
line = line.toLowerCase(); // text = line
bmSearch = bm.findPattern(line, testWord);
if (bmSearch == 1) {
// then match this word that is found with its timestamp.
listOfTimeStamps.add(timeStamp);
}
if (scan.hasNextLine()) {
info2 = scan.nextLine();
}
// want to check if info2 is a whitespace,
// or more words
// if its a whitespace, move on
// if its more words, then run the check for tokens loop again
if (info2.matches("[0-9]+") == false && info2.length() > 0) {
line = info2.replaceAll("[\\p{Punct}]", "");
//line = line.replaceAll("\\s","");
line = line.toLowerCase();
bmSearch = bm.findPattern(line, testWord);
if (bmSearch == 1) {
// then match this word that is found with its timestamp.
listOfTimeStamps.add(timeStamp);
}
if (scan.hasNextLine()) {
scan.nextLine();
}
}
} // end of searching through file
return listOfTimeStamps;
}
public static void showIndex(ArrayList<String> listOfTimeStamps, String testWord) {
// print index to console
if (listOfTimeStamps.size() == 1) {
System.out.print(testWord + ": " + "(" + listOfTimeStamps.get(0) + ")");
System.out.println();
}
else {
System.out.print(testWord + ": ");
for (int j = 0; j < listOfTimeStamps.size(); j++) {
System.out.print("(" + listOfTimeStamps.get(j) + ")" + ", ");
}
System.out.println();
}
}
}
| CMU-CREATE-Lab/Video-File-Index-Automator | GetIndex.java | 2,247 | // if a file with just words to find, each word seperated with a new line was given | line_comment | en | false |
109057_15 | public abstract class Rabbit
{
enum Gender
{
MALE,
FEMALE
}
protected int age; // En mois
protected final int sexualMaturityAge; // En mois
protected boolean isDead;
/**
* Constructeur de la classe Rabbit
*/
public Rabbit ()
{
this.age = 0;
this.sexualMaturityAge = (int) MersenneTwister.uniform(5, 9); // [5, 6, 7, 8]
this.isDead = false;
this.potentialDeath();
}
/**
* Autre constructeur pour la classe Rabbit
*
* @param age Âge du lapin
* @param sexualMaturityAge Âge de maturité sexuelle du lapin
*/
public Rabbit (int age, int sexualMaturityAge)
{
this.age = age;
this.sexualMaturityAge = sexualMaturityAge;
this.isDead = false;
this.potentialDeath();
}
/**
* Retourne le genre du lapin.
*
* @return Le genre du lapin
*/
public abstract Gender getGender ();
/**
* Retourne si le lapin est mort ou non.
*
* @return Si le lapin est mort : <b>true</b>
* Sinon : <b>false</b>
*/
public boolean isDead () {
return this.isDead;
}
/**
* Retourne si le lapin est mature sexuellement ou non.
*
* @return Si le lapin est mature sexuellement : true
* Sinon : false
*/
public boolean isSexuallyMature ()
{
return (this.age >= this.sexualMaturityAge);
}
/**
* Ajoute un mois au lapin et déclenche les fonctions mensuelles.
*/
public void newMonth ()
{
this.age++;
// Tirage pour savoir si le lapin meurt ou non
this.potentialDeath();
}
/**
* Appelle ou non la méthode de mort du lapin selon les probabilitées définies.
*/
private void potentialDeath ()
{
double randomNb = MersenneTwister.genrand_real1();
if (! this.isSexuallyMature())
{
// Non mature sexuellement
if (randomNb > Math.pow(0.5, (1 / 12.0)))
{
this.kill();
}
}
else if ((this.age / 12) < 7)
{
// Moins de 7 ans et mature sexuellement
if (randomNb > Math.pow(0.75, (1 / 12.0)))
{
this.kill();
}
}
else
{
// 7 ans ou plus
// Calcul de la probabilité de survie selon l'âge du lapin
double survivalProbability = ((float)((75 - (15 * ((this.age / 12) - 7)))) / 100);
// Si la probabilité de mourir est de 100% alors le lapin meurt
// Sinon, on effectue un tirage avec la probabilité calculée
if (survivalProbability == 0) {
this.kill();
}
else if (randomNb > Math.pow(survivalProbability, (1 / 12.0)))
{
this.kill();
}
}
}
/**
* Fait mourir le lapin.
*/
protected void kill ()
{
this.isDead = true;
}
}
| markblre/rabbit-population-simulation | src/Rabbit.java | 857 | // Si la probabilité de mourir est de 100% alors le lapin meurt | line_comment | en | true |
109637_0 | public class Backpack {
private Pencil pencil;
private Ruler ruler;
private Textbook textbook;
Backpack(){
System.out.println("Nice Backpack");
}
public static void main (String[] args){
/* Your mission is to get to school, but first you need to get all of your supplies into your backpack. */
Pencil pencil=new Pencil();
Ruler ruler=new Ruler();
Textbook book=new Textbook();
Backpack backpack=new Backpack();
backpack.putInBackpack(pencil);
backpack.putInBackpack(ruler);
backpack.putInBackpack(book);
backpack.goToSchool();
}
public void putInBackpack(Supply supply){
if (supply instanceof Pencil){
this.pencil = (Pencil) supply;
System.out.println("You put your pencil in your Backpack");
}else if(supply instanceof Ruler){
this.ruler = (Ruler) supply;
System.out.println("You put your ruler in your Backpack");
}else if(supply instanceof Textbook){
this.textbook = (Textbook) supply;
System.out.println("You put your textbook in your Backpack");
}else{
System.out.println("That isn't a valid school supply");
}
}
public void goToSchool(){
if(pencil == null || ruler == null || textbook == null){
System.err.println("You are not ready for School");
}else{
System.out.println("Congratulations! You are ready for school");
}
}
}
class Supply {
protected String name;
}
class Pencil extends Supply {
Pencil(){
this.name = "pencil";
System.out.println("You got your pencil!");
}
public void write(String writing){
System.out.println(writing);
}
}
class Ruler extends Supply {
Ruler(){
this.name = "ruler";
System.out.println("You found your ruler!!");
}
public void measure(){
System.out.println("Now you can measure your mouse!");
}
}
class Textbook extends Supply{
Textbook(){
this.name = "textbook";
System.out.println("You got your boring textbook");
}
public void read(){
System.out.println("The history of Iceland is long and interesting");
}
}
| cheetah676/level-1 | src/Backpack.java | 626 | /* Your mission is to get to school, but first you need to get all of your supplies into your backpack. */ | block_comment | en | true |
109883_0 |
/**
* This class allows me to store key-value pairs within a single object, so that I can access the key of a certain
* value without looking in the hash table
*
*/
public class kvPair<KeyType, ValueType> {
private KeyType key;
private ValueType value;
public kvPair(KeyType key, ValueType value) {
this.key = key;
this.value = value;
}
protected ValueType getValue() {
return this.value;
}
protected KeyType getKey() {
return this.key;
}
}
| cyschlueter/ShowSearcherApp | kvPair.java | 133 | /**
* This class allows me to store key-value pairs within a single object, so that I can access the key of a certain
* value without looking in the hash table
*
*/ | block_comment | en | true |
110275_0 | import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
try (Scanner sc = new Scanner(System.in)) {
String line = sc.nextLine();
String lower = line.toLowerCase();
lower = lower.replace(" ", "");
Set<Character> chars = new HashSet<Character>();
for (int i = 0; i < lower.length(); ++i) {
chars.add(lower.charAt(i));
}
if (chars.size() != 26) {
System.out.print("not ");
}
System.out.println("pangram");
}
}
}
| Nikit-370/HackerRank-Solution | 1 Month Interview Kit/Pangrams | 180 | /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ | block_comment | en | true |
112045_37 | package tile;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import javax.imageio.ImageIO;
public class TileManager {
public Tile STONE, ROAD, GRASS, GRASSUP, GRASSRIGHT, GRASSLEFT, GRASSDOWN, GRASSTOPLEFT, GRASSTOPRIGHT,
GRASSBOTTOMLEFT, GRASSBOTTOMRIGHT, WATER, TREE, BUSH, FLOWER, CASTLE1, CASTLE2, CASTLE3, CASTLE4, WOOD; // Declare
// tile
// types
// as Tile
// objects
private BufferedImage map; // BufferedImage to store the sprite map
public ArrayList<Tile> tiles = new ArrayList<>(); // Create Tiles list
public int tileSize = 64;
public TileManager() {
loadMap();
createTiles();
}
// Method to create and add tile objects to the 'tiles' list
private void createTiles() {
// Creating Tile objects and adding them to 'tiles' list
// Random Tiles
tiles.add(BUSH = new Tile(getSprite(1, 0), false)); // 0
tiles.add(TREE = new Tile(getSprite(0, 0), false)); // 1
tiles.add(FLOWER = new Tile(getSprite(3, 6), false)); // 2
tiles.add(WOOD = new Tile(getSprite(9, 0), false)); // 3
////////////////////////////////////////////////////////////////////////////
tiles.add(WOOD = new Tile(getSprite(0, 6), false)); // 4
tiles.add(WOOD = new Tile(getSprite(1, 6), false)); // 5
tiles.add(WOOD = new Tile(getSprite(2, 6), false)); // 6
////////////////////////////////////////////////////////////////////////////
tiles.add(ROAD = new Tile(getSprite(8, 0), false)); // 7
tiles.add(GRASSTOPLEFT = new Tile(getSprite(2, 3), true)); // 8
tiles.add(GRASSTOPRIGHT = new Tile(getSprite(1, 3), true)); // 9
tiles.add(GRASSBOTTOMLEFT = new Tile(getSprite(4, 0), true)); // 10
tiles.add(GRASSBOTTOMRIGHT = new Tile(getSprite(0, 3), true)); // 11
tiles.add(GRASSBOTTOMRIGHT = new Tile(getSprite(0, 3), true)); // 12
tiles.add(GRASSRIGHT = new Tile(getSprite(1, 4), true)); // 13
tiles.add(GRASSLEFT = new Tile(getSprite(0, 4), true)); // 14
tiles.add(GRASS = new Tile(getSprite(2, 4), true)); // 15
tiles.add(GRASSDOWN = new Tile(getSprite(3, 0), true)); // 16
tiles.add(GRASSUP = new Tile(getSprite(2, 0), true)); // 17
tiles.add(CASTLE1 = new Tile(getSprite(8, 5), false)); // 18
tiles.add(CASTLE2 = new Tile(getSprite(9, 5), false)); // 19
tiles.add(CASTLE3 = new Tile(getSprite(9, 6), false)); // 20
tiles.add(CASTLE4 = new Tile(getSprite(8, 6), false)); // 21
tiles.add(WATER = new Tile(getSprite(4, 15), false)); // 22
}
public BufferedImage getWaterSprite(int frame) {
// Adjust the coordinates based on your sprite sheet layout
return getSprite(0 + frame, 15);
}
// Load and return the sprite map as a BufferedImage
public static BufferedImage getSpriteMap() {
BufferedImage img = null;
InputStream is = TileManager.class.getClassLoader().getResourceAsStream("res/spritesheet.png");
try {
img = ImageIO.read(is);
} catch (IOException e) {
e.printStackTrace();
}
return img;
}
private void loadMap() {
map = getSpriteMap();
}
// Method to get a specific Tile by its ID
public BufferedImage getSprite(int id) {
return tiles.get(id).getSprite();
}
// Method to get a sprite from the sprite map based on x, y coordinates
public BufferedImage getSprite(int x, int y) {
// Return a sub-image of the sprite based on the specified coordinates and
// tileSize
return map.getSubimage(x * tileSize, y * tileSize, tileSize, tileSize);
}
}
| Vidaxxxxx/school | TowerDefense/tile/TileManager.java | 1,089 | // Method to get a specific Tile by its ID | line_comment | en | true |
112365_0 | package com.bhav.Oops5;
public abstract class Parent{
int age;
public Parent(int age){
this.age= age;
}
static void hello(){
System.out.println("hey");
}
// abstract Parent(); // ***error*** we cannot create abastract constructors
abstract void career();
abstract void partner();
} | Bhavishaya-Bansal/JAVA | com/bhav/Oops5/Parent.java | 82 | // abstract Parent(); // ***error*** we cannot create abastract constructors | line_comment | en | true |
112420_6 | import java.awt.*;
public class player {
GamePanel gp;
double x, y;
int money;
String career;
int salary;
String house;
int babies;
int steps;
double count;
public player(int m, String c, int s, String h, int b, int st, GamePanel gp, int xVal, int yVal, double cnt) {
money = m;
career = c;
salary = s;
house = h;
babies = b;
steps = st;
this.gp = gp;
x = xVal;
y = yVal;
count = cnt;
}
public void move(){
if(this.getSteps() < 35 ) {
x += 1;
y -= .4;
}
else if(this.getSteps() == 35){
this.setCnt(-1);
}else if(this.getSteps() >= 35 && this.getSteps() < 85 ) {
x += 1;
y -= .2;
}else if(this.getSteps() == 85){
this.setCnt(-1);
}else if(this.getSteps() >= 85 && this.getSteps() < 135) {
x += 1;
y -= .05;
}else if(this.getSteps() == 135){
this.setCnt(-1);
}else if(this.getSteps() >= 135 && this.getSteps() < 185) {
x += 1;
y -= .05;
}else if(this.getSteps() == 185){
this.setCnt(-1);
this.addMoney(this.getSalary());
}else if(this.getSteps() >= 184 && this.getSteps() < 235) {
x += 1;
y += .2;
}else if(this.getSteps() ==235){
this.setCnt(-1);
}else if(this.getSteps() >= 235 && this.getSteps() < 275) {
x += 1;
y += .55;
}else if(this.getSteps() == 275){
this.setCnt(-1);
}else if(this.getSteps() >= 275 && this.getSteps() < 318) {
y += 1;
x-=.4;
}else if(this.getSteps() == 318){
this.setCnt(-1);
}else if(this.getSteps() >= 318 && this.getSteps() < 370) {
y += .35;
x -= 1;
}else if(this.getSteps() == 370){
this.setCnt(-1);
}else if(this.getSteps() >= 370 && this.getSteps() < 415){
y+=.25;
x-=1;
}else if(this.getSteps() == 415){
this.setCnt((int)this.getCnt() * -1);
//this.setCnt(-1);
}else if(this.getSteps() >= 415 && this.getSteps() < 465) {
y += .3;
x -= 1;
}else if(this.getSteps() == 465){
this.setCnt(-1);
}else if(this.getSteps() >= 465 && this.getSteps() < 500) {
y += 1;
x -= 1;
}else if(this.getSteps() == 500){
this.setCnt(-1);
}else if(this.getSteps() >= 500 && this.getSteps() < 545) {
x -= 0;
y += 1;
}else if(this.getSteps() == 545){
this.setCnt(-1);
this.addMoney(this.getSalary());
}else if(this.getSteps() >= 545 && this.getSteps() < 585) {
y += .8;
x+=1;
}else if(this.getSteps() == 585){
this.setCnt(-1);
}else if(this.getSteps() >= 585 && this.getSteps() < 640) {
x += 1;
y += .3;
}else if(this.getSteps() == 640){
this.setCnt(-1);
}else if(this.getSteps() >= 640 && this.getSteps() < 695){
x+=1;
y+=.1;
}else if(this.getSteps() == 695){
this.setCnt(-1);
}else if(this.getSteps() >= 695 && this.getSteps() < 750){
x+=1;
y-=.3;
}else if(this.getSteps() == 750){
this.setCnt((int) this.getCnt() * -1);
//this.setCnt(-1);
}else if(this.getSteps() >= 750 && this.getSteps() < 810){
x+=1;
y-=.4;
}else if(this.getSteps() == 810){
this.setCnt(-1);
}else if(this.getSteps() >= 810 && this.getSteps() < 850){
x+=1;
y-=1;
}else if(this.getSteps() == 850){
this.setCnt(-1);
}else if(this.getSteps() >= 850 && this.getSteps() < 950){
x+=.5;
y-=.3;
}else if(this.getSteps() == 950){
this.setCnt(-1);
}else if(this.getSteps() >= 950 && this.getSteps() < 1055){
x+=.5;
y+=.1;
}else if(this.getSteps() == 1055){
this.setCnt(-1); //step 20
}else if(this.getSteps() >= 1055 && this.getSteps() < 1140){
x+=.5;
y+=.3;
}else if(this.getSteps() == 1140){
this.setCnt(-1);
this.addMoney(this.getSalary());
}else if(this.getSteps() >= 1140 && this.getSteps() < 1220){
y+=.65;
}else if(this.getSteps() == 1220){
this.setCnt(-1);
}else if(this.getSteps() >= 1220 && this.getSteps() < 1290){
x-=.3;
y+=.6;
}else if(this.getSteps() == 1290){
this.setCnt(-1);
}else if(this.getSteps() >= 1290 && this.getSteps() < 1360){
x-=.6;
y+=.4;
}else if(this.getSteps() == 1360){
this.setCnt(-1);
}else if(this.getSteps() >= 1360 && this.getSteps() < 1460){
x-=.6;
y+=.2;
}else if(this.getSteps() == 1460){
this.setCnt(-1);//25^
}else if(this.getSteps() >= 1460 && this.getSteps() < 1560){
x-=.6;
}else if(this.getSteps() == 1560){
this.setCnt(-1);
}else if(this.getSteps() >= 1560 && this.getSteps() < 1680){
x-=.5;
y+=.1;
}else if(this.getSteps() == 1680){
this.setCnt(-1);
this.addMoney(this.getSalary());
}else if(this.getSteps() >= 1680 && this.getSteps() < 1780){
x-=.5;
y+=.1;
}else if(this.getSteps() == 1780){
this.setCnt(-1);
}else if(this.getSteps() >= 1780 && this.getSteps() < 1880){
x-=.5;
y+=.2;
}else if(this.getSteps() == 1880){
this.setCnt((int) this.getCnt() * -1);
}else if(this.getSteps() >= 1880 && this.getSteps() < 1965){
x-=.5;
y+=.3;
}else if(this.getSteps() == 1965){
this.setCnt(-1);
}else if(this.getSteps() >= 1965 && this.getSteps() < 2030){
y+=.7;
}else if(this.getSteps() == 2030){
this.setCnt(-1);
}else if(this.getSteps() >= 2030 && this.getSteps() < 2090){
x+=.3;
y+=.7;
}else if(this.getSteps() == 2090){
this.setCnt(-1);
}else if(this.getSteps() >= 2090 && this.getSteps() < 2170){
x+=.6;
y+=.2;
}else if(this.getSteps() == 2170){
this.setCnt(-1);
}else if(this.getSteps() >= 2170 && this.getSteps() < 2250){
x+=.7;
y+=.1;
}else if(this.getSteps() == 2250){
this.setCnt(-1);
}else if(this.getSteps() >= 2250 && this.getSteps() < 2330){
x+=.7;
y-=.1;
}else if(this.getSteps() == 2330){
this.setCnt(-1);
}else if(this.getSteps() >= 2330 && this.getSteps() < 2410){
x+=.7;
y-=.2;
}else if(this.getSteps() == 2410){
this.setCnt(-1);
}else if(this.getSteps() >= 2410 && this.getSteps() < 2470){
x+=.7;
}else if(this.getSteps() == 2470){
this.setCnt(-1);
this.addMoney(this.getSalary());
}else if(this.getSteps() >= 2470 && this.getSteps() < 2570) {
x += .7;
}else if(this.getSteps() == 2570){
this.setCnt(-1);
}else if(this.getSteps() >= 2570 && this.getSteps() < 2700) {
x += .7;
}else if(this.getSteps() == 2700){
this.setCnt(-1);
}
}
public double getMove(){
return x;
}
public void drawSelf(Graphics g, int p){
if(p==1){
//g.setColor(Color.black);
//g.fillRect((int)x, (int)y, 20, 20);
Image boyPeg = Toolkit.getDefaultToolkit().getImage("boyPeg.png"); /*the image cannot be in the SRC folder*/
g.drawImage(boyPeg, (int)x, (int)y, 50,50,gp );
}else{
Image girlPeg = Toolkit.getDefaultToolkit().getImage("girlPeg.png"); /*the image cannot be in the SRC folder*/
g.drawImage(girlPeg,(int)x, (int)y, 50,50,gp );
//g.setColor(Color.blue);
//g.fillRect((int)x, (int)y, 20, 20);
}
}
public int getMoney() {
return money;
}
public int getSalary() {
return salary;
}
public String getCareer() {
return career;
}
public int getBabies() {
return babies;
}
public void setBabies(int num){
babies += num;
}
public String getHouse() {
return house;
}
public int getSteps() {
return steps;
}
public void addMoney(int val){
money+= val;
}
public void subMoney(int val){
money-=val;
}
public void setSalary(int val){
salary = val;
}
public void setCareer(String car){
career = car;
}
public void setHouse(String h){
house = h;
}
public void setSteps(){
steps+=1;
}
public double getCnt(){
return count;
}
public void setCnt(int amount){
count+=amount;
}
}
| Erika-Sal/finalGameOfLife | src/player.java | 3,190 | /*the image cannot be in the SRC folder*/ | block_comment | en | true |
112637_4 | /**
* @(#)Stumps.java
*
*
* @author
* @version 1.00 2014/1/8
*/
import java.util.*;
import java.io.*;
public class Stumps implements Classifier {
private boolean bool_decision = true;
private int index_decision = 0;
public Stumps(BinaryDataSet b, double[] weights) {
//for thru attributes:
//check if this attribute is the one we should split on by
//for thru training examples
//split on this attribute, see how many (weighted) mistakes
double max_decision = 0;
for (int a = 0; a < b.numAttrs; a++) {
double match = 0;
double mistake = 0;
for (int ex = 0; ex < b.numTrainExs; ex++) {
if (b.trainEx[ex][a] == b.trainLabel[ex])
match += weights[ex];
else
mistake += weights[ex];
}
if (match > max_decision) {
bool_decision = true;
index_decision = a;
max_decision = match;
}
if (mistake > max_decision) {
bool_decision = false;
index_decision = a;
max_decision = mistake;
}
}
}
public int predict(int[] ex) {
if (ex[index_decision] == 0) {
if (bool_decision)
return 0;
else
return 1;
}
else {
if (bool_decision)
return 1;
else
return 0;
}
}
public String algorithmDescription() {
return "weighted stump";
}
public String author() {
return "pthorpedmmckenn";
}
public static void main(String[] args)
throws FileNotFoundException, IOException {
if (args.length < 1) {
System.err.println("argument: filestem");
return;
}
String filestem = args[0];
BinaryDataSet d = new BinaryDataSet(filestem);
double[] weights = new double[d.numTrainExs];
for (int i = 0; i < weights.length; i++)
weights[i] = 1;
Classifier c = new Stumps(d,weights);
d.printTestPredictions(c, filestem);
}
}
| thorpep138/cos_402_final_project | Stumps.java | 610 | //split on this attribute, see how many (weighted) mistakes | line_comment | en | true |
112799_1 | package com.fishercoder.solutions;
/**
* 97. Interleaving String
*
* Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
* For example,
* Given:
* s1 = "aabcc",
* s2 = "dbbca",
* When s3 = "aadbbcbcac", return true.
* When s3 = "aadbbbaccc", return false.
*/
public class _97 {
public static class Solution1 {
public boolean isInterleave(String s1, String s2, String s3) {
int m = s1.length();
int n = s2.length();
if (m + n != s3.length()) {
return false;
}
boolean[][] dp = new boolean[m + 1][n + 1];
dp[0][0] = true;
for (int i = 0; i < m; i++) {
if (s1.charAt(i) == s3.charAt(i)) {
dp[i + 1][0] = true;
} else {
//if one char fails, that means it breaks, the rest of the chars won't matter any more.
//Mian and I found one missing test case on Lintcode: ["b", "aabccc", "aabbbcb"]
//if we don't break, here, Lintcode could still accept this code, but Leetcode fails it.
break;
}
}
for (int j = 0; j < n; j++) {
if (s2.charAt(j) == s3.charAt(j)) {
dp[0][j + 1] = true;
} else {
break;
}
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
int k = i + j - 1;
dp[i][j] = (s1.charAt(i - 1) == s3.charAt(k) && dp[i - 1][j])
|| (s2.charAt(j - 1) == s3.charAt(k) && dp[i][j - 1]);
}
}
return dp[m][n];
}
}
}
| gary-x-li/Leetcode | src/main/java/com/fishercoder/solutions/_97.java | 537 | //if one char fails, that means it breaks, the rest of the chars won't matter any more. | line_comment | en | false |
112922_0 | package gogo;
public class NumbersOfWords {
// billion: 1,000,000,000
// million: 1,000,000
// thousand: 1,000
public String numberToWords(int num) {
if(num==0) return "Zero";
int[] nums = new int[4];
String[] bases=new String[4];
bases[0] ="";
bases[1] = "Thousand";
bases[2] = "Million";
bases[3] = "Billion";
for(int i=0;i<4;i++){
nums[i]=num%1000;
num=num/1000;
}
StringBuilder sb=new StringBuilder();
for(int i=3;i>=0;i--) {
if (nums[i]!=0) {
String hundreds=helper(nums[i]);
if(sb.length()>0) {sb.append(" ");}
sb.append(hundreds.trim());
sb.append(" ");
sb.append(bases[i]);
}
}
return sb.toString().trim();
}
private String helper(int n){
int[] nums = new int[3];
for(int i=0;i<3;i++) {
nums[i]=n%10;
n=n/10;
}
StringBuilder sb=new StringBuilder();
if (nums[2]!=0){
sb.append(ones(nums[2]));
sb.append(" ");
sb.append("Hundred");
}
if (nums[1]>1) {
if(sb.length()>0) sb.append(" ");
sb.append(tens(nums[1]));
if (nums[0] !=0) {
if(sb.length()>0) sb.append(" ");
sb.append(ones(nums[0]));
}
} else if (nums[1]==1) {
if(sb.length()>0) sb.append(" ");
sb.append(teens(nums[0]));
} else {
if(sb.length()>0) sb.append(" ");
sb.append(ones(nums[0]));
}
return sb.toString();
}
private String teens(int n){
switch (n) {
case 0: return "Ten";
case 1: return "Eleven";
case 2: return "Twelve";
case 3: return "Thirteen";
case 4: return "Fourteen";
case 5: return "Fifteen";
case 6: return "Sixteen";
case 7: return "Seventeen";
case 8: return "Eighteen";
case 9: return "Nineteen";
default: return "";
}
}
private String ones(int n){
switch (n) {
case 1: return "One";
case 2: return "Two";
case 3: return "Three";
case 4: return "Four";
case 5: return "Five";
case 6: return "Six";
case 7: return "Seven";
case 8: return "Eight";
case 9: return "Nine";
default: return "";
}
}
private String tens(int n){
switch (n) {
case 2: return "Twenty";
case 3: return "Thirty";
case 4: return "Forty";
case 5: return "Fifty";
case 6: return "Sixty";
case 7: return "Seventy";
case 8: return "Eighty";
case 9: return "Ninety";
default: return "";
}
}
}
| WeizhengZhou/leetcode3 | src/gogo/NumbersOfWords.java | 933 | // billion: 1,000,000,000 | line_comment | en | false |
112959_4 | /*
Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.
For example,
123 -> "One Hundred Twenty Three"
12345 -> "Twelve Thousand Three Hundred Forty Five"
1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
Hint:
Did you see a pattern in dividing the number into chunk of words? For example, 123 and 123000.
Group the number by thousands (3 digits). You can write a helper function that takes a number less than 1000 and convert just that chunk to words.
There are many edge cases. What are some good test cases? Does your code work with input such as 0? Or 1000010? (middle chunk is zero and should not be printed out)
*/
public class IntegerToEnglishWords {
public String[] digits = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
public String[] teens = {"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
public String[] tens = {"Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
public String[] bigs = {"", "Thousand", "Million", "Billion"};
public String numberToWords(int number) {
if (number == 0) {
return "Zero";
}
if (number < 0) {
return "Negative " + numberToWords(-1 * number);
}
int count = 0;
String str = "";
while (number > 0) {
if (number % 1000 != 0) {
str = numToString100(number % 1000) + bigs[count] + " " + str;
}
number /= 1000;
count++;
}
return str.trim();
}
private String numToString100(int number) {
String str = "";
/* Convert hundreds place */
if (number >= 100) {
str += digits[number / 100 - 1] + " Hundred ";
number %= 100;
}
/* Convert tens place */
if (number >= 11 && number <= 19) {
return str + teens[number - 11] + " ";
} else if (number == 10 || number >= 20) {
str += tens[number / 10 - 1] + " ";
number %= 10;
}
/* Convert ones place */
if (number >= 1 && number <= 9) {
str += digits[number - 1] + " ";
}
return str;
}
}
/*
CC150 17-7
Reference:
https://leetcode.com/discuss/55273/my-java-solution
https://leetcode.com/discuss/55276/my-accepted-java-solution-248ms
https://leetcode.com/discuss/55349/if-you-know-how-to-read-numbers-you-can-make-it
http://www.cnblogs.com/jcliBlogger/p/4774090.html
*/ | songy23/Leetcode-1 | Medium/IntegerToEnglishWords.java | 890 | /*
CC150 17-7
Reference:
https://leetcode.com/discuss/55273/my-java-solution
https://leetcode.com/discuss/55276/my-accepted-java-solution-248ms
https://leetcode.com/discuss/55349/if-you-know-how-to-read-numbers-you-can-make-it
http://www.cnblogs.com/jcliBlogger/p/4774090.html
*/ | block_comment | en | true |
112997_4 | package logic1;
public class TeenSum {
// Given 2 ints, a and b, return their sum. However, "teen" values in the range 13..19 inclusive, are extra lucky.
// So if either value is a teen, just return 19.
//
// teenSum(3, 4) → 7
// teenSum(10, 13) → 19
// teenSum(13, 2) → 19
public int teenSum(int a, int b) {
if (a >= 13 && a <= 19 || b >= 13 && b <= 19) {
return 19;
}
return a + b;
}
}
| MalsR/codingbat | src/main/java/logic1/TeenSum.java | 182 | // teenSum(10, 13) → 19 | line_comment | en | true |
113485_8 | import java.io.IOException;
import java.util.*;
/**
Class to handle/mock the stream operations
This can be enhanced in the future to read from a real data stream pipeline
This class processes each loan and maps to right facility, and then performs bookkeeping
*/
public class StreamProcessor {
// Facilities sorted by interest rate
private ArrayList<Facility> sortedFacilities;
private TreeMap<Integer, Float> facilityYield = new TreeMap<>();
TreeMap<Integer, Integer> loanFacility = new TreeMap<>();
TreeMap<Integer, Integer> facilityYieldFinal = new TreeMap<>();
/**
* Constructor to setup the stream processing context
* The context is completely in memory - but needs to be more durable in future
*/
public StreamProcessor(String facilityFilePath, String covenantFilePath) {
// Load the processing context in form of facilities and covenants
try {
Hashtable<Integer, Facility> facilities = FileLoader.readFacilities(facilityFilePath, covenantFilePath);
// Once we have all the facilities and its covenants, build a list of faciities
// sorted by the interest rate
// We are optimizing for reading/access of faciities to match incoming loans
// So sort it once - nlg(n)
sortedFacilities = new ArrayList<Facility>(facilities.values());
sortedFacilities.sort((o1, o2) -> Math.round(o1.compareTo(o2)));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Method to handle the stream of loans
* Iterate through every object and invoke processing operation
* In future this can be subscribing to a data pipeline
*/
void loanStreamSubscriber(LinkedList<Loan> loans) {
// Check the loan against every facility to match its covenants
// For now we will be looping over
// This can be an actual subscriber to a streaming pipeline
for (Loan l: loans) {
this.computeOnStreamedInstance(l);
}
}
/**
* Operation to handle an instance of the streamed data
*/
private void computeOnStreamedInstance(Loan l) {
for (Facility f: sortedFacilities) {
// Check if loan is eligible - and then book-keeping if yes
if (f.getLoanEligibility(l).isApproved) {
this.manageLoanAssignmentBookKeeping(l, f);
return;
}
}
// Unassigned loan scenario
this.manageLoanAssignmentBookKeeping(l, null);
}
/**
* Manage the book keeping of assigning and updating loan assignments
* @param loan
* @param facility
*/
private void manageLoanAssignmentBookKeeping(Loan loan, Facility facility) {
// Manage unassigned loan
if (facility == null) {
this.loanFacility.put(loan.id, 0);
}
else {
this.loanFacility.put(loan.id, facility.facilityId);
// Reduce the loan amount available to trade
facility.amountAvailableToLoan -= loan.amount;
// Manage loan yield calculation and assign to facility
float yield = this.facilityYield.getOrDefault(facility.facilityId, Float.valueOf("0"));
yield += this.getFacilityYieldForLoan(loan, facility);
this.facilityYield.put(facility.facilityId, yield);
}
}
/**
* Calculate the yield for loan and facility
* @param loan
* @param facility
* @return
*/
private float getFacilityYieldForLoan(Loan loan, Facility facility) {
return (1 - loan.defaultLikelihood) * loan.interestRate * loan.amount
- (loan.defaultLikelihood * loan.amount)
- (facility.interestRate * loan.amount);
}
/**
* Convert hash table into Map<String, String> useful for CSV writing
*/
void roundOffFinalCalculations() {
this.facilityYield.entrySet()
.iterator()
.forEachRemaining(E -> this.facilityYieldFinal.put(
E.getKey(), Math.round(E.getValue())
));
}
}
| devEffort/funLoans | src/StreamProcessor.java | 980 | /**
* Method to handle the stream of loans
* Iterate through every object and invoke processing operation
* In future this can be subscribing to a data pipeline
*/ | block_comment | en | false |
113744_0 | /******************************
* Copyright (c) 2003,2019 Kevin Lano
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
* *****************************/
public class Scope
{ String scopeKind = "";
BasicExpression arrayExp = null;
BinaryExpression resultScope = null;
Scope(String k, BinaryExpression rs)
{ scopeKind = k;
resultScope = rs;
}
Scope(String k, BinaryExpression rs, BasicExpression a)
{ this(k,rs);
arrayExp = a;
}
}
| eclipse/agileuml | Scope.java | 185 | /******************************
* Copyright (c) 2003,2019 Kevin Lano
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
* *****************************/ | block_comment | en | true |
113832_24 | import java.io.*;
import java.util.ArrayList;
public class FileLoader {
private ArrayList<CreditCards> creditCards = new ArrayList<CreditCards>(); // Dilwsi arraylist gia ta creditcards
private ArrayList<Loan> loans = new ArrayList<Loan>();// Dilwsi arraylist gia ta loans
private ArrayList<Sellers> sellers = new ArrayList<Sellers>();// Dilwsi arraylist gia tous sellers
private ArrayList<Sales> sales = new ArrayList<Sales>();// Dilwsi arraylist gia ta sales
private ArrayList<CreditCardMovement> creditCardMovements = new ArrayList<CreditCardMovement>();// Dilwsi arraylist
// gia ta
// creditcards
// movements
public void loadFileBankProducts(String data) {
BufferedReader reader = null; // ta thetoume null
CreditCards creditCard = null;
Loan loan = null;
try {
reader = new BufferedReader(new FileReader(data));
String line;
while ((line = reader.readLine()) != null) { // diavazei kathe line tou text
if (line.toUpperCase().contains("BANKITEM_LIST".toUpperCase()) || (line.contains("{"))
|| (line.toUpperCase().contains("BANKITEM".toUpperCase()))
|| (line.contains("}"))) { // an to line periexei ena apo afta tote pigainei sto epomeno
continue;
} else {
if (line.toUpperCase().contains("Card".toUpperCase())) { // an line periexei to Card tote ftiaxnei
// object
creditCard = new CreditCards(); // credit card kai topothetei
line = reader.readLine(); // ta stoixeia pou diavazei an line
((CreditCards) creditCard).setCode(Integer.parseInt(line.trim().split(" ", 2)[1]));
line = reader.readLine();
((CreditCards) creditCard).setDescribe(line.trim().split(" ", 2)[1]);
line = reader.readLine();
((CreditCards) creditCard).setAfm(Integer.parseInt(line.trim().split(" ", 2)[1]));
line = reader.readLine();
((CreditCards) creditCard).setNumber(Integer.parseInt(line.trim().split(" ", 2)[1]));
line = reader.readLine();
((CreditCards) creditCard)
.setCommissionRate(Double.parseDouble(line.trim().split(" ", 2)[1]));
line = reader.readLine();
((CreditCards) creditCard)
.setMaxAmountOfMovement(Double.parseDouble(line.trim().split(" ", 2)[1]));
line = reader.readLine();
((CreditCards) creditCard)
.setMaxAnnualAmmount(Double.parseDouble(line.trim().split(" ", 2)[1]));
} else if (line.toUpperCase().contains("Loan".toUpperCase())) { // an line periexei to Loan tote
// ftiaxnei object
loan = new Loan(); // loan kai topothetei
line = reader.readLine(); // ta stoixeia pou diavazei an line
((Loan) loan).setCode(Integer.parseInt((line.trim().split(" ", 2)[1])));
line = reader.readLine();
((Loan) loan).setDescribe(((line.trim().split(" ", 2)[1])));
line = reader.readLine();
((Loan) loan).setAfm(Integer.parseInt(((line.trim().split(" ", 2)[1]))));
line = reader.readLine();
((Loan) loan).setNumber(Integer.parseInt(((line.trim().split(" ", 2)[1]))));
line = reader.readLine();
((Loan) loan).setAmountOfLoan(Integer.parseInt(((line.trim().split(" ", 2)[1]))));
line = reader.readLine();
((Loan) loan).setAnnualInterestRate(Integer.parseInt(((line.trim().split(" ", 2)[1]))));
}
if (creditCards.size() < 4) {
creditCards.add(creditCard);
}
if (loan != null) {
loans.add(loan);
}
line = reader.readLine();
}
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
// reader.close();
public void loadFileSellers(String data) {
BufferedReader reader = null;
Sellers seller = null;
try {
reader = new BufferedReader(new FileReader(data));
String line;
while ((line = reader.readLine()) != null) {
if (line.contains("SALESMAN_LIST") || (line.contains("{")) || (line.trim().contains("SALESMAN"))
|| (line.contains("}"))) { // do nothing go to the next line
continue;
} else {
seller = new Sellers();
((Sellers) seller).setCode(Integer.parseInt(line.trim().split(" ", 2)[1]));
line = reader.readLine();
((Sellers) seller).setLastName(line.trim().split(" ", 2)[1]);
line = reader.readLine();
((Sellers) seller).setFirstName(line.trim().split(" ", 2)[1]);
line = reader.readLine();
((Sellers) seller).setAfm(Integer.parseInt(line.trim().split(" ", 2)[1]));
sellers.add(seller);
line = reader.readLine();
}
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
// reader.close();
public void loadFileSales(String data) {
BufferedReader reader = null;
Sales sale = null;
try {
reader = new BufferedReader(new FileReader(data));
String line;
while ((line = reader.readLine()) != null) {
if (line.contains("SALES_LIST") || (line.contains("{")) || (line.trim().equals("SALES"))
|| (line.contains("}"))) { // do nothing go to the next line
continue;
} else {
sale = new Sales();
((Sales) sale).setCode(Integer.parseInt(line.trim().split(" ", 2)[1]));
line = reader.readLine();
((Sales) sale).setBankItemType(line.trim().split(" ", 2)[1]);
line = reader.readLine();
((Sales) sale).setBankProductCode(Integer.parseInt(line.trim().split(" ", 2)[1]));
line = reader.readLine();
((Sales) sale).setReason(line.trim().split(" ", 2)[1]);
sales.add(sale);
line = reader.readLine();
}
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
public void loadFileCreditCardMovements(String data) {
BufferedReader reader = null;
CreditCardMovement creditCardMovement = null;
try {
reader = new BufferedReader(new FileReader(data));
String line;
while ((line = reader.readLine()) != null) {
if (line.contains("TRN_LIST") || (line.contains("{")) || (line.trim().equals("TRN"))
|| (line.contains("}"))) { // do nothing go to the next line
continue;
} else {
creditCardMovement = new CreditCardMovement();
((CreditCardMovement) creditCardMovement)
.setEmplCode(Integer.parseInt(line.trim().split(" ", 2)[1]));
line = reader.readLine();
((CreditCardMovement) creditCardMovement).setCode(Integer.parseInt(line.trim().split(" ", 2)[1]));
line = reader.readLine();
((CreditCardMovement) creditCardMovement)
.setMovementWorth(Double.parseDouble(line.trim().split(" ", 2)[1]));
line = reader.readLine();
((CreditCardMovement) creditCardMovement).setReason(line.trim().split(" ", 2)[1]);
creditCardMovements.add(creditCardMovement);
line = reader.readLine();
}
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
public void WriteFilesCreditCardMovements(String data, int bankCode, int emplCode, double val, String reason) {
BufferedReader reader = null;
BufferedWriter writer = null;
try {
reader = new BufferedReader(new FileReader(data));
String line;
writer = new BufferedWriter(new FileWriter(data, true));
// while ((line = reader.readLine()).equals("}")) {
// continue;
// }
writer.write("\t\tTRN\n\t{\n\t\tEMPLOYEE_CODE " + emplCode + "\n\t\tΒΑΝΚΙΤΕΜ_CODE " + bankCode
+ "\n\t\tVAL " + val + "\n\t\tJUSTIFICATION " + reason + "\n\t}\n}");
writer.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
public void WriteFilesSales(String data, int salesmanCode, String bankItemType, int bankItemCode, String reason) {
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(data, true));
writer.write("\t\tSALES\n\t{\n\t\tSALESMAN_CODE " + salesmanCode + "\n\t\tBANKITEM_TYPE " + bankItemType
+ "\n\t\tBANKITEM_CODE " + bankItemCode + "\n\t\tJUSTIFICATION " + reason + "\n\t}\n}"); // writes
// data
writer.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
public ArrayList<CreditCards> getCreditCards() {
return creditCards;
}
public ArrayList<Loan> getLoans() {
return loans;
}
public ArrayList<CreditCardMovement> getCreditCardMovements() {
return creditCardMovements;
}
public ArrayList<Sales> getSales() {
return sales;
}
public ArrayList<Sellers> getSellers() {
return sellers;
}
public boolean isFileExists(File file) {
return file.exists();
}
}
| harabalos/Bank_Product_Manager | FileLoader.java | 2,365 | // while ((line = reader.readLine()).equals("}")) { | line_comment | en | true |
114402_17 | import java.awt.Color;
/**
* Class that references a pixel in a picture. Pixel
* stands for picture element where picture is
* abbreviated pix. A pixel has a column (x) and
* row (y) location in a picture. A pixel knows how
* to get and set the red, green, blue, and alpha
* values in the picture. A pixel also knows how to get
* and set the color using a Color object.
*
* @author Barb Ericson [email protected]
*/
public class Pixel
{
////////////////////////// fields ///////////////////////////////////
/** the digital picture this pixel belongs to */
private Picture picture;
/** the x (column) location of this pixel in the picture; (0,0) is top left */
private int x;
/** the y (row) location of this pixel in the picture; (0,0) is top left */
private int y;
////////////////////// constructors /////////////////////////////////
/**
* A constructor that takes the x and y location for the pixel and
* the picture the pixel is coming from
* @param picture the picture that the pixel is in
* @param x the x location of the pixel in the picture
* @param y the y location of the pixel in the picture
*/
public Pixel(Picture picture, int x, int y)
{
// set the picture
this.picture = picture;
// set the x location
this.x = x;
// set the y location
this.y = y;
}
///////////////////////// methods //////////////////////////////
/**
* Method to get the x location of this pixel.
* @return the x location of the pixel in the picture
*/
public int getX() { return x; }
/**
* Method to get the y location of this pixel.
* @return the y location of the pixel in the picture
*/
public int getY() { return y; }
/**
* Method to get the row (y value)
* @return the row (y value) of the pixel in the picture
*/
public int getRow() { return y; }
/**
* Method to get the column (x value)
* @return the column (x value) of the pixel
*/
public int getCol() { return x; }
/**
* Method to get the amount of alpha (transparency) at this pixel.
* It will be from 0-255.
* @return the amount of alpha (transparency)
*/
public int getAlpha() {
/* get the value at the location from the picture as a 32 bit int
* with alpha, red, green, blue each taking 8 bits from left to right
*/
int value = picture.getBasicPixel(x,y);
// get the alpha value (starts at 25 so shift right 24)
// then and it with all 1's for the first 8 bits to keep
// end up with from 0 to 255
int alpha = (value >> 24) & 0xff;
return alpha;
}
/**
* Method to get the amount of red at this pixel. It will be
* from 0-255 with 0 being no red and 255 being as much red as
* you can have.
* @return the amount of red from 0 for none to 255 for max
*/
public int getRed() {
/* get the value at the location from the picture as a 32 bit int
* with alpha, red, green, blue each taking 8 bits from left to right
*/
int value = picture.getBasicPixel(x,y);
// get the red value (starts at 17 so shift right 16)
// then AND it with all 1's for the first 8 bits to
// end up with a resulting value from 0 to 255
int red = (value >> 16) & 0xff;
return red;
}
/**
* Method to get the red value from a pixel represented as an int
* @param value the color value as an int
* @return the amount of red
*/
public static int getRed(int value)
{
int red = (value >> 16) & 0xff;
return red;
}
/**
* Method to get the amount of green at this pixel. It will be
* from 0-255 with 0 being no green and 255 being as much green as
* you can have.
* @return the amount of green from 0 for none to 255 for max
*/
public int getGreen() {
/* get the value at the location from the picture as a 32 bit int
* with alpha, red, green, blue each taking 8 bits from left to right
*/
int value = picture.getBasicPixel(x,y);
// get the green value (starts at 9 so shift right 8)
int green = (value >> 8) & 0xff;
return green;
}
/**
* Method to get the green value from a pixel represented as an int
* @param value the color value as an int
* @return the amount of green
*/
public static int getGreen(int value)
{
int green = (value >> 8) & 0xff;
return green;
}
/**
* Method to get the amount of blue at this pixel. It will be
* from 0-255 with 0 being no blue and 255 being as much blue as
* you can have.
* @return the amount of blue from 0 for none to 255 for max
*/
public int getBlue() {
/* get the value at the location from the picture as a 32 bit int
* with alpha, red, green, blue each taking 8 bits from left to right
*/
int value = picture.getBasicPixel(x,y);
// get the blue value (starts at 0 so no shift required)
int blue = value & 0xff;
return blue;
}
/**
* Method to get the blue value from a pixel represented as an int
* @param value the color value as an int
* @return the amount of blue
*/
public static int getBlue(int value)
{
int blue = value & 0xff;
return blue;
}
/**
* Method to get a color object that represents the color at this pixel.
* @return a color object that represents the pixel color
*/
public Color getColor()
{
/* get the value at the location from the picture as a 32 bit int
* with alpha, red, green, blue each taking 8 bits from left to right
*/
int value = picture.getBasicPixel(x,y);
// get the red value (starts at 17 so shift right 16)
// then AND it with all 1's for the first 8 bits to
// end up with a resulting value from 0 to 255
int red = (value >> 16) & 0xff;
// get the green value (starts at 9 so shift right 8)
int green = (value >> 8) & 0xff;
// get the blue value (starts at 0 so no shift required)
int blue = value & 0xff;
return new Color(red,green,blue);
}
/**
* Method to set the pixel color to the passed in color object.
* @param newColor the new color to use
*/
public void setColor(Color newColor)
{
// set the red, green, and blue values
int red = newColor.getRed();
int green = newColor.getGreen();
int blue = newColor.getBlue();
// update the associated picture
updatePicture(this.getAlpha(),red,green,blue);
}
/**
* Method to update the picture based on the passed color
* values for this pixel
* @param alpha the alpha (transparency) at this pixel
* @param red the red value for the color at this pixel
* @param green the green value for the color at this pixel
* @param blue the blue value for the color at this pixel
*/
public void updatePicture(int alpha, int red, int green, int blue)
{
// create a 32 bit int with alpha, red, green blue from left to right
int value = (alpha << 24) + (red << 16) + (green << 8) + blue;
// update the picture with the int value
picture.setBasicPixel(x,y,value);
}
/**
* Method to correct a color value to be within 0 to 255
* @param the value to use
* @return a value within 0 to 255
*/
private static int correctValue(int value)
{
if (value < 0)
value = 0;
if (value > 255)
value = 255;
return value;
}
/**
* Method to set the red to a new red value
* @param value the new value to use
*/
public void setRed(int value)
{
// set the red value to the corrected value
int red = correctValue(value);
// update the pixel value in the picture
updatePicture(getAlpha(), red, getGreen(), getBlue());
}
/**
* Method to set the green to a new green value
* @param value the value to use
*/
public void setGreen(int value)
{
// set the green value to the corrected value
int green = correctValue(value);
// update the pixel value in the picture
updatePicture(getAlpha(), getRed(), green, getBlue());
}
/**
* Method to set the blue to a new blue value
* @param value the new value to use
*/
public void setBlue(int value)
{
// set the blue value to the corrected value
int blue = correctValue(value);
// update the pixel value in the picture
updatePicture(getAlpha(), getRed(), getGreen(), blue);
}
/**
* Method to set the alpha (transparency) to a new alpha value
* @param value the new value to use
*/
public void setAlpha(int value)
{
// make sure that the alpha is from 0 to 255
int alpha = correctValue(value);
// update the associated picture
updatePicture(alpha, getRed(), getGreen(), getBlue());
}
/**
* Method to get the distance between this pixel's color and the passed color
* @param testColor the color to compare to
* @return the distance between this pixel's color and the passed color
*/
public double colorDistance(Color testColor)
{
double redDistance = this.getRed() - testColor.getRed();
double greenDistance = this.getGreen() - testColor.getGreen();
double blueDistance = this.getBlue() - testColor.getBlue();
double distance = Math.sqrt(redDistance * redDistance +
greenDistance * greenDistance +
blueDistance * blueDistance);
return distance;
}
/**
* Method to compute the color distances between two color objects
* @param color1 a color object
* @param color2 a color object
* @return the distance between the two colors
*/
public static double colorDistance(Color color1,Color color2)
{
double redDistance = color1.getRed() - color2.getRed();
double greenDistance = color1.getGreen() - color2.getGreen();
double blueDistance = color1.getBlue() - color2.getBlue();
double distance = Math.sqrt(redDistance * redDistance +
greenDistance * greenDistance +
blueDistance * blueDistance);
return distance;
}
/**
* Method to get the average of the colors of this pixel
* @return the average of the red, green, and blue values
*/
public double getAverage()
{
double average = (getRed() + getGreen() + getBlue()) / 3.0;
return average;
}
/**
* Method to return a string with information about this pixel
* @return a string with information about this pixel
*/
public String toString()
{
return "Pixel row=" + getRow() +
" col=" + getCol() +
" red=" + getRed() +
" green=" + getGreen() +
" blue=" + getBlue();
}
}
| SunnyHillsHighSchool/picture-class-rpaik4204 | Pixel.java | 2,840 | // get the alpha value (starts at 25 so shift right 24)
| line_comment | en | false |
114580_0 | /**
* The Calculator class in Java performs basic arithmetic operations such as addition, subtraction,
* multiplication, and division.
*/
class Calculator{
float addition(float operand_1,float operand_2){
return(operand_1+operand_2);
}
float substraction(float operand_1,float operand_2){
return(operand_1-operand_2);
}
float multiplication(float operand_1,float operand_2){
return(operand_1*operand_2);
}
float division(float operand_1,float operand_2){
return(operand_1/operand_2);
}
public static void main(String[]args){
Calculator calc=new Calculator();
float operand_1=10;
float operand_2=10;
float add_result=calc.addition(operand_1,operand_2);
System.out.println("result:"+add_result);
float sub_result=calc.substraction(operand_1,operand_2);
System.out.println("result:"+sub_result);
float mult_result=calc.multiplication(operand_1,operand_2);
System.out.println("result:"+mult_result);
float div_result=calc.division(operand_1,operand_2);
System.out.println("result:"+div_result);
}
}
| 01fe22bca153/Calculator | Calci.java | 311 | /**
* The Calculator class in Java performs basic arithmetic operations such as addition, subtraction,
* multiplication, and division.
*/ | block_comment | en | false |
114609_0 |
/**
* @author Yiyang Hou
* Student ID: 1202537
* Username: yiyhou1
*/
public class Entry {
public static final int ENTRY_LENGTH = 7; // This is a constant, so can be set public and is
// also widely used across all classes.
private int entryId;
private int[] numbers = new int[ENTRY_LENGTH];
private String memberId = "";
private int prizeDivision = 0;
private int prize = 0;
public int getPrize() {
switch (prizeDivision) {
case 1:
this.prize = 50000;
break;
case 2:
this.prize = 5000;
break;
case 3:
this.prize = 1000;
break;
case 4:
this.prize = 500;
break;
case 5:
this.prize = 100;
break;
case 6:
this.prize = 50;
break;
default:
this.prize = 0;
break;
}
return prize;
}
public void setPrizeDivision(int division) {
this.prizeDivision = division;
}
public int getPrizeDivision() {
return prizeDivision;
}
public void setEntryId(int newEntryId) {
this.entryId = newEntryId;
}
public int getEntryId() {
return this.entryId;
}
public void setNumbers(int[] newNumbers) {
for (int i = 0; i < ENTRY_LENGTH; i++) {
numbers[i] = newNumbers[i];
}
}
public int[] getNumbers() {
return numbers;
}
public String getMemberId() {
return memberId;
}
public void setMemberId(String memberId) {
this.memberId = memberId;
}
/**
* Print method
*/
public void printNumbers() {
for (int number : numbers) {
if (number < 10) {
System.out.print(" " + number);
} else {
System.out.print(" " + number);
}
}
}
/**
*
* @param inputNumbers
*/
public void CreateNumbers(int[] inputNumbers) {
for (int i = 0; i < ENTRY_LENGTH; i++) {
numbers[i] = inputNumbers[i];
}
}
}
| yiyang-hou/COMP90041-Assignment2 | Entry.java | 651 | /**
* @author Yiyang Hou
* Student ID: 1202537
* Username: yiyhou1
*/ | block_comment | en | true |
114656_1 | import java.util.ArrayList;
/**
* This class runs on separate thread and manages the transaction queue and Block mining.
*/
public class Miner implements Runnable{
public static volatile P2PMessageQueue oIncomingMessageQueue = new P2PMessageQueue();
public static volatile boolean bAbortPoW = false;
public static volatile ArrayList<String> lstTransactionPool = new ArrayList<>();
int iBlockTxSize = 4;
public String sUsername;
/**
* PoW is where miner keeps trying incrementing nonce until hash begins with as many 0s as the difficulty specifies.
* @param oBlock
* @return
*/
public boolean doProofOfWork(Block oBlock) {
Integer nonce = 0;
oBlock.setNonce("0");
int iDiff = oBlock.getDifficulty();
String[] diff = new String[iDiff];
for (int x=0;x<diff.length;x++) {
diff[x] = "0";
}
String sDiff = diff.toString();
while (true) {
if (bAbortPoW = true) {
bAbortPoW = false;
System.out.println("[Miner] Aborted mining block due to already confirmed block");
return false;
}
else {
oBlock.setNonce(nonce.toString());
String hashed = oBlock.computeHash();
oBlock.setHash(hashed);
String[] sHashed = hashed.split("");
String[] aDiffCheck = new String[iDiff];
for(int x = 0; x<iDiff;x++) {
aDiffCheck[x]= sHashed[x];
}
String sDiffCheck = aDiffCheck.toString();
if (sDiff.compareTo(sDiffCheck) == 0) {
return true;
}
}
}
}
/**
* This thread monitors incoming messages, monitors the transaction queue, and mines Block if enough transactions collected.
* Called as part of Runnable interface and shouldn't be called directly by code.
*/
public void run() {
BlockchainUtil u = new BlockchainUtil();
u.p("Miner thread started.");
// *****************************
// *** Eternal Mining Loop *****
// Because miner always checking for next block to immediately work on.
while(true){
u.sleep(500);
while(oIncomingMessageQueue.hasNodes()){
P2PMessage oMessage = oIncomingMessageQueue.dequeue();
lstTransactionPool.add(oMessage.getMessage());
}
// Check if transaction pool full and lock if it is.
if (lstTransactionPool.size() >= iBlockTxSize) {
Block oBlock = new Block();
oBlock.setMinerUsername(sUsername);
oBlock.computeHash();
String sMerkleRoot = oBlock.computeMerkleRoot(lstTransactionPool);
oBlock.setMerkleRoot(sMerkleRoot);
boolean bMined = doProofOfWork(oBlock);
if(bMined){
// Notify connected node.
if(BlockchainBasics.sRemoteMinerIP != null){
P2PUtil.connectForOneMessage(BlockchainBasics.sRemoteMinerIP, BlockchainBasics.iRemoteMinerPort,
"mined");
}
u.p("");
u.p("***********");
u.p("BLOCK MINED");
u.p("nonce: " + oBlock.getNonce());
u.p("hash: " + oBlock.getHash());
u.p("");
u.p("Transactions:");
for(int x=0; x < lstTransactionPool.size(); x++){
u.p("Tx " + x + ": " + lstTransactionPool.get(x));
}
u.p("***********");
}
else{
u.p("[miner] Mining block failed.");
}
// Clear tx pool.
lstTransactionPool.clear();
}
}
}
}
| codeogabe/blockchain | Miner.java | 882 | /**
* PoW is where miner keeps trying incrementing nonce until hash begins with as many 0s as the difficulty specifies.
* @param oBlock
* @return
*/ | block_comment | en | true |
115195_12 | /**
* Dice Machine class that will roll a user's dice input
* @author Kyla
*/
package labs;
public class DiceMachine {
public static void main(String[] args)
{
//instantiate a new string
String str = new String ("The apple is red");
//instantiate a second string with removed strings
String str2 = new String(noSpace(str));
//print str2
System.out.println(str2);
}
/**
* method called noSpace that removes spaces from String
* @param str
* @return the String with no spaces
*/
public static String noSpace (String str)
{
//declare int spaces as 0 and keep track of the previous spaces
int spaces = 0;
//instantiate a new string called noSpace to store the string with no spaces
String noSpace = new String ("");
//create a for loop
//declare an int i as 0, and i will increase until it isn't less than the
//length of the string
//ensures the loop is run the correct amount of times
for (int i = 0; i<str.length(); i++)
{
//if statement to check each character in the string if the loop is true
//and if the character at the number at i is a space
if (str.charAt(i) == ' ')
{
//concatenate noSpace to include the String value from the number of prior and current spaces
//does not include the first character and those after the last space in the string
noSpace = noSpace.concat(str.substring(spaces + 1, i));
//reassign int spaces as i to store the current spaces
spaces = i;
}
}
//get the value of noSpace with concatenating
//includes the first character and those after the last space in the string
//keep outside of the loop
noSpace = String.valueOf(str.charAt(0)).concat(noSpace).concat(str.substring(spaces + 1));
//return noSpace
return noSpace;
}
}
| kykanemoto/ClassworkSubmissions | Task5.java | 497 | //and if the character at the number at i is a space | line_comment | en | true |
116403_0 | import java.util.Arrays;
/**
* Write a description of class U6q2 here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class U6q2
{
public static void main(String[] args) {
System.out.println("These are both valid ways to initialize an array");
int[] arr = {10,20,30,40,50,60,71,80,90,91};
System.out.println(Arrays.toString(arr));
}
public int[] transform(int[] a)
{
a[0]++;
a[2]++;
return a;
}
public void sampleMethod(int y)
{
int[] arr = {0, 0, 0, 0};
arr = transform(arr);
}
}
| leahkuruvila/Corrections6-10 | U6q2.java | 203 | /**
* Write a description of class U6q2 here.
*
* @author (your name)
* @version (a version number or a date)
*/ | block_comment | en | true |
116517_0 | import javax.swing.JFrame;
/**
This program displays the growth of an investment.
*/
public class InvestmentViewer3
{
public static void main(String[] args)
{
JFrame frame = new InvestmentFrame3();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
| noahlattari/Java-Appointment-Calendar | src/InvestmentViewer3.java | 84 | /**
This program displays the growth of an investment.
*/ | block_comment | en | false |
116891_4 |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
//import java.util.Scanner;
import java.util.*;
public class ChristmasSpruce
{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next(){
while (st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}
catch (IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
long nextLong(){
return Long.parseLong(next());
}
double nextDouble(){
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try{
str = br.readLine();
}
catch (IOException e){
e.printStackTrace();
}
return str;
}
}
public static void mul(int a,int b,int re) {
if(b>0) {
re+=a;
b--;
if(b==0)
System.out.println(re);
mul(a,b,re);
}
}
public static void merge(int[] a,int l,int m,int u) {
int n1 = m-l+1;
int n2 = u-m;
int[] left = new int[n1];
int []right = new int[n2];
int i,j,k;
for(i=0;i<n1;i++)
left[i]=a[i+l];
for(i=0;i<n2;i++)
right[i]=a[i+m+1];
i=0;
j=0;
k=l;
while(i<n1&&j<n2) {
if(left[i]<right[j]) {
a[k]=left[i];
i++;
}else {
a[k]=right[j];
j++;
}
k++;
}
while(i<n1) {
a[k]=left[i];
i++;
k++;
}
while(j<n2) {
a[k]=right[j];
k++;
j++;
}
}
public static void sort(int[] a,int l,int u) {
if(l<u) {
int m = l+((u-l)/2);
// m/=2;
sort(a,l,m);
sort(a,m+1,u);
merge(a,l,m,u);
}
}
public static void main(String[] args){
FastReader in=new FastReader();
int n = in.nextInt();
int[] ar = new int[n+11];
int i = 0 ;
int []con = new int[n+11];
int[] leaf = new int[n+11];
for(i=2;i<=n;i++) {
ar[i]=in.nextInt();
con[ar[i]]++;
}
Vector nonLeaf = new Vector();
for(i=1;i<=n;i++) {
if(con[i]==0) {
leaf[i]=1;
}
// System.out.println(con[i]+" "+leaf[i]);
if(leaf[i]==0)
nonLeaf.add(i);
}
// System.out.println("NONO LEAF");
// System.out.println(nonLeaf);
boolean ans = true;
// for leaf child leaf[i]=1
// for nonLeaf child leaf[i]=0
// for(i=1;i<n+1;i++)
// System.out.println(leaf[i]+" "+i);
// System.out.println("asdf");
int[] leafChild= new int[n+1];
for(i = 0;i<nonLeaf.size();i++) {
int nu = (int) nonLeaf.get(i);
int result = 0;
if(leafChild[nu]==0) {
for(int j = 2;j<=n;j++){
// System.out.println(ar[j]+" "+leaf[j]+" jj "+j);
if(ar[j]==nu&&leaf[j]==1) {
result++;
}
}
// System.out.println("RESULT "+result);
if(result<3)
result=-1;
leafChild[nu]=result;
}
if(leafChild[nu]<0) {
// System.out.println(leafChild[nu]+" "+nu);
ans = false;
break;
}
}
System.out.println(ans?"YES":"NO");
}
}
| deepesharya123/code | ChristmasSpruce.java | 1,293 | // System.out.println(nonLeaf); | line_comment | en | true |
117811_0 | /**
* Created by Scott Lindley on 10/13/2016.
*/
public class LG extends Remote{
public LG(boolean needsBatteries, boolean supportsUsb) {
super(needsBatteries, supportsUsb);
supportsBrands();
}
@Override
public void channelUp() {
System.out.println("LG remote went up one channel");
}
@Override
public void channelDown() {
System.out.println("LG remote went down one channel");
}
@Override
public void volumeUp() {
System.out.println("LG remote turned the volume up");
}
@Override
public void volumeDown() {
System.out.println("LG remote turned the volume down");
}
@Override
public boolean isRechargeable() {
if(needsBatteries()){
return false;
}
return true;
}
@Override
public void supportsBrands() {
getSupportedBrands().add("LG");
getSupportedBrands().add("Sharp");
getSupportedBrands().add("Toshiba");
}
@Override
public boolean isWaterProof() {
return true;
}
}
| ScottLindley/abstract-classes-and-interfaces-lab | src/LG.java | 266 | /**
* Created by Scott Lindley on 10/13/2016.
*/ | block_comment | en | true |
117913_23 | // 689. Maximum Sum of 3 Non-Overlapping Subarrays
// Given an integer array nums and an integer k, find three non-overlapping subarrays of length k with maximum sum and return them.
//
// Return the result as a list of indices representing the starting position of each interval (0-indexed). If there are multiple answers, return the lexicographically smallest one.
//
//
//
// Example 1:
//
// Input: nums = [1,2,1,2,6,7,5,1], k = 2
// Output: [0,3,5]
// Explanation: Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5].
// We could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger.
// Example 2:
//
// Input: nums = [1,2,1,2,1,2,1,2,1], k = 2
// Output: [0,2,4]
//
//
// Constraints:
//
// 1 <= nums.length <= 2 * 104
// 1 <= nums[i] < 216
// 1 <= k <= floor(nums.length / 3)
//
// Runtime: 2 ms, faster than 100.00% of Java online submissions for Maximum Sum of 3 Non-Overlapping Subarrays.
// Memory Usage: 42.1 MB, less than 49.32% of Java online submissions for Maximum Sum of 3 Non-Overlapping Subarrays.
class Solution {
public int[] maxSumOfThreeSubarrays(int[] nums, int k) {
int len = nums.length;
int[] left = new int[len];
int[] right = new int[len];
int[] sum = new int[len + 1];
for (int i = 1; i <= len; i++) sum[i] = sum[i - 1] + nums[i - 1];
int max = 0;
for (int i = 0; i <= len - k; i++) {
if (sum[i + k] - sum[i] > max) {
max = sum[i + k] - sum[i];
left[i] = i;
} else {
left[i] = left[i - 1];
}
}
max = 0;
for (int i = len - k; i >= 0; i--) {
if (sum[i + k] - sum[i] >= max) {
max = sum[i + k] - sum[i];
right[i] = i;
} else {
right[i] = right[i + 1];
}
}
max = 0;
int[] ans = new int[3];
for (int i = k; i <= len - 2 * k; i++) {
int total = sum[left[i - k] + k] - sum[left[i - k]] + sum[i + k] - sum[i] + sum[right[i + k] + k] - sum[right[i + k]];
if (total > max) {
max = total;
ans[0] = left[i - k];
ans[1] = i;
ans[2] = right[i + k];
}
}
return ans;
}
}
// left: max interval from index 0 to i - 1 ** i - 1 >= k
// mid: from i to i + k
// right: from i + k + 1 .. length - 1 | ishuen/leetcode | 689.java | 860 | // 1 <= k <= floor(nums.length / 3) | line_comment | en | true |
118798_0 | package mediaRentalManager;
/*
* The Album class represents an album in the media database
* The Album class extends the Media class, as it is a type of media
* In addition to a title and number of copies inherited from the Media
* class, an album also has an artist and a list of songs
*/
public class Album extends Media {
private String artist;
private String songs;
public Album(String title, int copiesAvailable, String artist,
String songs) {
super(title, copiesAvailable);
this.artist = artist;
this.songs = songs;
}
public String getArtist() {
return artist;
}
public String getSongs() {
return songs;
}
public String toString() {
return "Title: " + title + ", Copies Available: " +
copiesAvailable + ", Artist: " + artist + ", Songs: "
+ songs;
}
}
| probably-coding/media-rental-manager | Album.java | 224 | /*
* The Album class represents an album in the media database
* The Album class extends the Media class, as it is a type of media
* In addition to a title and number of copies inherited from the Media
* class, an album also has an artist and a list of songs
*/ | block_comment | en | false |
119135_0 | import krister.Ess.*;
import processing.core.*;
/*
WSound Class
_________________________________
Extends the Ess library by providing
more simple functions to deal with
sound :
* Remove Silence using a threshold
* Add Silence
* Draw a sound wave
* Normalize a sound ( change volume)
* Concatenate two sounds
* Save a sound to a file
*/
public class WSound {
private AudioChannel channel;
private PApplet p;
private String file;
// Constructor to create a WSound out of a file name
public WSound(String file, PApplet p) {
Ess.start(p);
this.p=p;
this.file=file;
this.channel=new AudioChannel(file);
}
// Constructor to create an empty WSound of size size
public WSound(int size, PApplet p) {
Ess.start(p);
this.p=p;
this.channel=new AudioChannel(size);
}
// Constructor to create a WSound out of another WSound
public WSound(WSound sound, PApplet p) {
Ess.start(p);
this.p=p;
this.channel=new AudioChannel(sound.channel.size,sound.channel.sampleRate);
p.arrayCopy(sound.channel.samples, this.channel.samples);
}
public void play() {
if(channel.size!=0)
channel.play();
}
public void playLoop() {
if(channel.size!=0)
channel.play(Ess.FOREVER);
}
// Saves the sound to a file
public void save(String filename) {
if(channel.size!=0)
channel.saveSound(filename);
}
public float maxAmplitude(){
return maximumAbs(channel.samples);
}
// Finds the maximum ( or absolute minimum whichever is bigger) of array values
public float maximumAbs(float [] array){
float maximum=array[0];
for ( int i=1; i<array.length; i++) {
if(p.abs(array[i])>maximum)
maximum=p.abs(array[i]);
}
return maximum;
}
// Finds the position of the first value above a threshold
private int findfirst(float[] array, float threshold) {
for(int i=0; i<array.length; i++)
if(p.abs(array[i])>threshold)
return i;
return 0;
}
// Finds the position of the last value above a threshold
private int findlast(float[] array, float threshold) {
for(int i=0; i<array.length; i++)
if(p.abs(array[array.length-i-1])>threshold)
return i;
return 0;
}
// Draws the wave
public void draw(int x, int y, int w, int h, int c) {
p.stroke(c);
float scale_x=w/((float)(channel.samples.length-1)); //width of the canvas divided by number of data points gives the horizontal scale
float scale_y=h/2; //height of the canvas divided by vertical range gives the vertical scale
for(int i=0; i<channel.size-1; i+=p.floor((float)p.width/w)) {
// y+h is y position of the bottom edge of the canvas, we're drawing in reverse
p.line(i*scale_x+x, (y+h)-(channel.samples[i]+1)*scale_y, (i+1)*scale_x+x, (y+h)-(channel.samples[i+1]+1)*scale_y);
}
}
// Elevates all amplitudes to a value proportional to the maximum given
public void normalize(float maximum) {
if (maximum<0 || maximum >1) {
maximum=1;
p.println("Maximum level out of bounds, setting to 1");
}
//Multiplier is the intensity divided by the maximum or the minimum whichever is bigger
float multiplier=maximum/maxAmplitude();
for (int i=0; i<channel.size; i++ ) {
channel.samples[i]*=multiplier;
}
}
// Removes silence (silence is all sound of amplitude lower than the given threshold)
public void trim(float threshold) {
if(threshold>0 && threshold < maxAmplitude()) {
// adjustChannel adds and removes samples to the sound
channel.adjustChannel(-findfirst(channel.samples, threshold),Ess.BEGINNING);
channel.adjustChannel(-findlast(channel.samples, threshold),Ess.END);
} else {
p.println("Threshold is larger than the maximum amplitude");
channel.initChannel(1);
}
}
// Adds a silence of duration time at the beginning or the end
public void addSilence(float time, boolean beginning) {
int framestoadd=(int)(time*channel.sampleRate); // calculate number of samples to add
float[] newsamples= new float[channel.size+framestoadd]; // create the new sound with added size
for(int i=0; i<channel.size+framestoadd; i++) {
// loop through the old sound and either add empty frames at the beginning or at the end
if(beginning) {
if(i>framestoadd) {
newsamples[i]=channel.samples[i-framestoadd];
} else {
newsamples[i]=0;
}
} else {
if(i>channel.size-1) {
newsamples[i]=0;
} else {
newsamples[i]=channel.samples[i];
}
}
}
channel.initChannel(channel.size+framestoadd);
channel.samples=newsamples;
}
//Concatenate two WSounds
public WSound concat(WSound sound2) {
WSound result=new WSound(channel.size+sound2.channel.size, p); //Create a new WSound with size equal to the sum of both sizes
// concatenate the first samples array with the second one and put them in the new WSound's samples array
// could've looped through the result samples array and added both arrays one sample at a time but the "concat" function is way cleaner
result.channel.samples=p.concat(channel.samples, sound2.channel.samples);
result.channel.sampleRate(sound2.channel.sampleRate);
return result;
}
public int getDuration() {
return channel.duration;
}
public String getFileName() {
return file;
}
public boolean getState() {
return channel.state==Ess.PLAYING;
}
} | wassgha/AudioEditorProcessing | WSound.java | 1,529 | /*
WSound Class
_________________________________
Extends the Ess library by providing
more simple functions to deal with
sound :
* Remove Silence using a threshold
* Add Silence
* Draw a sound wave
* Normalize a sound ( change volume)
* Concatenate two sounds
* Save a sound to a file
*/ | block_comment | en | false |
119482_0 |
/**
* Ask the user to choose a phone from the list of at least 5 phones. You must use one switch-case and one conditional statement.
* Name of the phone they are purchasing:
* State where the product is shipped:
*
* Sarah Poravanthattil
* 3/21/22
*/
import java.util.Scanner;
public class PhoneSales
{
public static void main(String[]args){
System.out.println("List of phones: iPhone 6, iPhone 7, iPhone 8, iPhone XR, iPhone 13");
Scanner input = new Scanner(System.in);
System.out.println("Choose one of the options above: ");
String phone = input.nextLine();
System.out.println("What state are you shipping to?(New Jersey;Deleware;Pennsylvania): ");
String state = input.nextLine();
double phonecost = 0;
double tax = 0;
if(phone.equals("iPhone 6")){
phonecost = 199.99;
}
if (phone.equals("iPhone 7")){
phonecost = 499.99;
}
if (phone.equals("iPhone 8")){
phonecost = 599.99;
}
if (phone.equals("iPhone XR")){
phonecost = 749.99;
}
if (phone.equals("iPhone 13")){
phonecost = 899.99;
}
switch(state){
case "New Jersey":
tax = phonecost * 1.06625;
break;
case "Pennsylvania":
tax = phonecost * 1.03;
break;
case "Deleware":
tax = phonecost;
break;
default:
tax = phonecost * 1.075;
}
System.out.println("You bought the " + phone + " and it will be shipped to " + state +".");
System.out.printf("The total cost = $ %.2f%n", tax);
}
}
| mohithn04/APCompSci | PhoneSales.java | 494 | /**
* Ask the user to choose a phone from the list of at least 5 phones. You must use one switch-case and one conditional statement.
* Name of the phone they are purchasing:
* State where the product is shipped:
*
* Sarah Poravanthattil
* 3/21/22
*/ | block_comment | en | false |
119574_28 | //
// DOCUMENTACION INTERNA
//
// Nombre del programa: INTERPRETELISP.JAVA
//
// Fin en Mente:
// Utilizando java y los recursos dados por la Universidad Del Valle, se realizara un programa el cual sera capaz de interpretar el lenguaje LISP.
//
//
// Programadores: Olivier Viau 23544
// Fabian Morales 23267
// Renato Rojas 23813
// Belen Monterroso 231497
//
// Lenguaje: Java
//
// Recursos:
// https://www.geeksforgeeks.org/throw-throws-java/
// https://docs.oracle.com/javase%2F7%2Fdocs%2Fapi%2F%2F/org/omg/CORBA/Context.html
// ChatGpt3 para funciones regulares y validaciones
//
// Historia de Modificaciones:
//
// [000] 28/02/2024 Programa nuevo
// [001] 29/02/2024 Validador de paréntesis
// [002] 4/3/24 Ideas defunc
// [003] 4/3/24 SetQ
// [004] 5/3/24 palabras reservadas
// [005] 7/3/24 Diccionario
// [006] 8/3/24 Guardar funciones
// [007] 8/3/24 Quote
// [008] 11/3/24 List
// [009] 11/3/24 Atom
// [010] 11/3/24 Defunc completo
public class main {
public static void main(String[] args) throws Exception {
Vista vista=new Vista();
vista.menu();
}
}
| 0liRem/LispJavaInterpreter | main.java | 510 | // [005] 7/3/24 Diccionario | line_comment | en | true |
119576_11 | /**
* Ideas:
* Don't trade early on (or make really wide markets) before you can estimate volatility
* Based on estimated volatility, make spread around fair price
* Have different fair prices based on which exchange it is?
*
*/
import java.util.ArrayList;
import org.chicago.cases.AbstractExchangeArbCase;
import org.chicago.cases.arb.Quote;
import com.optionscity.freeway.api.IDB;
import com.optionscity.freeway.api.IJobSetup;
public class arbkai extends AbstractExchangeArbCase {
class MyArbImplementation implements ArbCase {
// Note...the IDB will be used to save data to the hard drive and access it later
// This will be useful for retrieving data between rounds
private IDB myDatabase;
int factor;
int position;
double[] desiredRobotPrices = new double[2];
double[] desiredSnowPrices = new double[2];
double pnl;
double spent;
double fair;
double aggression;
double threshold;
double edge;
double minSpread;
double positionConstant;
double upperBound;
double lowerBound;
double center;
int numAtLower = 0;
int numAtUpper = 0;
int runAlgo;
int timeStep = 5; //first time this will be incremented is at 5
int totalTrades; //decent metric of how aggressive we're being
//To find how volatile something is, keep track of the last 20 or so ticks.
//Goes from most recent to least recent, so index 0 is the most recent one.
final int numTrackedQuotes = 20;
ArrayList<Quote> robotTrackedQuotes = new ArrayList<Quote>();
ArrayList<Quote> snowTrackedQuotes = new ArrayList<Quote>();
ArrayList<Double> fairPrices = new ArrayList<Double>();
public void addVariables(IJobSetup setup) {
// Registers a variable with the system.
setup.addVariable("aggression", "aggressiveness factor", "double", "0.75");
setup.addVariable("threshold", "threshold on difference between two exchanges before trading", "double", "1.0");
setup.addVariable("edge", "To DO NOTHING, make this 200 and adjust LOWERBOUND and UPPERBOUND to 0, 200", "double", "0.20");
setup.addVariable("positionConstant", "How much to fade", "double", "0.10");
setup.addVariable("minSpread", "minimum size of spread (for round 3 should be 3 for safety)", "double", "3.0");
setup.addVariable("runAlgo", "0 to run alg, 1/2/3 for +-20/15/10", "int", "0");
setup.addVariable("upperBound", "R1: 120, R2: 160, R3: 115", "double", "120.0");
setup.addVariable("lowerBound", "R1: 80, R2: 40, R3: 85", "double", "80.0");
setup.addVariable("center", "Guess is 100", "double", "100.0");
}
public void initializeAlgo(IDB database) {
// Databases can be used to store data between rounds
myDatabase = database;
database.put("currentPosition", 0);
aggression = getDoubleVar("aggression");
threshold = getDoubleVar("threshold");
edge = getDoubleVar("edge");
positionConstant = getDoubleVar("positionConstant");
minSpread = getDoubleVar("minSpread");
runAlgo = getIntVar("runAlgo");
upperBound = getDoubleVar("upperBound");
lowerBound = getDoubleVar("lowerBound");
center = getDoubleVar("center");
}
@Override
public void fillNotice(Exchange exchange, double price, AlgoSide algoside) {
log("QUOTE FILLED at a price of " + price + " on " + exchange + " as a " + algoside);
log("Trade happened at time" + (timeStep-5));
if(algoside == AlgoSide.ALGOBUY){
position += 1;
spent+=price;
if (Math.abs(price-lowerBound)<=0.1) {
numAtLower++;
}
}
else{
position -= 1;
spent-=price;
if (Math.abs(price-upperBound)<=0.1) {
numAtUpper++;
}
}
totalTrades++;
log ("TOTAL TRADES " + totalTrades);
//log ("TIME IS T=" + timeStep);
pnl = position*fair-spent;
if (position == 0) {
log("POSITION 0! " + pnl);
}
else {
log("CURRENT NET PNL IS: " + pnl + " Position: " + position);
}
}
@Override
public void positionPenalty(int clearedQuantity, double price) {
log("I received a position penalty with " + clearedQuantity + " positions cleared at " + price);
position -= clearedQuantity;
spent -= clearedQuantity*price;
}
@Override
public void newTopOfBook(Quote[] quotes) {
timeStep++;
log ("TIME: " + timeStep);
for (Quote quote : quotes) {
log("NEW BID of " + quote.bidPrice + ", and ask of " + quote.askPrice + " from " + quote.exchange);
}
double robotMid = (quotes[0].bidPrice+quotes[0].askPrice)/2.0;
double snowMid = (quotes[1].bidPrice+quotes[1].askPrice)/2.0;
fair = (robotMid+snowMid)/2.0;
int size = robotTrackedQuotes.size();
if (size > 20) {
robotTrackedQuotes.remove(0);
snowTrackedQuotes.remove(0);
fairPrices.remove(0);
}
robotTrackedQuotes.add(quotes[0]);
snowTrackedQuotes.add(quotes[1]);
fairPrices.add(fair);
size = robotTrackedQuotes.size();
/**
* Calcuate volatility here based on robotTrackedQuotes and snowTrackedQuotes
*/
double maxChange = 0.0;
double currentChange = 0.0;
for (int i = 0; i <= Math.min(size-6,10) ; i ++) {
currentChange = fairPrices.get(size-1-i)-fairPrices.get(size-6-i);
maxChange = Math.max(maxChange,currentChange);
}
for (int i = 1; i < Math.min(size,5); i ++) {
currentChange = fairPrices.get(size-1)-fairPrices.get(size-1-i);
maxChange = Math.max(maxChange, currentChange*5/i);
}
double adjustBasedOnPosition = 0.0;
int selfImposedPositionLimit = 160;
if (timeStep > 750) {
int helperVar = (timeStep-750)/10;
selfImposedPositionLimit = Math.abs(160-helperVar*6);
}
if (position >= selfImposedPositionLimit) {
adjustBasedOnPosition = (-position+selfImposedPositionLimit)*positionConstant;
}
//log ("ADJUSTING" + adjustBasedOnPosition);
if (position <= -selfImposedPositionLimit) {
adjustBasedOnPosition = (-position-selfImposedPositionLimit)*positionConstant;
}
//log ("ADJUSTING" + adjustBasedOnPosition);
double netpnl = fair*position - spent;
log ("PNL: " + netpnl + " Position: " + position);
double dontTrade = 30.00;
//log ("My fair price bb: " + fair);
if (numAtLower>10 && netpnl<0) {
numAtLower = 0;
lowerBound -= 5;
}
if (numAtUpper>10 && netpnl<0) {
numAtUpper = 0;
upperBound += 5;
}
//double threshold = 1.0;
if (Math.abs(robotMid-snowMid) > threshold) {
log ("Arbitrage opportunity!");
dontTrade = 0.0;
}
double adjustedFair = fair + adjustBasedOnPosition;
double spreadSizeOneDirection = Math.max(aggression*maxChange+edge+dontTrade, minSpread/2);
log ("Spread size: " + spreadSizeOneDirection);
if (runAlgo == 1) {
adjustedFair = center;
spreadSizeOneDirection = 20;
}
if (runAlgo == 2) {
adjustedFair = center;
spreadSizeOneDirection = 15;
}
if (runAlgo == 3) {
adjustedFair = center;
spreadSizeOneDirection = 10;
}
if (position >= 190) {
desiredRobotPrices[0] = 0;
desiredRobotPrices[1] = Math.max(quotes[0].bidPrice, quotes[1].bidPrice);
desiredSnowPrices[0] = 0;
desiredSnowPrices[1] = Math.max(quotes[0].bidPrice, quotes[1].bidPrice);
}
else if (position <= -190) {
desiredRobotPrices[0] = Math.min(quotes[0].askPrice, quotes[1].askPrice);
desiredRobotPrices[1] = 500.0;
desiredSnowPrices[0] = Math.min(quotes[0].askPrice, quotes[1].askPrice);
desiredSnowPrices[1] = 500.0;
}
else {
desiredRobotPrices[0] = Math.max(adjustedFair-spreadSizeOneDirection, lowerBound);
desiredRobotPrices[1] = Math.min(adjustedFair+spreadSizeOneDirection, upperBound);
desiredSnowPrices[0] = Math.max(adjustedFair-spreadSizeOneDirection, lowerBound);
desiredSnowPrices[1] = Math.min(adjustedFair+spreadSizeOneDirection, upperBound);
}
}
@Override
public Quote[] refreshQuotes() {
Quote[] quotes = new Quote[2];
quotes[0] = new Quote(Exchange.ROBOT, desiredRobotPrices[0], desiredRobotPrices[1]);
quotes[1] = new Quote(Exchange.SNOW, desiredSnowPrices[0], desiredSnowPrices[1]);
log("MY BID IS " + desiredRobotPrices[0] + ", and my ask is " + desiredRobotPrices[1] + " on both exchanges");
return quotes;
}
}
@Override
public ArbCase getArbCaseImplementation() {
return new MyArbImplementation();
}
}
| juesato/uchig | src/arbkai.java | 2,504 | //log ("ADJUSTING" + adjustBasedOnPosition); | line_comment | en | true |
119593_3 | import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.ggp.base.player.gamer.exception.GamePreviewException;
import org.ggp.base.player.gamer.statemachine.StateMachineGamer;
import org.ggp.base.util.game.Game;
import org.ggp.base.util.statemachine.MachineState;
import org.ggp.base.util.statemachine.Move;
import org.ggp.base.util.statemachine.Role;
import org.ggp.base.util.statemachine.StateMachine;
import org.ggp.base.util.statemachine.exceptions.GoalDefinitionException;
import org.ggp.base.util.statemachine.exceptions.MoveDefinitionException;
import org.ggp.base.util.statemachine.exceptions.TransitionDefinitionException;
/***
* This class contains all the methods needed to complete the class (as based on the notes)
* at a minimum level. To implement further extensions to your player,
* you are free to dig into the code base and change whatever you want to optimize
* and improve your player.
*
* You are free to use this class as much or as little as you want. It is here to provide
* an interface to the code base that makes implementing ideas from the notes easier. It
* is up to you to improve your player beyond this. Good luck!
*
* @author Jeffrey Barratt
*/
public abstract class GGPlayer extends StateMachineGamer {
/**
* Finds the next state after the provided state, given the list of moves was played
* by the players in the game.
*/
public MachineState findNext(List<Move> actions, MachineState s, StateMachine m)
throws TransitionDefinitionException {
return m.getNextState(s, actions);
}
/**
* Finds all legal moves for the given role in the given state.
*/
public List<Move> findLegals(Role r, MachineState s, StateMachine m)
throws MoveDefinitionException {
return m.getLegalMoves(s, r);
}
/**
* Finds all combinations of moves that can be played, given that the role provided played
* the action provided. (e.g. if the tic tac toe board position was filled except for the
* top left and bottom right, and it was O to play, and this method was called with
* findLegalJoints([Role X], [noop], current, machine), it would return [[noop, (place 1 1)], [noop, (place 3 3)]],
* where noop, (place 1 1) and (place 3 3) are all moves.
*
* This method is useful for the minscore method in both MiniMax/AlphaBeta and MCTS
*/
public List<List<Move>> findLegalJoints(Role r, Move action, MachineState s, StateMachine m)
throws MoveDefinitionException {
return m.getLegalJointMoves(s, r, action);
}
/**
* Finds all possible actions that are available to the given role. This includes illegal
* moves as well as legal ones for any given state.
*/
public List<Move> findActions(Role r, StateMachine m)
throws MoveDefinitionException {
return m.findActions(r);
}
/**
* Returns true if the given state is a terminal state, false otherwise.
*/
public boolean findTerminalp(MachineState s, StateMachine m) {
return m.findTerminalp(s);
}
/**
* Returns the current utility the given role has in the given state.
*/
public int findReward(Role r, MachineState s, StateMachine m)
throws GoalDefinitionException {
return m.getGoal(s, r);
}
/**
* Returns a (possibly empty) list of all players in the game that are not the given role.
*/
public List<Role> findOpponents(Role r, StateMachine m) {
List<Role> roles = new ArrayList<Role>(m.getRoles());
roles.remove(r);
return roles;
}
/**
* Simulates a game with random moves until a terminal state is reached.
* Useful for Monte-Carlo implementations.
*/
Random gen = null;
public int depthCharge(Role r, MachineState s, StateMachine m)
throws MoveDefinitionException, TransitionDefinitionException, GoalDefinitionException {
if (gen == null) gen = new Random();
MachineState current = s;
while (!m.findTerminalp(current)) {
List<List<Move>> moves = m.getLegalJointMoves(current);
current = m.getNextState(current, moves.get(gen.nextInt(moves.size())));
}
return m.findReward(r, current);
}
/*
* Below are interfaces for the GGPlayer class to interact with the StateMachineGamer class
* in a much clearer and more consistent way. You will not need to use the code below.
*/
public abstract void start(long timeout)
throws TransitionDefinitionException, MoveDefinitionException, GoalDefinitionException;
public abstract Move play(long timeout)
throws TransitionDefinitionException, MoveDefinitionException, GoalDefinitionException;
@Override
public abstract void abort();
@Override
public abstract void stop();
@Override
public void stateMachineMetaGame(long timeout)
throws TransitionDefinitionException, MoveDefinitionException, GoalDefinitionException {
start(timeout);
}
@Override
public Move stateMachineSelectMove(long timeout)
throws TransitionDefinitionException, MoveDefinitionException, GoalDefinitionException {
return play(timeout);
}
@Override
public void stateMachineAbort() {abort();}
@Override
public void stateMachineStop() {stop();}
/**
* Not currently used in the current GGP standard.
*/
@Override
public void preview(Game g, long timeout) throws GamePreviewException {}
}
| super-goodman/ggp-base | player/GGPlayer.java | 1,409 | /**
* Finds all combinations of moves that can be played, given that the role provided played
* the action provided. (e.g. if the tic tac toe board position was filled except for the
* top left and bottom right, and it was O to play, and this method was called with
* findLegalJoints([Role X], [noop], current, machine), it would return [[noop, (place 1 1)], [noop, (place 3 3)]],
* where noop, (place 1 1) and (place 3 3) are all moves.
*
* This method is useful for the minscore method in both MiniMax/AlphaBeta and MCTS
*/ | block_comment | en | true |
120018_2 | /*
* PizzaManager Pizza Class
* CSS 162, Final Project
* Summer 2014
* Author: Rob Nash
* Student: Todd Lynam
*/
//Mozzarella class extends Cheese
//Mozzarella is a shallow class and only contains static final values and passes them to the Cheese super constructor
public class Mozzarella extends Cheese{
public static final int calories = 100;
public static final Money cost = new Money(0,75);
public static final String description = "Mozzarella sticks sliced";
//Constructor calls Cheese constructor with super
public Mozzarella() {
super(description, cost, calories);
}
}
| tlynam/Data-Structures-Project-Final | Mozzarella.java | 182 | //Mozzarella is a shallow class and only contains static final values and passes them to the Cheese super constructor | line_comment | en | true |
120089_2 | package com.selenium.s1;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import io.github.bonigarcia.wdm.WebDriverManager;
public class d43 {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
WebDriverManager.chromedriver().setup();
ChromeOptions co=new ChromeOptions();
co.addArguments("--remote-allow-origins=*");
WebDriver driver=new ChromeDriver(co);
driver.get("https://j2store.net/free/");
driver.manage().window().maximize();
Thread.sleep(3000);
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.scrollBy(0,1000)");
WebElement clo=driver.findElement(By.xpath("//*[@id=\"Mod112\"]/div/div/ul/li[1]/h4/a"));
clo.click();
driver.navigate().back();
Thread.sleep(3000);
driver.navigate().forward();
Thread.sleep(3000);
driver.navigate().refresh();
Thread.sleep(3000);
driver.close();
}
}
| Naveenm03/selenium1 | d43.java | 362 | //*[@id=\"Mod112\"]/div/div/ul/li[1]/h4/a"));
| line_comment | en | true |
120147_7 | /******************************************************************************
*
* A graph, implemented using a Map of sets.
* Self-loops allowed.
*
* The <tt>Graph</tt> class represents an undirected graph of vertices,
* represented as integer values.
* It supports the following operations:
* - add a vertex to the graph,
* - add an edge to the graph,
* - iterate over all of the vertices adjacent to a vertex.
* It also provides methods for returning the number of vertices <em>V</em>,
* the number of edges <em>E</em>, the degree of a vertex, and a String
* representation of the Graph.
*
*/
import java.util.*;
public class Graph {
private static final String NEWLINE = System.getProperty("line.separator");
private int V;
private int E;
private Map<Integer, Set<Integer>> adj;
/**
* Initializes an empty graph
*/
public Graph()
{
this.V = 0;
this.E = 0;
adj = new TreeMap<>();
}
public void setter (Map adj1)
{
adj = adj1;
}
/**
* Returns the number of vertices in this graph.
*
* @return the number of vertices in this graph
*/
public int vertices()
{
return V;
}
/**
* Returns the number of edges in this graph.
*
* @return the number of edges in this graph
*/
public int edges()
{
return E;
}
/**
* Ensures the argument is a valid vertex in the graph
*
* @param v one vertex in the graph
* @throws IllegalArgumentException if v is not a valid vertex
*/
private void validateVertex(int v)
{
if (!adj.containsKey(v))
throw new IllegalArgumentException("Invalid Vertex " + v);
}
/**
* Adds the vertex v to this graph
*
* @param v one vertex in the graph
* @return true if v was added, false otherwise
*/
public boolean addVertex(int v)
{
if (adj.containsKey(v))
return false;
V++;
Set<Integer> neighbors = new HashSet<>();
adj.put(v, neighbors);
return true;
}
/**
* Adds the undirected edge v-w to this graph.
* The arguments must be valid vertices in the graph.
* @param v one vertex in the edge
* @param w the other vertex in the edge
* @throws IllegalArgumentException if either vertex does not exist
*/
public void addEdge(int v, int w)
{
validateVertex(v);
validateVertex(w);
E++;
adj.get(v).add(w);
adj.get(w).add(v);
}
/**
* Returns the vertices adjacent to vertex <tt>v</tt>.
*
* @param v the vertex
* @return an Iterator containing the vertices adjacent to vertex <tt>v</tt>
* @throws IllegalArgumentException if v is not a valid vertex
*/
public Iterator<Integer> getAdjacent(int v)
{
validateVertex(v);
return adj.get(v).iterator();
}
/**
* Returns the degree of vertex <tt>v</tt>.
*
* @param v the vertex
* @return the degree of vertex <tt>v</tt>
* @throws IllegalArgumentException if v is not a valid vertex
*/
public int degree(int v)
{
validateVertex(v);
return adj.get(v).size();
}
/**
* Returns a string representation of this graph.
*
* @return the number of vertices <em>V</em>, followed by the number of edges <em>E</em>,
* followed by the <em>V</em> adjacency lists
*/
public String toString()
{
StringBuilder s = new StringBuilder();
s.append(V + " vertices, " + E + " edges " + NEWLINE);
for (int v: adj.keySet())
{
s.append(v + ": ");
for (int w : adj.get(v))
{
s.append(w + " ");
}
s.append(NEWLINE);
}
return s.toString();
}
} | alphago004/PathFinder | Graph.java | 969 | /**
* Returns the vertices adjacent to vertex <tt>v</tt>.
*
* @param v the vertex
* @return an Iterator containing the vertices adjacent to vertex <tt>v</tt>
* @throws IllegalArgumentException if v is not a valid vertex
*/ | block_comment | en | true |
121057_14 |
package demo;
import java.util.Date;
public class Home extends javax.swing.JFrame {
public Home() {
initComponents();
Date dt=new Date();
// dateTF.setText("Date: "+dt);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
desktopPane = new javax.swing.JDesktopPane();
l2 = new javax.swing.JLabel();
l1 = new javax.swing.JLabel();
l3 = new javax.swing.JLabel();
menuBar = new javax.swing.JMenuBar();
Stock = new javax.swing.JMenu();
GMI = new javax.swing.JMenuItem();
Cal = new javax.swing.JMenu();
Normal = new javax.swing.JMenuItem();
Bill = new javax.swing.JMenu();
customer = new javax.swing.JMenuItem();
jMenu1 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBounds(new java.awt.Rectangle(214, 214, 0, 0));
desktopPane.setBackground(new java.awt.Color(0, 17, 218));
desktopPane.setBorder(new javax.swing.border.MatteBorder(new javax.swing.ImageIcon(getClass().getResource("/demo/Two-Businessmen-Shaking-Hands-Article-201806211800.jpg")))); // NOI18N
desktopPane.setAlignmentX(1.0F);
desktopPane.setAlignmentY(1.0F);
desktopPane.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
desktopPane.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
l2.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
l2.setText(" BALAJI LADIES WEAR MANAGEMENT PORTAL");
desktopPane.add(l2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 190, 860, 70));
l1.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
l1.setText("WELCOME TO ");
desktopPane.add(l1, new org.netbeans.lib.awtextra.AbsoluteConstraints(280, 100, 290, 70));
l3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/demo/Two-Businessmen-Shaking-Hands-Article-201806211800.jpg"))); // NOI18N
desktopPane.add(l3, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 0, -1, -1));
Stock.setForeground(new java.awt.Color(0, 0, 153));
Stock.setMnemonic('f');
Stock.setText("Stock");
Stock.setFont(new java.awt.Font("Segoe UI", 1, 24)); // NOI18N
Stock.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
StockActionPerformed(evt);
}
});
GMI.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_G, java.awt.event.InputEvent.CTRL_MASK));
GMI.setFont(new java.awt.Font("Segoe UI", 1, 24)); // NOI18N
GMI.setForeground(new java.awt.Color(204, 0, 102));
GMI.setMnemonic('o');
GMI.setText("Garments");
GMI.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
GMIActionPerformed(evt);
}
});
Stock.add(GMI);
menuBar.add(Stock);
Cal.setForeground(new java.awt.Color(0, 0, 153));
Cal.setMnemonic('e');
Cal.setText("Calculator");
Cal.setFont(new java.awt.Font("Segoe UI", 1, 24)); // NOI18N
Normal.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK));
Normal.setFont(new java.awt.Font("Segoe UI", 1, 24)); // NOI18N
Normal.setForeground(new java.awt.Color(204, 0, 51));
Normal.setMnemonic('t');
Normal.setText("Normal");
Normal.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
NormalActionPerformed(evt);
}
});
Cal.add(Normal);
menuBar.add(Cal);
Bill.setForeground(new java.awt.Color(0, 0, 153));
Bill.setMnemonic('h');
Bill.setText("Bill");
Bill.setFont(new java.awt.Font("Segoe UI", 1, 24)); // NOI18N
customer.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_B, java.awt.event.InputEvent.SHIFT_MASK));
customer.setFont(new java.awt.Font("Segoe UI", 1, 24)); // NOI18N
customer.setForeground(new java.awt.Color(204, 0, 51));
customer.setMnemonic('c');
customer.setText("Customer Bill");
customer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
customerActionPerformed(evt);
}
});
Bill.add(customer);
menuBar.add(Bill);
jMenu1.setForeground(new java.awt.Color(0, 0, 153));
jMenu1.setText("Back");
jMenu1.setFont(new java.awt.Font("Segoe UI", 1, 24)); // NOI18N
jMenuItem1.setFont(new java.awt.Font("Segoe UI", 1, 24)); // NOI18N
jMenuItem1.setForeground(new java.awt.Color(204, 0, 51));
jMenuItem1.setText("Go Back");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem1);
menuBar.add(jMenu1);
setJMenuBar(menuBar);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(desktopPane, javax.swing.GroupLayout.PREFERRED_SIZE, 857, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(desktopPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
desktopPane.getAccessibleContext().setAccessibleDescription("");
pack();
}// </editor-fold>//GEN-END:initComponents
private void GMIActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_GMIActionPerformed
new Garments().setVisible(true);
}//GEN-LAST:event_GMIActionPerformed
private void StockActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_StockActionPerformed
}//GEN-LAST:event_StockActionPerformed
private void NormalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NormalActionPerformed
new Normal_Calc().setVisible(true);
}//GEN-LAST:event_NormalActionPerformed
private void customerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_customerActionPerformed
new customer_bill().setVisible(true);
}//GEN-LAST:event_customerActionPerformed
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
new Login().setVisible(true);
}//GEN-LAST:event_jMenuItem1ActionPerformed
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Home().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenu Bill;
private javax.swing.JMenu Cal;
private javax.swing.JMenuItem GMI;
private javax.swing.JMenuItem Normal;
private javax.swing.JMenu Stock;
private javax.swing.JMenuItem customer;
private javax.swing.JDesktopPane desktopPane;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JLabel l1;
private javax.swing.JLabel l2;
private javax.swing.JLabel l3;
private javax.swing.JMenuBar menuBar;
// End of variables declaration//GEN-END:variables
}
| SomyaAgr/Shop-Management-Software | Home.java | 2,577 | // </editor-fold>//GEN-END:initComponents | line_comment | en | true |
121252_0 |
import java.util.*;
class bubbleSort{
public static void main(String[] args){
int[] arr = {9,8,7,6,5,4,3,2,1};
int n = arr.length;
int tmp;
/*
This sorting algorithm is the simplest sorting algorithm that works by repeatedly
swapping the adjacent elements if they are in the wrong order.
If we have total N elements, then we need to repeat the above process for N-1 times.
We can use Bubble Sort as per below constraints :
It works well with large datasets where the items are almost sorted because it
takes only one iteration to detect whether the list is sorted or not.
But if the list is unsorted to a large extend
then this algorithm holds good for small datasets or lists.
This algorithm is fastest on an extremely small or nearly sorted set of data.
***Worst and Average Case Time Complexity: O(n*n). Worst case occurs when array is reverse sorted.
Best Case Time Complexity: O(n). Best case occurs when array is already sorted.
Auxiliary Space: O(1)
Boundary Cases: Bubble sort takes minimum time (Order of n) when elements are already sorted.
Sorting In Place: Yes
Stable: Yes****(IMP)
*/
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(arr[i]<arr[j]){
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
for(int i=0;i<n;i++){
System.out.print(arr[i]);
}
}
}
| TusharKukra/Hacktoberfest2021-EXCLUDED | bubblesort.java | 393 | /*
This sorting algorithm is the simplest sorting algorithm that works by repeatedly
swapping the adjacent elements if they are in the wrong order.
If we have total N elements, then we need to repeat the above process for N-1 times.
We can use Bubble Sort as per below constraints :
It works well with large datasets where the items are almost sorted because it
takes only one iteration to detect whether the list is sorted or not.
But if the list is unsorted to a large extend
then this algorithm holds good for small datasets or lists.
This algorithm is fastest on an extremely small or nearly sorted set of data.
***Worst and Average Case Time Complexity: O(n*n). Worst case occurs when array is reverse sorted.
Best Case Time Complexity: O(n). Best case occurs when array is already sorted.
Auxiliary Space: O(1)
Boundary Cases: Bubble sort takes minimum time (Order of n) when elements are already sorted.
Sorting In Place: Yes
Stable: Yes****(IMP)
*/ | block_comment | en | false |
121456_7 | import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Use main to run and test the below functions
}
/**
* Puts the elements in the arrayList in sorted order from smallest to greatest.
* This function uses selection sort to sort the arrayList.
* @param arrayList the ArrayList to be sorted. arrayList cannot contain duplicates
*/
public static void selectionSort(ArrayList<Integer> arrayList) {
throw new UnsupportedOperationException("SelectionSort() has not been implemented yet");
}
/**
* Returns the index that value is located in the arrayList. This function searches linearly in
* the arrayList to find the value.
* @param arrayList the ArrayList containing the list of values to search. arrayList cannot contain duplicates
* @param value the value we are looking for in the array list
*/
public static int linearSearch(ArrayList<Integer> arrayList, int value) {
throw new UnsupportedOperationException("LinearSearch() has not been implemented yet");
}
/**
* Returns the index that value is located in the arrayList. This function uses binary search in
* the arrayList to find the value.
* @param arrayList the ArrayList containing the list of values to search. THIS ARRAYLIST MUST BE
* IN SORTED ORDER. arrayList cannot contain duplicates
* @param value the value we are looking for in the array list
*/
public static int binarySearch(ArrayList<Integer> arrayList, int value) {
throw new UnsupportedOperationException("LinearSearch() has not been implemented yet");
}
/**
* Puts the elements in the arrayList in sorted order from smallest to greatest.
* This function uses MergeSort to sort the arrayList.
* @param arrayList the ArrayList to be sorted. arrayList cannot contain duplicates
*/
public static void mergeSort(ArrayList<Integer> arrayList) {
}
/**
* This function is a helper function used to help you implement mergeSort.
* The function sorts the portion of arrayList specified by the range [lo, hi). The range
* includes lo but excludes hi (arrayList[lo] is the first element in the range, but
* arrayList[hi] is the first element after the last element in the range).
* @param arrayList the ArrayList to be sorted.
* @param lo the index of the first element in the range
* @param hi the index of the last element in the range + 1.
*/
public static void sort(ArrayList<Integer> arrayList, int lo, int hi) {
//arrayList.merge();
}
/**
* This function is a helper function used to help you implement mergeSort.
* The function merges two consecutive, sorted ranges in the arrayList into one sorted range. The ranges
* are specified as [lo, mid) and [mid, hi). Each range includes the first element, but excludes
* the last element (the same way as in sort()).
* @param arrayList the ArrayList to be sorted.
* @param lo the index of the first element in the first range
* @param mid the boundary point of the two ranges. arrayList[mid] is in the second range.
* @param hi the index of the last element in the second range + 1.
*/
public static void merge(ArrayList<Integer> arrayList, int lo, int mid, int hi) {
ArrayList<Integer> newArray = new ArrayList<Integer>();
int x = lo;
int y = mid;
int z = hi;
}
}
| HolyNamesAcademy/unit7-mergesort-laurenmiller00 | src/Main.java | 793 | /**
* This function is a helper function used to help you implement mergeSort.
* The function merges two consecutive, sorted ranges in the arrayList into one sorted range. The ranges
* are specified as [lo, mid) and [mid, hi). Each range includes the first element, but excludes
* the last element (the same way as in sort()).
* @param arrayList the ArrayList to be sorted.
* @param lo the index of the first element in the first range
* @param mid the boundary point of the two ranges. arrayList[mid] is in the second range.
* @param hi the index of the last element in the second range + 1.
*/ | block_comment | en | false |
121502_3 |
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import java.io.IOException;
import java.awt.Graphics2D;
public class Card {
private int suit; //suit of the card (Clubs[0], Diamonds[1], Hearts[3], or Spades[4])
private int rank; //rank of the card (Ace[0], 2[1], 3[2], 4[3], 5[4], 6[5], 7[6], 8[7], 9[8], 10[9], Jack[10], Queen[11], or King[12])
private int xPosition; //x position of the card image that you will draw to the screen
private int yPosition; //y position of the card image that you will draw to the screen
public Card() { //a default constructor of Card
suit = 0;
rank = 0;
}
public Card(int s, int r) { //a constructor of Card that initializes the main attributes
suit = s;
rank = r;
}
public int getSuit() { //this method returns you the suit of the card.
return suit;
}
public int getRank() { //this method returns you the rank of the card.
return rank;
}
public void printCard(Graphics2D g2, boolean dealerTurn, boolean faceDown, int cardNumber) throws IOException {//this method draws the card accordingly (looking to the parameters). It throws a IOException because we will be reading some image files.
//The first parameter is the g2[powerful brush] since we will draw some images. The second parameter tells the method if it is dealer's turn. The third method checks if the card drawn will be face down or face up. The fourth parameter tells the method which card on the line will be drawn so that each line could be drawn next to each other in a horizontal line.
BufferedImage deckImg = ImageIO.read(new File("cardSpriteSheet.png")); //we read the sprite sheet image.
int imgWidth = 950; //this is the width of the sprite sheet image in pixels.
int imgHeight = 392; //this is the height of the sprite sheet image in pixels.
BufferedImage[][] cardPictures = new BufferedImage[4][13]; //we create this two-dimensional array to store the individiual card pictures.
BufferedImage backOfACard = ImageIO.read(new File("backsideOfACard.jpg")); //this image will be the back of a card.
for (int c = 0; c < 4; c++) {
for (int r = 0; r < 13; r++) {
cardPictures[c][r] = deckImg.getSubimage(r*imgWidth/13, c*imgHeight/4, imgWidth/13, imgHeight/4); //we assign the relative card pictures to the 2-D array.
}
}
if (dealerTurn) { //if it is dealer's turn, then the card will be printed to the top where the dealer's hand is located.
yPosition = 75;
}
else { //if it is the player's turn, then the card will be printed to the below where the player's hand is located.
yPosition = 400;
}
xPosition = 500 + 75*cardNumber; // we want the drawn cards to come side by side so we shift the x position of the cards accordingly.
if (faceDown) { //this boolean parameter will tell the method if the printed card will be face down or face up.
g2.drawImage(backOfACard, xPosition, yPosition, null ); //if it is facedown, we draw the image of a back of a card.
}
else {
g2.drawImage(cardPictures[suit][rank], xPosition, yPosition, null); //if it is not face up, we draw the image from the 2-D array.
}
}
} | TunaCuma/BlackJack-with-gui | Card.java | 930 | //y position of the card image that you will draw to the screen
| line_comment | en | true |
122489_24 | package utils;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.geom.AffineTransform;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import javax.sound.sampled.Clip;
import javax.sound.sampled.FloatControl;
import engine.Resources;
/**
* Useful utility functions
*/
public class Utils {
/**
* This method makes it easier to draw images centered with rotation and
* scale
*
* @param filename
* name of image file
* @param x
* CENTER x coord
* @param y
* CENTER y coord
* @param rot
* rotation in radians
*/
public static void drawImage(Graphics2D g, String filename, double x,
double y, double rot, double scale) {
Image img = Resources.getImage(filename);
int xs = img.getWidth(null), ys = img.getHeight(null);
// rotation stuff
AffineTransform prevTransform = g.getTransform();
g.translate(x, y);
g.rotate(rot);
g.scale(scale, scale);
// draw the image
g.drawImage(img, (int) -xs / 2, (int) -ys / 2, null);
g.setTransform(prevTransform);
}
/**
* This method makes it easier to draw a rect with rotation and scale
*
* @param x
* CENTER x coord
* @param y
* CENTER y coord
* @param rot
* rotation in radians
*/
public static void fillRect(Graphics2D g, double x, double y, double xs,
double ys, double rot, double scale) {
// rotation stuff
AffineTransform prevTransform = g.getTransform();
g.translate(x, y);
g.rotate(rot);
g.scale(scale, scale);
// fill the rect
g.fillRect((int) -xs / 2, (int) -ys / 2, (int) xs, (int) ys);
g.setTransform(prevTransform);
}
/**
* @return A random value between min and max
*/
public static double randomRange(double min, double max) {
return Math.random() * (max - min) + min;
}
/**
* @return A random value >= min and < max (does not include max
*/
public static int randomRangeInt(int min, int max) {
return (int) Math.floor(randomRange(min, max));
}
/**
* @return The value clamped to the range min to max
*/
public static double clamp(double val, double min, double max) {
return Math.max(Math.min(val, max), min);
}
// /**
// * @return True if the rect (x, y, xs, ys) collides with the rect (x2, y2,
// * xs2, ys2). (x, y) is the top left
// */
// public static boolean rectsCollide(double x, double y, double xs,
// double ys, double x2, double y2, double xs2, double ys2) {
// return (x + xs > x2) && (x < x2 + xs2)
// && (y + ys > y2) && (y < y2 + ys2);
// }
/**
* @return whether the point is inside the rect defined by rx, ry, rw, rh.
* (rx, ry) is the top left corner.
*/
public static boolean pointInRect(double x, double y, double rx, double ry,
double rw,double rh){
return (x >= rx && y >= ry && x <= rx + rw && y <= ry + rh);
}
/**
* Linear interpolate between two values.
* @param t Value between 0 and 1
*/
public static double lerp(double a, double b, double t) {
t = Math.min(t, 1);
return (1 - t) * a + t * b;
}
// Utils.log, Utils.err, and Utils.fatal will pass their string arg
// to these observers when used
public static Observer logObserver = null;
public static Observer errObserver = null;
public static Observer fatalObserver = null;
public static void log(String msg){
System.out.println(msg);
if(logObserver != null)
logObserver.notify(msg);
}
/**
* Log a fatal error and quit
*/
public static void fatal(String msg){
String errMsg = "Fatal error: " + msg;
System.err.println(errMsg);
if(errObserver != null)
errObserver.notify(errMsg);
if(fatalObserver != null){
fatalObserver.notify(null);
} else {
System.exit(1);
}
}
public static void err(String msg){
String errMsg = "Error: " + msg;
System.err.println(errMsg);
if(errObserver != null)
errObserver.notify(errMsg);
}
/**
* Do a mod operation that doesn't return negative values
*/
public static double mod(double a, double b){
return (a % b + b) % b;
}
/**
* Draw the string centered, instead of left justified
*/
public static void drawStringCentered(Graphics2D g, String s, int x, int y){
FontMetrics fm = g.getFontMetrics();
int w = fm.stringWidth(s);
int h = fm.getHeight();
g.drawString(s, x - w/2, y + h/3);
}
/**
* Set the volume of the audio clip
*/
public static void setClipVolume(Clip c, double volume){
FloatControl vol = (FloatControl) c.getControl(FloatControl.Type.MASTER_GAIN);
vol.setValue((float)volume);
}
/**
* Calculate the size of the object after being serialized
*/
public static int calcNetworkSize(Serializable o) {
try {
ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(
byteOutputStream);
objectOutputStream.writeObject(o);
objectOutputStream.flush();
objectOutputStream.close();
return byteOutputStream.toByteArray().length;
} catch (IOException e) {
Utils.err("Couldn't calculate object size");
return 0;
}
}
/**
* Pack a double into a byte. This is useful for sending doubles over the network when
* you don't need 64 bits of precision. You must supply a min and max value of the double,
* so that it can be packed into a smaller space.
* @return A byte representing the double's location between min and max, packed in the
* lower 'nBits' bits of the byte.
*/
public static byte packRange(double val, double min, double max, int nBits){
if(val < min || val > max){
Utils.err("Couldn't pack byte, value was outside of range! Fix immediately");
return 0;
}
double ratio = (val - min)/(max - min);
int maxBitVal = (int)Math.pow(2, nBits)-1;
byte ret = (byte)Math.round(ratio * maxBitVal);
return ret;
}
/**
* Unpack a double that has been packed using 'packRange'. Note that precision is
* lost when packing and unpacking, so if you packed 0, for example, don't expect
* this method to return exactly 0 when unpacked.
*/
public static double unpackRange(byte val, double min, double max, int nBits){
int maxBitVal = (int)Math.pow(2, nBits)-1;
int vali = val & 0xFF;
double ratio = (double)vali/maxBitVal;
double ret = ratio * (max-min) + min;
return ret;
}
/**
* Pack and unpack a double, then return it. Lets you see how much precision
* is lost when packing/unpacking the value.
*/
public static double testCompression(double val, double min, double max, int nBits){
return unpackRange(packRange(val, min, max, nBits), min, max, nBits);
}
/**
* Smallest difference between 2 angles (in degrees).
*/
public static double angleDifference(double a, double b){
return Utils.mod((b-a) + 180, 360) - 180;
}
/**
* @return the text in the clipboard, or null if couldn't get it.
*/
public static String readClipboard(){
String str = null;
try {
str = (String) Toolkit.getDefaultToolkit()
.getSystemClipboard().getData(DataFlavor.stringFlavor);
} catch (HeadlessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedFlavorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
}
| m15399/GameDevGame | src/utils/Utils.java | 2,335 | /**
* Do a mod operation that doesn't return negative values
*/ | block_comment | en | false |
122558_33 | import java.util.Random;
import java.text.DecimalFormat;
public class Matrix {
private int x;
private int y;
private String msg;
public int[][] myMatrix;
public double[][] doubleMatrix;
private DecimalFormat output = new DecimalFormat("0.000000000");
/*----------------- Constructors -----------------*/
//Constructs empty matrix of given dimensions
public Matrix(int rows, int columns){
y = rows;
x = columns;
int[][] blankMatrix = new int[y][x];
myMatrix = blankMatrix;
}
public Matrix(int rows, int columns, boolean placeholder){
y = rows;
x = columns;
double[][] blankMatrix = new double[y][x];
doubleMatrix = blankMatrix;
}
//Constructs square matrix filled with integer values between 1 and 9
public Matrix(int randRowCol) {
x = randRowCol;
y = randRowCol;
int[][] randMatrix = new int[y][x];
myMatrix = randMatrix;
Random randGen = new Random();
for (int j = 0; j < y; j++){
for (int k = 0; k < x; k++) {
myMatrix[j][k] = randGen.nextInt(9)+1;
}
}
}
//Constructs matrix and fills with string
public Matrix(int rows, int columns, String myMsg) {
x = columns; //sets columns
y = rows; //sets matrix rows
msg = myMsg;
int[][] encodeMatrix = new int[y][x]; //builds matrix
myMatrix = encodeMatrix;
int[] brokenMsg = new int[msg.length()]; //declares array for message to fill
for (int i = 0; i<msg.length(); i++) {
brokenMsg[i] = (int)msg.charAt(i);
}
int count = 0;
for (int j = 0; j < y; j++){
for (int k = 0; k < x; k++) {
myMatrix[j][k] = brokenMsg[count];
count++;
}
}
}
//Constructs matrix and fills with mes
public Matrix(int rows, int columns, String myMsg, Boolean alt) {
x = columns; //sets columns
y = rows; //sets matrix rows
msg = myMsg;
int[][] encodeMatrix = new int[y][x]; //builds matrix
myMatrix = encodeMatrix;
int[] brokenMsg = new int[msg.length()]; //declares array for message to fill
for (int i = 0; i<msg.length(); i++) {
brokenMsg[i] = msg.charAt(i)-48;
}
int count = 0;
String[][] pieceTogether = new String[y][x];
/*System.out.println("\nMessage:");*/
for (int j = 0; j < y; j++){
for (int k = 0; k < x; k++) {
pieceTogether[j][k] = brokenMsg[4*count]+""+brokenMsg[4*count+1]+""+
brokenMsg[4*count+2]+""+brokenMsg[4*count+3];
/*System.out.println(j + " " + k+ " " + pieceTogether[j][k]);*/
count++;
myMatrix[j][k] = Integer.parseInt(pieceTogether[j][k]);
}
}
}
//Constructs matrix and fills with key
public Matrix(int rows, int columns, String myMsg, int alt) {
x = columns; //sets columns
y = rows; //sets matrix rows
msg = myMsg;
int[][] encodeMatrix = new int[y][x]; //builds matrix
myMatrix = encodeMatrix;
int[] brokenMsg = new int[msg.length()]; //declares array for message to fill
for (int i = 0; i<msg.length(); i++) {
brokenMsg[i] = msg.charAt(i)-48;
}
int count = 0;
String[][] pieceTogether = new String[y][x];
/*System.out.println("\nKey:");*/
for (int j = 0; j < y; j++){
for (int k = 0; k < x; k++) {
myMatrix[j][k] = brokenMsg[count];
count++;
/*System.out.println(j + " " + k + " " + myMatrix[j][k]);*/
}
}
}
//helper constructor for inverse
public Matrix(int rows, int columns, int[] myNum) {
x = columns; //sets columns
y = rows; //sets matrix rows
int[][] encodeMatrix = new int[y][x]; //builds matrix
myMatrix = encodeMatrix;
int count = 0;
for (int j = 0; j < y; j++){
for (int k = 0; k < x; k++) {
myMatrix[j][k] = myNum[count];
count++;
}
}
}
//Constructs a matrix based on the multiplication of current matrix and given matrix
public Matrix matrixMult(Matrix cofactor) {
Matrix product = new Matrix(this.getRows(), cofactor.getColumns());
for (int e = 0; e < cofactor.getColumns(); e++){
for (int f = 0; f < this.getRows(); f++) {
for(int g = 0; g < this.getColumns(); g++) {
product.myMatrix[f][e] += this.myMatrix[f][g]*cofactor.myMatrix[g][e];
/*System.out.println(f+" "+e+" "+product.myMatrix[f][e]);*/
}
}
}
return product;
}
public Matrix matrixMultDouble(Matrix cofactor) {
Matrix product = new Matrix(this.getRows(), cofactor.getColumns(), true);
for (int e = 0; e < 3; e++){
for (int f = 0; f < this.getRows(); f++) {
for(int g = 0; g < this.getColumns(); g++) {
product.doubleMatrix[f][e] += (double)this.myMatrix[f][g]*cofactor.doubleMatrix[g][e];
/*System.out.println(f+" "+e+" "+product.doubleMatrix[f][e]);*/
}
}
}
Matrix productInt = new Matrix(product.getRows(), product.getColumns());
for (int f = 0; f < product.getRows(); f++){
for (int e = 0; e < product.getColumns(); e++) {
productInt.myMatrix[f][e]=(int)Math.round(product.doubleMatrix[f][e]);
}
}
/*System.out.println(productInt.readMatrix());*/
return productInt;
}
//Constructs matrix based on inverse of current matrix
//Only works for 3x3 matrices, will have to be rewritten if key size is changed
public Matrix matrixInverse() {
Matrix minor;
int a,b,c,d = -1;
int count = 0;
int[] minorNum = new int[10];
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++){
a = -1;
b = -1;
c = -1;
d = -1;
int[] rowIndex = {0,1,2};
int[] columnIndex = {0,1,2};
removeInteger(rowIndex, i);
if(stillThere(rowIndex, 0) && stillThere(rowIndex, 1)){
a = 0;
b = 1;
} else if (stillThere(rowIndex, 0) && stillThere(rowIndex, 2)) {
a = 0;
b = 2;
} else if (stillThere(rowIndex, 1) && stillThere(rowIndex, 2)) {
a = 1;
b = 2;
}
removeInteger(columnIndex, j);
if(stillThere(columnIndex, 0) && stillThere(columnIndex, 1)){
c = 0;
d = 1;
} else if (stillThere(columnIndex, 0) && stillThere(columnIndex, 2)) {
c = 0;
d = 2;
} else if (stillThere(columnIndex, 1) && stillThere(columnIndex, 2)) {
c = 1;
d = 2;
}
minorNum[count]= this.myMatrix[a][c]*this.myMatrix[b][d]
-this.myMatrix[a][d]*this.myMatrix[b][c];
count++;
}
}
for(int k=1; k<minorNum.length; k+=2) {
minorNum[k] *= -1;
}
minor = new Matrix(3,3,minorNum);
Matrix cofactor = new Matrix(3,3);
for(int m=0; m<3; m++){
for(int n=0; n<3; n++){
cofactor.myMatrix[m][n] = minor.myMatrix[n][m];
}
}
double detFactor = 1.0/((this.myMatrix[0][0]*minor.myMatrix[0][0]) +
(this.myMatrix[0][1]*minor.myMatrix[0][1])+
(this.myMatrix[0][2]*minor.myMatrix[0][2]));
/*System.out.println("Determinant Factor: " + output.format(detFactor));*/
Matrix inverse = new Matrix(3,3,true);
for(int q=0; q<3; q++){
for(int r=0; r<3; r++){
inverse.doubleMatrix[q][r] = detFactor*cofactor.myMatrix[q][r];
if (Double.isNaN(inverse.doubleMatrix[q][r])){
System.out.println("Invalid key - please try again!");
System.exit(0);
}
}
}
/*System.out.println("Inverse: " + inverse.readDoubleMatrix());*/
return inverse;
}
public String decodeMatrix(){
char[][] decodedMatrix = new char[this.y][this.x];
for (int i=0; i<this.y; i++){
for (int j=0; j<this.x; j++){
int a = 0;
a = this.myMatrix[i][j];
decodedMatrix[i][j]=(char)a;
}
}
String write2String = "";
for (int j = 0; j < this.y; j++){
for (int k = 0; k < this.x; k++) {
write2String += decodedMatrix[j][k];
}
}
return write2String;
}
public void removeInteger(int[] array, int intToRemove) {
array[indexOf(array, intToRemove)] = -1;
}
private int indexOf(int[] array, int searchInt){
int index = -1;
for (int j = 0; j<array.length; j++) {
if (array[j] == searchInt) {
index = j;
}
}
return index;
}
private boolean stillThere(int[] array, int searchInt) {
boolean found = false;
for (int j=0; j<array.length; j++){
if(array[j] == searchInt){
found = true;
}
}
return found;
}
/*----------------- Access Methods -----------------*/
public int getValue(int row, int column){
return myMatrix[row][column];
}
public int getColumns(){
return x;
}
public int getRows(){
return y;
}
/*----------------- Mutator Method -----------------*/
public void setValue(int row, int column, int value){
myMatrix[row][column]=value;
}
/*----------------- Additional Methods -----------------*/
//Converts matrix to string
public String readMatrix() {
String write2 = "";
for (int j = 0; j < this.getRows(); j++){
for (int k = 0; k < this.getColumns(); k++) {
write2 += this.myMatrix[j][k];
}
}
return write2;
}
public String readEncMatrix() {
String write2 = "";
String[][] placeholder = new String[this.getRows()][this.getColumns()];
for (int j = 0; j < this.getRows(); j++){
for (int k = 0; k < this.getColumns(); k++) {
placeholder[j][k] = ""+this.myMatrix[j][k];
while (placeholder[j][k].length()<4){
placeholder[j][k] = "0"+placeholder[j][k];
}
/*System.out.println(placeholder[j][k]);*/
write2 += placeholder[j][k];
}
}
return write2;
}
public String readDoubleMatrix() {
String write2 = "";
for (int j = 0; j < this.getRows(); j++){
for (int k = 0; k < this.getColumns(); k++) {
write2 += this.doubleMatrix[j][k];
}
}
return write2;
}
}
| James-D-Wood/encryption-project | Matrix.java | 3,397 | /*System.out.println("Inverse: " + inverse.readDoubleMatrix());*/ | block_comment | en | true |
122780_0 |
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class hps {
public static void main(String[] args) throws NumberFormatException, IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("hps.in")));
PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream("hps.out")));
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
int n = Integer.valueOf(br.readLine());
StringTokenizer st;
String[][] combos = {
{"sci","pap","roc"},
{"pap","sci","roc"},
{"pap","roc","sci"},
{"roc","pap","sci"},
{"sci","roc","pap"},
{"roc","sci","pap"}
};
int[] cow1 = new int[n];
int[] cow2 = new int[n];
for(int i = 0;i<n;i++){
st = new StringTokenizer(br.readLine());
cow1[i] = Integer.valueOf(st.nextToken());
cow2[i] = Integer.valueOf(st.nextToken());
}
int max = 0;
int temp = 0;
for(int i = 0;i<combos.length;i++){
for(int j = 0;j<n;j++){
System.out.println(combos[i][cow1[j]-1]);
System.out.println(combos[i][cow2[j]-1]);
if(combos[i][cow1[j]-1]=="roc"&&combos[i][cow2[j]-1]=="sci"){
temp++;
}
else if(combos[i][cow1[j]-1]=="sci"&&combos[i][cow2[j]-1]=="pap"){
temp++;
}
else if(combos[i][cow1[j]-1]=="pap"&&combos[i][cow2[j]-1]=="roc"){
temp++;
}
}
System.out.println();
if(temp>max){
max = temp;
}
temp = 0;
}
pw.println(max);
pw.flush();
pw.close();
br.close();
}
}
| justinlin26/usaco | hps.java | 631 | //BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); | line_comment | en | true |
123617_0 | /* Vapor API Terms and Conditions
*
* - You MAY NOT
* - attempt to claim ownership of, or pass off the Vapor source code and materials as your own work unless:
*
* - used as constituent component in an Android application that you intend to release and/or profit from
*
* - use or redistribute the Vapor source code and materials without explicit attribution to the owning parties
*
* - advertise Vapor in a misleading, inappropriate or offensive fashion
*
* - Indemnity
* You agree to indemnify and hold harmless the authors of the Software and any contributors for any direct, indirect,
* incidental, or consequential third-party claims, actions or suits, as well as any related expenses, liabilities, damages,
* settlements or fees arising from your use or misuse of the Software, or a violation of any terms of this license.
*
* - DISCLAIMER OF WARRANTY
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
* WARRANTIES OF QUALITY, PERFORMANCE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
*
* - LIMITATIONS OF LIABILITY
* YOU ASSUME ALL RISK ASSOCIATED WITH THE INSTALLATION AND USE OF THE SOFTWARE. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS OF THE SOFTWARE BE LIABLE FOR CLAIMS, DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF, OR IN CONNECTION WITH THE
* SOFTWARE. LICENSE HOLDERS ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USE AND ASSUME ALL RISKS ASSOCIATED
* WITH ITS USE, INCLUDING BUT NOT LIMITED TO THE RISKS OF PROGRAM ERRORS, DAMAGE TO EQUIPMENT, LOSS OF DATA OR SOFTWARE PROGRAMS,
* OR UNAVAILABILITY OR INTERRUPTION OF OPERATIONS.
*
* © Darius Hodaei. License Version 1.1. Last Updated 30/06/2013.
*/
package vapor.core;
public interface $map<X, M> {
M map(X x);
}
| ComethTheNerd/Vapor-API | core/$map.java | 528 | /* Vapor API Terms and Conditions
*
* - You MAY NOT
* - attempt to claim ownership of, or pass off the Vapor source code and materials as your own work unless:
*
* - used as constituent component in an Android application that you intend to release and/or profit from
*
* - use or redistribute the Vapor source code and materials without explicit attribution to the owning parties
*
* - advertise Vapor in a misleading, inappropriate or offensive fashion
*
* - Indemnity
* You agree to indemnify and hold harmless the authors of the Software and any contributors for any direct, indirect,
* incidental, or consequential third-party claims, actions or suits, as well as any related expenses, liabilities, damages,
* settlements or fees arising from your use or misuse of the Software, or a violation of any terms of this license.
*
* - DISCLAIMER OF WARRANTY
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
* WARRANTIES OF QUALITY, PERFORMANCE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
*
* - LIMITATIONS OF LIABILITY
* YOU ASSUME ALL RISK ASSOCIATED WITH THE INSTALLATION AND USE OF THE SOFTWARE. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS OF THE SOFTWARE BE LIABLE FOR CLAIMS, DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF, OR IN CONNECTION WITH THE
* SOFTWARE. LICENSE HOLDERS ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USE AND ASSUME ALL RISKS ASSOCIATED
* WITH ITS USE, INCLUDING BUT NOT LIMITED TO THE RISKS OF PROGRAM ERRORS, DAMAGE TO EQUIPMENT, LOSS OF DATA OR SOFTWARE PROGRAMS,
* OR UNAVAILABILITY OR INTERRUPTION OF OPERATIONS.
*
* © Darius Hodaei. License Version 1.1. Last Updated 30/06/2013.
*/ | block_comment | en | true |
124219_0 | package application;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Main extends Application {
Stage primaryStage;
CommonUseObjects obj;
@Override
public void start(Stage primaryStage) {
try {
VBox root = (VBox)FXMLLoader.load(getClass().getClassLoader().getResource("view/LoginView.fxml"));
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.setTitle("Faculty Recommendation Compiler");
primaryStage.show();
//adding a reference to use when switching scenes
obj = CommonUseObjects.getInstance();
obj.setPrimaryStage(primaryStage);
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
| rg492/CS151GroupProject | Main.java | 240 | //adding a reference to use when switching scenes
| line_comment | en | true |