file_id
int64 1
250k
| content
stringlengths 0
562k
| repo
stringlengths 6
115
| path
stringlengths 1
147
|
---|---|---|---|
1,034 | import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.Sets;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
public class yj
extends yq
{
private static final UUID a = UUID.fromString("020E0DFB-87AE-4653-9556-831010E291A0");
private static final sn b = new sn(a, "Attacking speed boost", 0.15000000596046448D, 0).a(false);
private static final Set<ajt> c = Sets.newIdentityHashSet();
private static final ke<Optional<arc>> bv = kh.a(yj.class, kg.g);
private static final ke<Boolean> bw = kh.a(yj.class, kg.h);
static
{
c.add(aju.c);
c.add(aju.d);
c.add(aju.m);
c.add(aju.n);
c.add(aju.N);
c.add(aju.O);
c.add(aju.P);
c.add(aju.Q);
c.add(aju.W);
c.add(aju.aK);
c.add(aju.aL);
c.add(aju.aU);
c.add(aju.bk);
c.add(aju.bw);
}
private int bx = 0;
private int by = 0;
public yj(aht β)
{
super(β);
a(0.6F, 2.9F);
this.P = 1.0F;
a(aym.g, -1.0F);
}
protected void r()
{
this.bp.a(0, new th(this));
this.bp.a(2, new ts(this, 1.0D, false));
this.bp.a(7, new ug(this, 1.0D));
this.bp.a(8, new tp(this, zj.class, 8.0F));
this.bp.a(8, new uf(this));
this.bp.a(10, new yj.a(this));
this.bp.a(11, new yj.c(this));
this.bq.a(1, new yj.b(this));
this.bq.a(2, new uv(this, false, new Class[0]));
this.bq.a(3, new uy(this, yk.class, 10, true, false, new Predicate()
{
public boolean a(yk β)
{
return β.o();
}
}));
}
protected void bA()
{
super.bA();
a(yt.a).a(40.0D);
a(yt.d).a(0.30000001192092896D);
a(yt.e).a(7.0D);
a(yt.b).a(64.0D);
}
public void c(sa β)
{
super.c(β);
sm β = a(yt.d);
if (β == null)
{
this.by = 0;
this.Z.b(bw, Boolean.valueOf(false));
β.c(b);
}
else
{
this.by = this.T;
this.Z.b(bw, Boolean.valueOf(true));
if (!β.a(b)) {
β.b(b);
}
}
}
protected void i()
{
super.i();
this.Z.a(bv, Optional.absent());
this.Z.a(bw, Boolean.valueOf(false));
}
public void o()
{
if (this.T >= this.bx + 400)
{
this.bx = this.T;
if (!ad()) {
this.l.a(this.p, this.q + bn(), this.r, ng.aY, bz(), 2.5F, 1.0F, false);
}
}
}
public void a(ke<?> β)
{
if ((bw.equals(β)) &&
(dc()) && (this.l.E)) {
o();
}
super.a(β);
}
public void b(dn β)
{
super.b(β);
arc β = db();
if (β != null)
{
β.a("carried", (short)ajt.a(β.t()));
β.a("carriedData", (short)β.t().e(β));
}
}
public void a(dn β)
{
super.a(β);
arc β;
arc β;
if (β.b("carried", 8)) {
β = ajt.b(β.l("carried")).a(β.g("carriedData") & 0xFFFF);
} else {
β = ajt.b(β.g("carried")).a(β.g("carriedData") & 0xFFFF);
}
if ((β == null) || (β.t() == null) || (β.a() == axe.a)) {
β = null;
}
a(β);
}
private boolean c(zj β)
{
adq β = β.br.b[3];
if ((β != null) && (β.b() == ado.a(aju.aU))) {
return false;
}
bbj β = β.f(1.0F).a();
bbj β = new bbj(this.p - β.p, bl().b + this.H / 2.0F - (β.q + β.bn()), this.r - β.r);
double β = β.b();
β = β.a();
double β = β.b(β);
if (β > 1.0D - 0.025D / β) {
return β.D(this);
}
return false;
}
public float bn()
{
return 2.55F;
}
public void n()
{
if (this.l.E) {
for (int β = 0; β < 2; β++) {
this.l.a(cy.y, this.p + (this.S.nextDouble() - 0.5D) * this.G, this.q + this.S.nextDouble() * this.H - 0.25D, this.r + (this.S.nextDouble() - 0.5D) * this.G, (this.S.nextDouble() - 0.5D) * 2.0D, -this.S.nextDouble(), (this.S.nextDouble() - 0.5D) * 2.0D, new int[0]);
}
}
this.bc = false;
super.n();
}
protected void M()
{
if (ah()) {
a(rc.f, 1.0F);
}
if ((this.l.B()) && (this.T >= this.by + 600))
{
float β = e(1.0F);
if ((β > 0.5F) &&
(this.l.h(new cj(this))) && (this.S.nextFloat() * 30.0F < (β - 0.4F) * 2.0F))
{
c(null);
da();
}
}
super.M();
}
protected boolean da()
{
double β = this.p + (this.S.nextDouble() - 0.5D) * 64.0D;
double β = this.q + (this.S.nextInt(64) - 32);
double β = this.r + (this.S.nextDouble() - 0.5D) * 64.0D;
return l(β, β, β);
}
protected boolean a(rr β)
{
bbj β = new bbj(this.p - β.p, bl().b + this.H / 2.0F - β.q + β.bn(), this.r - β.r);
β = β.a();
double β = 16.0D;
double β = this.p + (this.S.nextDouble() - 0.5D) * 8.0D - β.b * β;
double β = this.q + (this.S.nextInt(16) - 8) - β.c * β;
double β = this.r + (this.S.nextDouble() - 0.5D) * 8.0D - β.d * β;
return l(β, β, β);
}
private boolean l(double β, double β, double β)
{
boolean β = k(β, β, β);
if (β)
{
this.l.a(null, this.m, this.n, this.o, ng.aZ, bz(), 1.0F, 1.0F);
a(ng.aZ, 1.0F, 1.0F);
}
return β;
}
protected nf G()
{
return dc() ? ng.aX : ng.aU;
}
protected nf bR()
{
return ng.aW;
}
protected nf bS()
{
return ng.aV;
}
protected void a(boolean β, int β)
{
super.a(β, β);
arc β = db();
if (β != null) {
a(new adq(β.t(), 1, β.t().e(β)), 0.0F);
}
}
protected kk J()
{
return azt.u;
}
public void a(arc β)
{
this.Z.b(bv, Optional.fromNullable(β));
}
public arc db()
{
return (arc)((Optional)this.Z.a(bv)).orNull();
}
public boolean a(rc β, float β)
{
if (b(β)) {
return false;
}
if ((β instanceof re))
{
for (int β = 0; β < 64; β++) {
if (da()) {
return true;
}
}
return false;
}
boolean β = super.a(β, β);
if ((β.e()) && (this.S.nextInt(10) != 0)) {
da();
}
return β;
}
public boolean dc()
{
return ((Boolean)this.Z.a(bw)).booleanValue();
}
static class b
extends uy<zj>
{
private final yj i;
private zj j;
private int k;
private int l;
public b(yj β)
{
super(zj.class, false);
this.i = β;
}
public boolean a()
{
double β = f();
this.j = this.i.l.a(this.i.p, this.i.q, this.i.r, β, β, null, new Predicate()
{
public boolean a(zj β)
{
return (β != null) && (yj.a(yj.this, β));
}
});
return this.j != null;
}
public void c()
{
this.k = 5;
this.l = 0;
}
public void d()
{
this.j = null;
super.d();
}
public boolean b()
{
if (this.j != null)
{
if (!yj.a(this.i, this.j)) {
return false;
}
this.i.a(this.j, 10.0F, 10.0F);
return true;
}
if ((this.d != null) && (((zj)this.d).au())) {
return true;
}
return super.b();
}
public void e()
{
if (this.j != null)
{
if (--this.k <= 0)
{
this.d = this.j;
this.j = null;
super.c();
}
}
else
{
if (this.d != null) {
if (yj.a(this.i, (zj)this.d))
{
if (((zj)this.d).h(this.i) < 16.0D) {
this.i.da();
}
this.l = 0;
}
else if ((((zj)this.d).h(this.i) > 256.0D) &&
(this.l++ >= 30) &&
(this.i.a(this.d)))
{
this.l = 0;
}
}
super.e();
}
}
}
static class a
extends tk
{
private final yj a;
public a(yj β)
{
this.a = β;
}
public boolean a()
{
if (this.a.db() == null) {
return false;
}
if (!this.a.l.U().b("mobGriefing")) {
return false;
}
if (this.a.bF().nextInt(2000) != 0) {
return false;
}
return true;
}
public void e()
{
Random β = this.a.bF();
aht β = this.a.l;
int β = on.c(this.a.p - 1.0D + β.nextDouble() * 2.0D);
int β = on.c(this.a.q + β.nextDouble() * 2.0D);
int β = on.c(this.a.r - 1.0D + β.nextDouble() * 2.0D);
cj β = new cj(β, β, β);
arc β = β.o(β);
arc β = β.o(β.b());
arc β = this.a.db();
if ((β != null) && (a(β, β, β.t(), β, β)))
{
β.a(β, β, 3);
this.a.a(null);
}
}
private boolean a(aht β, cj β, ajt β, arc β, arc β)
{
if (!β.a(β, β)) {
return false;
}
if (β.a() != axe.a) {
return false;
}
if (β.a() == axe.a) {
return false;
}
if (!β.h()) {
return false;
}
return true;
}
}
static class c
extends tk
{
private final yj a;
public c(yj β)
{
this.a = β;
}
public boolean a()
{
if (this.a.db() != null) {
return false;
}
if (!this.a.l.U().b("mobGriefing")) {
return false;
}
if (this.a.bF().nextInt(20) != 0) {
return false;
}
return true;
}
public void e()
{
Random β = this.a.bF();
aht β = this.a.l;
int β = on.c(this.a.p - 2.0D + β.nextDouble() * 4.0D);
int β = on.c(this.a.q + β.nextDouble() * 3.0D);
int β = on.c(this.a.r - 2.0D + β.nextDouble() * 4.0D);
cj β = new cj(β, β, β);
arc β = β.o(β);
ajt β = β.t();
bbi β = β.a(new bbj(on.c(this.a.p) + 0.5F, β + 0.5F, on.c(this.a.r) + 0.5F), new bbj(β + 0.5F, β + 0.5F, β + 0.5F), false, true, false);
boolean β = (β != null) && (β.a().equals(β));
if ((yj.dd().contains(β)) && (β))
{
this.a.a(β);
β.g(β);
}
}
}
}
| MCLabyMod/LabyMod-1.9 | yj.java |
1,037 | // Java implementation of Server 1
// Save file as S1.class
import java.io.*;
import java.text.*;
import java.util.*;
import java.net.*;
import java.security.*;
import java.lang.*;
import java.math.*;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Arrays;
import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.SignatureException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.net.SocketTimeoutException;
import java.security.SecureRandom;
// S1 class
public class S1
{
//accessing voter table in the form of Hashmap and classes
static VoterData temp1 = new VoterData();
public static HashMap<String, VoterInfo> VoterTable = temp1.getVoterTable();
//accessing Candidate table
static CandidateData temp2 = new CandidateData();
public static HashMap<String, String> CandidateTable = temp2.getCandidateTable();
//create empty VoterCheck Table
public static HashMap<String, VoterCheck> VoterCheckTable= new HashMap<String, VoterCheck>();
//aes secret key for S2 Server
public static SecretKey getSecretKeyS2(){
String keyStr = "012345678901234567890123456789XY";
byte[] decodedKey = Base64.getMimeDecoder().decode(keyStr);
SecretKey secretKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
return secretKey;
}
public static void main(String[] args) throws IOException
{
// S1 is listening on port 5056 for voter
ServerSocket ss = new ServerSocket(5056);
// running infinite loop for getting voter vote
while (true){
Socket s = null;
try{
// socket object to receive incoming voter requests
s = ss.accept();
// obtaining input and output streams
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
// create a new thread object
Thread t = new VoterHandler(s, dis, dos);
// Invoking the start() method
t.start();
}
catch (Exception e){
s.close();
e.printStackTrace();
}
}
}
}
//
// ClientHandler class
//
class VoterHandler extends Thread{
//socket connection variables
final DataInputStream dis;
final DataOutputStream dos;
final Socket s;
// For AES Encryption
static Cipher cipher;
//Nonces
private long N2 = Long.parseLong(nonceGenerator());
private long N3 = Long.parseLong(nonceGenerator());
// Constructor
public VoterHandler(Socket s, DataInputStream dis, DataOutputStream dos){
this.s = s;
this.dis = dis;
this.dos = dos;
}
@Override
public void run(){
BigInteger serverKey = new BigInteger("1");
//socket communication buffer strings
String received;
String toreturn;
String vote = new String();
//authentication strings
String accepted = "accepted";
String rejected = "rejected";
//Initialize Username .. useful later on in program
String Username = "";
int flagS2 = 0;
try{
//LOGIN STARTS -- We have to assume that an already existing salt is there on both sides
//Functions for salt functionality
SecureRandom random = new SecureRandom();
Base64.Encoder enc = Base64.getEncoder();
//2-Factor authentication
int flag = 0,i=0;
while(flag < 3){
// receive VoterId
Username = dis.readUTF();
System.out.println("Recieved VoterId : " + Username);
if(S1.VoterTable.get(Username).getUidAssigned()){
dos.writeUTF(rejected);
dos.flush();
try{
// closing resources
this.s.close();
this.dis.close();
this.dos.close();
System.out.println("Connection is broken");
flagS2 = 1;
break;
}catch(IOException e){
e.printStackTrace();
}
}
//Taking Salt from database and converting to bytes
String salttemp = S1.VoterTable.get(Username).getSalt();
byte[] salt = salttemp.getBytes();
//get salt to corresponding user from database(using some random thing as salt as of now)
random.nextBytes(salt);
//encode the salt to send
String salt1 = Base64.getEncoder().encodeToString(salt);
String message = "----------------------------Sending Salt----------------------------------------";
dos.writeUTF(message);
//sending encoded salt
dos.flush();
dos.writeUTF(salt1);
dos.flush();
String hp;
// Hashing the passwork string taken from the database
//password accessed from database
final String pass = S1.VoterTable.get(Username).getPassword();
try{
KeySpec spec = new PBEKeySpec(pass.toCharArray(),salt,65536, 128);
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
byte hash[] = f.generateSecret(spec).getEncoded();
hp = enc.encodeToString(hash);
}catch (NoSuchAlgorithmException ex){
throw new IllegalStateException( ex);
}catch (InvalidKeySpecException ex){
throw new IllegalStateException("Invalid SecretKeyFactory", ex);
}
//receive hashed password from voter
String Pwd = dis.readUTF();
//checking hashkey in database with one sent by user
//check username to the one present in the database
if(Username.equals(S1.VoterTable.get(Username).getVoterId()) && Pwd.equals(hp)){
dos.writeUTF(accepted);
dos.flush();
flag = 4;
}else{
dos.writeUTF(rejected);
dos.flush();
System.out.println("rejected");
flag ++;
}
}
//sending an otp to mail
if(flag == 4){
//get email from database
String check = TLSEmail.otp(S1.VoterTable.get(Username).getEmail());
//Recieves OTP
String otp = dis.readUTF();
if(otp.equals(check)){
dos.writeUTF(accepted);
dos.flush();
serverKey = DHServer.fetchServerKey(dis,dos);
}else{
dos.writeUTF(rejected);
dos.flush();
}
}
if(flagS2 != 1)
{
//PACKET 1 and 2
// receive packet 1
received = dis.readUTF();
System.out.println("\n----------------------------Receive Packet1-------------------------------");
SecretKey SharedKey = getSecretKey(serverKey);
//decrypts the packet 1
String packet1 = decryptAES(received, SharedKey);
String[] msgList = packet1.split("\\s+");
String VoterId = msgList[1];
long N1 = Long.parseLong(msgList[2]);
//generates uniqueId
String uniqueID;
if(!S1.VoterTable.get(VoterId).getUidAssigned()){
do{
//get random uniqueID
uniqueID = getAlphaNumericString(10);
//assign if uniqueID is unique
if(!S1.VoterCheckTable.containsKey(uniqueID)){
VoterCheck voter = new VoterCheck(VoterId,uniqueID);
S1.VoterCheckTable.put(uniqueID, voter);
S1.VoterTable.get(VoterId).changeUidAssigned();
S1.VoterTable.get(VoterId).setUniqueId(uniqueID);
break;
}
}while(true);
}
//sending candidate list as an hashmap object to Webserver
ObjectOutputStream mapdos = new ObjectOutputStream(dos);
mapdos.writeObject(S1.CandidateTable);
//Semding packet 2
System.out.println("----------------------------Sending Packet2----------------------------------------");
String packet2 = getmessagePacket2(S1.VoterTable.get(VoterId).getUniqueId(), N1, SharedKey);
dos.writeUTF(packet2);
// PACKET 3
received = "Initial";
// receive packet 3
//polling for the packet
s.setSoTimeout(5000);
do{
try{
received = dis.readUTF();
}
catch (SocketTimeoutException e){
System.out.println("Packet3 not Recieved... Sending Packet 2 again.");
dos.writeUTF(packet2);
}
catch (Exception e){
e.printStackTrace();
}
}while(received == "Initial");
s.setSoTimeout(0);
System.out.println("\n----------------------------Receive Packet3-------------------------------");
//decrypting packet 3
String Msg = decryptAES(received, SharedKey);
msgList = Msg.split("\\s+"); //splits to a list of rsa encrypted packet, uid, dig sig and N2-1
String UID = msgList[1];
Long N2_mod = Long.parseLong(msgList[3]);
//Check if nonce is correct
//getVoteCasted returns boolean for whether the corresponding UID has casted vote or not
//So if it returns true.. then socket should close
if ((S1.VoterCheckTable.get(UID).getVoteCasted()) || (N2_mod != N2-1)){
System.out.println("Voter already voted");
System.out.println("Refusing this connection.");
this.s.close();
System.out.println("Connection closed");
flagS2 = 1;
}
//else .. set Vote Casted to true
S1.VoterCheckTable.get(UID).setVoteCasted();
vote = msgList[0];
}
} catch (IOException e) {
e.printStackTrace();
} catch(Exception e){
e.printStackTrace();
}
try
{
// closing resources
this.dis.close();
this.dos.close();
}catch(IOException e){
e.printStackTrace();
}
// All communication with S2 from here onwards
if (flagS2 != 1)
{
try{
//Set up socket for connecting to S2
// getting localhost ip
InetAddress ip_S2 = InetAddress.getByName("localhost");
// establish the connection with server port 1235
Socket s_S2 = new Socket(ip_S2, 1234);
// obtaining input and out streams
DataInputStream dis_S2 = new DataInputStream(s_S2.getInputStream());
DataOutputStream dos_S2 = new DataOutputStream(s_S2.getOutputStream());
//set up communication with S2 in this block
//send request to S2
String toSendtoS2 = EncryptionDecryptionAES.encrypt(vote+" "+Long.toString(N3),S1.getSecretKeyS2());
dos_S2.writeUTF(toSendtoS2);
System.out.println("\n---------------------Sent Packet4---------------------");
//recieve response
received = dis_S2.readUTF();
if(Long.parseLong(received)+1 == N3){
System.out.println("\n---------------------Received Packet5---------------------");
}else{
System.out.println("\nWrong nonce. Vote is not counted");
}
dis_S2.close();
dos_S2.close();
s_S2.close();
}catch(Exception e){
e.printStackTrace();
}
}
} //end run()
//
//External Function
public static String encryptAES(String plainText, SecretKey secretKey) throws Exception{
cipher = Cipher.getInstance("AES");
byte[] plainTextByte = plainText.getBytes();
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedByte = cipher.doFinal(plainTextByte);
Base64.Encoder encoder = Base64.getEncoder();
String encryptedText = encoder.encodeToString(encryptedByte);
return encryptedText;
}
public static String decryptAES(String encryptedText, SecretKey secretKey) throws Exception{
cipher = Cipher.getInstance("AES");
Base64.Decoder decoder = Base64.getDecoder();
byte[] encryptedTextByte = decoder.decode(encryptedText);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedByte = cipher.doFinal(encryptedTextByte);
String decryptedText = new String(decryptedByte);
return decryptedText;
}
static String getAlphaNumericString(int n){
// chose a Character random from this String
String AlphaNumericString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789" + "abcdefghijklmnopqrstuvxyz";
// create StringBuffer size of AlphaNumericString
StringBuilder sb = new StringBuilder(n);
for (int i = 0; i < n; i++){
// generate a random number between
// 0 to AlphaNumericString variable length
int index = (int)(AlphaNumericString.length() * Math.random());
// add Character one by one in end of sb
sb.append(AlphaNumericString.charAt(index));
}
return sb.toString();
}
public static SecretKey getSecretKey(BigInteger serverKey){
String key = serverKey.toString();
int length = key.length();
int i = 0;
String keyStr = "012345678901234567890123456789XY";
for(i= length; i < keyStr.length();i++){
char x = keyStr.charAt(i);
key = key + String.valueOf(x);
}
byte[] decodedKey = Base64.getMimeDecoder().decode(key);
SecretKey secretKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
System.out.println(secretKey);
return secretKey;
}
public static String getmessagePacket2(String uniqueID, long N1, SecretKey SharedKey) throws SignatureException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException{
long N2 = 3725678901L;
String packet = "";
String secret = getAlphaNumericString(10);
try{
packet = encryptAES(uniqueID + " " + Long.toString(N1-1) + " " + Long.toString(N2) + " " + secret , SharedKey);
}catch(Exception e){
e.printStackTrace();
}
return packet;
}
public static String nonceGenerator(){
SecureRandom secureRandom = new SecureRandom();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < 15; i++) {
stringBuilder.append(secureRandom.nextInt(10));
}
String randomNumber = stringBuilder.toString();
return randomNumber;
}
}
| KavithaVarughese/Internet_Voting | S1.java |
1,039 |
import java.io.*;
public class Ri {
public static final Object RI_NULL = null;
public static final String RI_P = "P";
public static final String RI_CS = "Cs";
public static final int RI_TRUE = 1;
public static final int RI_FALSE = 0;
public static final String RiBSplineBasis = "b-spline";
public static final String RI_UNION = "union";
public static final String RI_PRIMITIVE = "primitive";
public static final String RI_INTERSECTION = "intersection";
public static final String RI_DIFFERENCE = "difference";
public static final String RI_BICUBIC = "bicubic";
public static final String RiBezierBasis = "BezierBasis";
//public static final String RiBSplineBasis = "BSplineBasis";
public static final String RiCatmullRomBasis = "CatmullRomBasis";
public static final String RiHermiteBasis = "HermiteBasis";
public static final String RiPowerBasis = "PowerBasis";
public static final String RiBesselFilter = "BesselFilter";
public static final String RiBlackmanHarrisFilter ="BlackmanHarrisFilter";
public static final String RiBoxFilter = "BoxFilter";
public static final String RiCatmullRomFilter = "CatmullRomFilter";
public static final String RiDiskFilter = "DiskFilter";
public static final String RiGaussianFilter = "GaussianFilter";
public static final String RiMitchellFilter = "MitchellFilter";
public static final String RiLanczosFilter = "LanczosFilter";
public static final String RiSeparableCatmullRomFilter ="SeparableCatmullRomFilter";
public static final String RiSincFilter = "SincFilter";
public static final String RiTriangleFilter = "TriangleFilter";
public static final String RiErrorIgnore = "ErrorIgnore";
public static final String RiErrorPrint = "ErrorPrint";
public static final String RiErrorPrintOnce = "ErrorPrintOnce";
public static final String RiErrorCondAbort = "ErrorCondAbort";
public static final String RiErrorAbort = "ErrorAbort";
public static final String RiErrorCleanup = "ErrorCleanup";
public static final String RiProcDelayedReadArchive ="ProcDelayedReadArchive";
public static final String RiProcRunProgram = "ProcRunProgram";
public static final String RiProcDynamicLoad = "ProcDynamicLoad";
public static final int RI_BEZIERSTEP = 3;
public static final int RI_BSPLINESTEP = 1;
public static final int RI_CATMULLROMSTEP = 1;
public static final int RI_HERMITESTEP = 2;
public static final int RI_POWERSTEP = 4;
private static PrintStream out;
public void RiBegin(Object o) {
File fi;
if (o instanceof String) {
String name = (String) o;
fi = new File(name);
}
else fi = new File("java.rib");
try {
out = new PrintStream(fi);
//System.out.println("opening stream");
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(2);
}
RiHider("raytrace","int incremental",0,"int minsamples",16,
"int maxsamples", 86);
RiIntegrator("PxrPathTracer","handle","int maxIndirectBounces", new int []{2},
"int numLightSamples", new int[]{1}, "int numBxdfSamples",
new int[] {1}, "int numIndirectSamples", new int[]{1},
"int numDiffuseSamples", new int[] {4},
"int numSpecularSamples", new int[] {4});
}
public void RiEnd() {
out.close();
}
public void RiDisplay(String name, String type, String mode, Object... objects) {
out.print("Display ");
toOut(name);
toOut(type);
toOut(mode);
toOut(objects);
lineEnd();
}
public void RiDisplay(Object... objects) {
out.print("Display ");
toOut(this.getClass()+".tiff");
toOut("framebuffer");
toOut("rgba");
toOut(objects);
lineEnd();
}
public void RiFormat(Integer xres, Integer yres, double aspect) {
out.print("Format ");
toOut(xres);
toOut(yres);
toOut(aspect);
lineEnd();
}
public void RiProjection(String name, Object... os) {
out.print("Projection ");
toOut(name);
toOut(os);
lineEnd();
}
private int lights = 0;
public int RiLightSource(String name, Object... os ) {
System.err.println("RiLightSource is deprecated. DO NOT IGNORE THIS");
//System.out.println("The Amherst College CS321 binding will replace this with a");
// System.out.println("PxrEnvDayLight");
//RiRotate(-90,1,0,0); //???
//RiRotate(90,0,0,0);
//out.print("Light ");
//toOut("PxrDistantLight");
//toOut("PxrEnvDayLight");
//lights++;
//toOut("light"+lights);
//toOut("intensity");
//toOut(100000);
/*
out.print("LightSource ");
toOut(name);
toOut(lights);
toOut(os);
*/
// lineEnd();
return -1;
}
public void RiPixelSamples(double x, double y) {
out.print("PixelSamples ");
toOut(x);
toOut(y);
lineEnd();
}
public void RiPixelSamples(Integer x, Integer y) {
out.print("PixelSamples ");
toOut(x);
toOut(y);
lineEnd();
}
public void RiSurface(String name, Object... objects) {
System.out.println("RiSurface is deprecated. The Amherst College binding will replace");
System.out.println("This with a simple Bxdf if the shader is matte. It the shader is");
System.out.println("Something else, we will throw an excpetion");
if (!name.equals("matte")) {
AC_CS321_Exception e = new AC_CS321_Exception(name);
//throw e;
}
RiColor(currentColor);
/*
out.print("Surface ");
toOut(name);
toOut(objects);
lineEnd();
*/
}
public void RiWorldBegin() {
out.print("WorldBegin");
lineEnd();
RiTransformBegin();
//RiTranslate(10.0,0.0,0.0);
RiLight("PxrDomeLight","light3","float intensity",0.1,RI_NULL);
//RiLight("PxrSphereLight","light3","float intensity",1000,RI_NULL);
RiTransformEnd();
}
public void RiWorldBegin(double intensity) {
out.print("WorldBegin");
lineEnd();
RiTransformBegin();
//RiTranslate(10.0,0.0,0.0);
if (intensity == 0) {
System.out.println("default light is turned off");
}
else RiLight("PxrDomeLight","light3","float intensity",intensity,RI_NULL);
//RiLight("PxrSphereLight","light3","float intensity",1000,RI_NULL);
RiTransformEnd();
}
public void RiWorldEnd() {
out.print("WorldEnd");
lineEnd();
}
public void RiTranslate(double dx, double dy, double dz) {
out.print("Translate ");
toOut(dx);
toOut(dy);
toOut(dz);
lineEnd();
}
public void RiScale(double dx, double dy, double dz) {
out.print("Scale ");
toOut(dx);
toOut(dy);
toOut(dz);
lineEnd();
}
public void RiRotate(double... ds) {
out.print("Rotate ");
for (double d : ds)
toOut(d);
lineEnd();
}
public void RiPattern(String name, Object... os) {
simple("Pattern",name,os);
}
public void RiAttributeBegin() {
simple("AttributeBegin");
}
public void RiAttributeEnd() {
simple("AttributeEnd");
}
public void RiTransformBegin() {
simple("TransformBegin");
}
public void RiTransformEnd() {
simple("TransformEnd");
}
public void RiPolygon(Integer n, Object... os ) {
out.print("Polygon ");
toOut(os);
lineEnd();
}
public void RiAtmosphere(String name, Object... os) {
simple("Atmosphere",name,os);
}
public void RiAreaLightSource(String name, Object... os) {
simple("AreaLightSource",name,os);
}
public void RiAttribute(String name, Object... os) {
simple("Attribute",name,os);
}
public void RiBasis(String u, int us, String v, int vs) {
out.print("Basis ");
toOut(u);
toOut(us);
toOut(v);
toOut(vs);
lineEnd();
}
public void RiBlobby(
int nleaf,
int ncode, int code[],
int nflt, double flt[],
int nstr, String str[],
Object... os) {
out.print("Blobby ");
toOut(nleaf);
//toOut(ncode);
toOut(ncode,code);
//toOut(nflt);
toOut(flt);
//toOut(nstr);
toOutString(str);
toOut(os);
lineEnd();
}
private void toOutString(String[] str) {
out.print("[ ");
for (String d : str) {
out.print("\""+d+"\"");
}
out.print(" ] ");
}
public void RiBound(double[] ds) {
out.print("Bound ");
for (double d1 : ds) {
double d = d1;
toOut(d);
}
lineEnd();
}
public void RiClipping(double a, double b) {
out.print("Clipping ");
toOut(a);
toOut(b);
lineEnd();
}
public void RiColor(double[] ds) {
/*out.print("Color ");
for (double d : ds) {
toOut(d);
}*/
System.out.println("RiColor is deprecated");
System.out.println("The AC CS321 binding will replace this with a Bxdf with the color");
System.out.println("Assigned to the diffuse color");
currentColor = ds;
out.print("Bxdf ");
toOut("PxrSurface");
toOut("CS321_"+randTag());
toOut("color diffuseColor");
out.print("[ ");
for (double d : ds) {
toOut(d);
}
out.print(" ]");
toOut("color specularFaceColor");
out.print("[ ");
for (double d : ds) {
toOut(d);
}
out.print(" ]");
toOut("int diffuseDoubleSided");
toOut( new int[] {1});
lineEnd();
}
private int randTag() {
return (int) (Math.random()*1000);
}
public void RiColorSample(int n, double[] a, double[] b) {
out.print("ColorSamples");
toOut(a);
toOut(b);
lineEnd();
}
public void RiConcatTransform(double[][] t) {
simple("ConcatTransform",t);
}
public void RiConcatTransform(double[] t) {
simple("ConcatTransform",t);
}
public void RiCone(double height, double radius, double max, Object... os ) {
out.print("Cone ");
toOut(height);
toOut(radius);
toOut(max);
toOut(os);
lineEnd();
}
public void RiCoordinateSystem(String name) {
simple("CoordinateSystem",name);
}
public void RiCoordSysTransform(String name) {
simple("CoordinateSysTransform",name);
}
public void RiCropWindow(double... ds) {
out.print("CropWindow ");
for (double d : ds)
toOut(d);
lineEnd();
}
public void RiCurves(String type, int ncurves, int[] nverts, String wrap, Object... os) {
out.print("Curves ");
toOut(type);
toOut(nverts);
toOut(wrap);
toOut(os);
lineEnd();
}
public void RiCylinder(double radius, double min, double max, double th, Object... objects) {
out.print("Cylinder ");
toOut(radius);
toOut(min);
toOut(max);
toOut(th);
toOut(objects);
lineEnd();
}
public void RiDeclare(String name, String type) {
out.print("Declare ");
toOut(name);
toOut(type);
lineEnd();
}
public void RiDeformation(String name, Object... os) {
simple("Deformation",name,os);
}
public void RiDepthOfField(double fs, double fl, double fd) {
out.print("DepthOfField ");
toOut(fs);
toOut(fl);
toOut(fd);
lineEnd();
}
public void RiDetail(double[] ds) {
out.print("Detail ");
for (double d1 : ds) {
double d = d1;
toOut(d);
}
lineEnd();
}
public void RiDetailRange(double... ds) {
out.print("DetailRange ");
for (double d : ds) {
toOut(d);
}
lineEnd();
}
public void RiDisk(double h, double r, double t, Object... os) {
out.print("Disk ");
toOut(h);
toOut(r);
toOut(t);
toOut(os);
lineEnd();
}
public void RiDisplacement(String name, Object... os) {
simple("Displacement",name,os);
}
public void RiErrorHandler(String n) {
simple("ErrorHandler",n);
}
public void RiExposure(double g, double gamma) {
out.print("Exposure ");
toOut(g);
toOut(gamma);
lineEnd();
}
public void RiExterior(String name, Object... os) {
simple("Exterior",name,os);
}
public void RiFrameAspectRatio(double d) {
out.print("FrameAspectRatio ");
toOut(d);
lineEnd();
}
public void RiFrameBegin(int n) {
out.println("FrameBegin "+n);
}
public void RiFrameEnd() {
simple("FrameEnd");
}
public void RiGeneralPolygon(int loops, int[] verts, Object... os) {
out.print("GeneralPolygon ");
toOut(verts);
toOut(os);
lineEnd();
}
public void RiGeometricApproximation(String s, double d) {
out.print("GeometricApproximation ");
toOut(d);
lineEnd();
}
public void RiGeometry(String name, Object... os) {
simple("Geometry",name,os);
}
public void RiHider(String name, Object... os) {
simple("Hider ", name, os);
}
public void RiHyperboloid(double[] a, double[] b, double angle, Object... os) {
out.print("Hyperboloid ");
for (double d : a)
toOut(d);
for (double d : b)
toOut(d);
toOut(angle);
toOut(os);
lineEnd();
}
public void RiIdentity() {
simple("Identity");
}
public void RiIlluminate(int handle, int onoff) {
out.print("Illuminate ");
toOut(handle);
toOut(onoff);
lineEnd();
}
public void RiImager(String name, Object... os) {
simple("Imager",name,os);
}
public void RiInterior(String name, Object... os) {
simple("Interior",name,os);
}
//makeBump
//MakeCubeEnvironment
//MakeLatLongEnv
public void RiMakeShadow(String picturename, String textureName, Object... os) {
out.print("MakeShadow ");
toOut(picturename);
toOut(textureName);
toOut(os);
lineEnd();
}
//Maketexture
public void RiMatte(int onoff) {
simple("Matte",onoff);
}
/*
* MotionBegin [ t0 t1... tn-1 ]
MotionEnd -
*/
public void RiMotionBegin( int n, double... ds ) {
out.print("MotionBegin ");
out.print("[ ");
if (n != ds.length)
System.out.println("Warning - number of timesteps in RiMotionBegin is not the same" +
" as parameter n (cs.amherst.edu warning");
for (double d : ds) {
out.print(d+" ");
}
out.print(" ]");
lineEnd();
}
public void RiMotionEnd () {
out.println("MotionEnd ");
lineEnd();
}
public void RiNuPatch(int nu, int uorder, double[] uknot, double umin, double umax,
int nv, int vorder, double[] vknot, double vmin, double vmax, Object... os) {
out.print("NuPatch ");
toOut(nu);
toOut(uorder);
toOut(uknot);
toOut(umin);
toOut(umax);
toOut(nv);
toOut(vorder);
toOut(vknot);
toOut(vmin);
toOut(vmax);
toOut(os);
lineEnd();
}
private int objects = 0;
public int RiObjectBegin() {
objects++;
out.println("ObjectBegin "+objects);
return objects;
}
public void RiObjectEnd() {
simple("ObjectEnd");
}
public void RiObjectInstance(int obj) {
simple("ObjectInstance",obj);
}
public void RiOpacity(double[] c) {
out.print("Opacity ");
for (double d : c)
toOut(d);
lineEnd();
}
public void RiOption(String name, Object... os) {
simple("Option",name,os);
}
public void RiOrientation(String orient) {
simple("Orientation",orient);
}
public void RiParaboloid(double rax, double zmin, double zmax, double th, Object... os) {
out.print("Paraboloid ");
toOut(rax);
toOut(zmin);
toOut(zmax);
toOut(th);
toOut(os);
lineEnd();
}
public void RiPatch(String name, Object... os) {
simple("Patch",name,os);
}
public void RiPatchMesh(String type, int nu, String uwrap, int nv,
String vwrap, Object... os) {
out.print("PatchMesh ");
toOut(type);
toOut(nu);
toOut(uwrap);
toOut(nv);
toOut(vwrap);
toOut(os);
lineEnd();
}
public void RiPerspective(double fov) {
simple("Perspective",fov);
}
public void RiPixelFilter(String name, double xw, double yw) {
out.print("PixelFilter ");
toOut(name);
toOut(xw);
toOut(yw);
lineEnd();
}
public void RiPixelSampleImager(String name, Object... os) {
simple("PixelSampleImager",name,os);
}
public void RiPixelVariance(double variation) {
simple("PixelVariance",variation);
}
public void RiPointsGeneralPolygons(int npolys, int[] nloops, int[] nverts,
int[] verts, Object... os) {
out.print("PointsGeneralPolygons ");
toOut(nloops);
toOut(nverts);
toOut(verts);
toOut(os);
lineEnd();
}
public void RiPointsPolygons(int npolys, int[] nverts,
int[] verts, Object... os) {
out.print("PointsPolygons ");
toOut(nverts);
toOut(verts);
toOut(os);
lineEnd();
}
public void RiSubdivisionMeshSimp ( String scheme, int nfaces, int nvertices[],
int vertices[], /*int ntags, String tags[],
int nargs[], int intargs[], double floatargs[],*/
Object... os) {
out.print("SubdivisionMesh ");
toOut(scheme);
//toOut(nfaces);
toOut(nvertices);
toOut(vertices);
//toOut(ntags);
//toOut(tags);
//toOut(nargs);
//toOut(intargs);
//toOut(floatargs);
toOut(os);
lineEnd();
}
public void RiSubdivisionMesh ( String scheme, int nfaces, int nvertices[],
int vertices[], int ntags, String tags[],
int nargs[], int intargs[], double floatargs[],
Object... os) {
out.print("SubdivisionMesh ");
toOut(scheme);
//toOut(nfaces);
toOut(nvertices);
toOut(vertices);
//toOut(ntags);
toOut(tags);
toOut(nargs);
toOut(intargs);
toOut(floatargs);
toOut(os);
lineEnd();
}
//RiProcedural
public void RiQuantize(String type, double... ds) {
out.print("Quantize ");
for (double d :ds)
toOut(d);
lineEnd();
}
public void RiRelativeDetail(double rd) {
simple("RelativeDetail",rd);
}
public void RiReverseOrientation() {
simple("ReverseOrientation");
}
public void RiScreenWindow(double... ds) {
out.print("ScreenWindow ");
for (double d : ds) {
toOut(d);
}
lineEnd();
}
public void RiShadingInterpolation(String t) {
simple("ShadingInterpolation", t);
}
public void RiShadingRate(double r) {
simple("ShadingRate",r);
}
public void RiShutter(double o, double c) {
out.print("Shutter ");
toOut(o);
toOut(c);
lineEnd();
}
public void RiSides(int r) {
simple("Sides",r);
}
public void RiSkew(double... ds) {
out.print("Skew ");
for (double d : ds)
toOut(d);
lineEnd();
}
public void RiSolidBegin(String name) {
simple("SolidBegin",name);
}
public void RiSolidEnd() {
simple("SolidEnd");
}
public void RiSphere(double radius, double zmin, double zmax, double theta,
Object... os) {
out.print("Sphere ");
toOut(radius);
toOut(zmin);
toOut(zmax);
toOut(theta);
toOut(os);
lineEnd();
}
public void RiTextureCoordinates(double...ds) {
out.print("TextureCoordinates");
for (double d : ds)
toOut(d);
lineEnd();
}
public void RiTorus ( double majorradius, double minorradius,
double phimin, double phimax, double thetamax,
Object... os) {
out.print("Torus ");
toOut(majorradius);
toOut(minorradius);
toOut(phimin);
toOut(phimax);
toOut(thetamax);
toOut(os);
lineEnd();
}
public void RiTransform(double[][] t) {
out.print("Transform ");
toOut(t);
lineEnd();
}
//Trimcurves
private void simple(String meth, double x, double y) {
out.print(meth+" ");
toOut(x);
toOut(y);
lineEnd();
}
private void simple(String meth, double fov) {
out.print(meth+" ");
toOut(fov);
lineEnd();
}
private void simple(String meth, int onoff) {
out.print(meth+" ");
toOut(onoff);
lineEnd();
}
private void simple(String meth, String name) {
out.print(meth+" ");
toOut(name);
lineEnd();
}
private void simple(String meth, double[][] t) {
out.print(meth+" ");
toOut(t);
lineEnd();
}
private void simple(String meth, double[] t) {
out.print(meth+" ");
toOut(t);
lineEnd();
}
private void simple(String method, String name, Object[] os) {
out.print(method+" ");
toOut(name);
toOut(os);
lineEnd();
}
private void simple(String s) {
out.print(s);
lineEnd();
}
private void lineEnd() {
out.println();
}
private void toOut(int n, int[] a) {
out.print("[ ");
for (int i=0; i<n; i++)
out.print(a[i]+" ");
out.print("] ");
}
private void toOut(Object[] objects) {
for (Object o : objects) {
if (o == null) break;
toOut(o);
}
}
private void toOut(String[] ds) {
out.print("[ ");
for (String d : ds) {
toOut(d);
}
out.print(" ] ");
}
private void toOut(Object o) {
if (o instanceof String)
toOut((String) o);
else if (o instanceof Integer)
toOut((Integer) o);
else if (o instanceof Double)
toOut((Double) o);
else if (o instanceof Double[][][]) {
Double ds[][][] = (Double[][][]) o;
out.print("[ ");
for (Double[][] dl : ds) {
for (Double d[] : dl)
for (Double d2 : d)
toOut(d2);
}
out.print(" ] ");
}
else if (o instanceof double[][][]) {
double ds[][][] = (double[][][]) o;
out.print("[ ");
for (double[][] dl : ds) {
for (double d[] : dl)
for (double d2 : d)
toOut(d2);
}
out.print(" ] ");
}else if (o instanceof int[]) {
int ds[] = (int[]) o;
out.print("[ ");
for (int d : ds) {
toOut(d);
}
out.print(" ] ");
}
else if (o instanceof double[]) {
double ds[] = (double[]) o;
out.print("[ ");
for (double d : ds) {
toOut(d);
}
out.print(" ] ");
}
else if (o instanceof String)
toOut((String) o);
else if (o instanceof Integer)
toOut((Integer) o);
else if (o instanceof double[][]) {
double ds[][] = (double[][]) o;
out.print("[ ");
for (double[] dl : ds) {
for (double d : dl)
toOut(d);
}
out.print(" ] ");
}
else if (o instanceof Double[][]) {
Double ds[][] = (Double[][]) o;
out.print("[ ");
for (Double[] dl : ds) {
for (Double d : dl)
toOut(d);
}
out.print(" ] ");
}
else if (o instanceof double[]) {
double ds[] = (double[]) o;
out.print("[");
for (double d : ds) {
toOut(d);
}
out.print(" ] ");
}
else
toOut("Problem with "+o.getClass());
}
private void toOut(Integer i) {
out.print(i.intValue()+" ");
}
private void toOut(Double i) {
out.print(i.doubleValue()+" ");
}
private void toOut(int i) {
out.print(i+" ");
}
private void toOut(double d) {
out.print(d+" ");
}
private void toOut(String name) {
out.print("\""+name+"\" ");
}
protected void RiColor(double d, double e, double f) {
double[] c = {d,e,f};
RiColor(c);
}
protected void RiPoints(int n,Object... os) {
out.print("Points ");
toOut(os);
lineEnd();
}
protected void RiReadArchive(String string, Object... os) {
out.print("ReadArchive ");
toOut(string);
toOut(os);
lineEnd();
}
//Below here added 2020
protected void RiBxdf(String s, Object... os) {
out.print("Bxdf ");
toOut(s);
toOut(os);
lineEnd();
}
public void RiIntegrator(String name, Object... os) {
simple("Integrator ", name, os);
}
protected void RiLight(String string, Object...os) {
simple("Light",string,os);
}
/* protected void RiHider(String s, Object... os) {
out.print("Hider ");
toOut(s);
toOut(os);
lineEnd();
}
*/
private double[] currentColor = new double[] {1,1,1};
}
| dafg05/Raytracer | Ri.java |
1,040 | /*************************************************************************
* Compilation: javac In.java
* Execution: java In (basic test --- see source for required files)
*
* Reads in data of various types from standard input, files, and URLs.
*
*************************************************************************/
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
import java.util.regex.Pattern;
/**
* <i>Input</i>. This class provides methods for reading strings
* and numbers from standard input, file input, URLs, and sockets.
* <p>
* The Locale used is: language = English, country = US. This is consistent
* with the formatting conventions with Java floating-point literals,
* command-line arguments (via {@link Double#parseDouble(String)})
* and standard output.
* <p>
* For additional documentation, see
* <a href="http://introcs.cs.princeton.edu/31datatype">Section 3.1</a> of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i>
* by Robert Sedgewick and Kevin Wayne.
* <p>
* Like {@link Scanner}, reading a token also consumes preceding Java
* whitespace, reading a full line consumes
* the following end-of-line delimeter, while reading a character consumes
* nothing extra.
* <p>
* Whitespace is defined in {@link Character#isWhitespace(char)}. Newlines
* consist of \n, \r, \r\n, and Unicode hex code points 0x2028, 0x2029, 0x0085;
* see <tt><a href="http://www.docjar.com/html/api/java/util/Scanner.java.html">
* Scanner.java</a></tt> (NB: Java 6u23 and earlier uses only \r, \r, \r\n).
*/
public final class In {
private Scanner scanner;
/*** begin: section (1 of 2) of code duplicated from In to StdIn */
// assume Unicode UTF-8 encoding
private static final String charsetName = "UTF-8";
// assume language = English, country = US for consistency with System.out.
private static final java.util.Locale usLocale =
new java.util.Locale("en", "US");
// the default token separator; we maintain the invariant that this value
// is held by the scanner's delimiter between calls
private static final Pattern WHITESPACE_PATTERN
= Pattern.compile("\\p{javaWhitespace}+");
// makes whitespace characters significant
private static final Pattern EMPTY_PATTERN
= Pattern.compile("");
// used to read the entire input. source:
// http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html
private static final Pattern EVERYTHING_PATTERN
= Pattern.compile("\\A");
/*** end: section (1 of 2) of code duplicated from In to StdIn */
/**
* Create an input stream from standard input.
*/
public In() {
scanner = new Scanner(new BufferedInputStream(System.in), charsetName);
scanner.useLocale(usLocale);
}
/**
* Create an input stream from a socket.
*/
public In(java.net.Socket socket) {
try {
InputStream is = socket.getInputStream();
scanner = new Scanner(new BufferedInputStream(is), charsetName);
scanner.useLocale(usLocale);
}
catch (IOException ioe) {
System.err.println("Could not open " + socket);
}
}
/**
* Create an input stream from a URL.
*/
public In(URL url) {
try {
URLConnection site = url.openConnection();
InputStream is = site.getInputStream();
scanner = new Scanner(new BufferedInputStream(is), charsetName);
scanner.useLocale(usLocale);
}
catch (IOException ioe) {
System.err.println("Could not open " + url);
}
}
/**
* Create an input stream from a file.
*/
public In(File file) {
try {
scanner = new Scanner(file, charsetName);
scanner.useLocale(usLocale);
}
catch (IOException ioe) {
System.err.println("Could not open " + file);
}
}
/**
* Create an input stream from a filename or web page name.
*/
public In(String s) {
try {
// first try to read file from local file system
File file = new File(s);
if (file.exists()) {
scanner = new Scanner(file, charsetName);
scanner.useLocale(usLocale);
return;
}
// next try for files included in jar
URL url = getClass().getResource(s);
// or URL from web
if (url == null) { url = new URL(s); }
URLConnection site = url.openConnection();
InputStream is = site.getInputStream();
scanner = new Scanner(new BufferedInputStream(is), charsetName);
scanner.useLocale(usLocale);
}
catch (IOException ioe) {
System.err.println("Could not open " + s);
}
}
/**
* Create an input stream from a given Scanner source; use with
* <tt>new Scanner(String)</tt> to read from a string.
* <p>
* Note that this does not create a defensive copy, so the
* scanner will be mutated as you read on.
*/
public In(Scanner scanner) {
this.scanner = scanner;
}
/**
* Does the input stream exist?
*/
public boolean exists() {
return scanner != null;
}
/*** begin: section (2 of 2) of code duplicated from In to StdIn,
* with all methods changed from "public" to "public static" ***/
/**
* Is the input empty (except possibly for whitespace)? Use this
* to know whether the next call to {@link #readString()},
* {@link #readDouble()}, etc will succeed.
*/
public boolean isEmpty() {
return !scanner.hasNext();
}
/**
* Does the input have a next line? Use this to know whether the
* next call to {@link #readLine()} will succeed. <p> Functionally
* equivalent to {@link #hasNextChar()}.
*/
public boolean hasNextLine() {
return scanner.hasNextLine();
}
/**
* Is the input empty (including whitespace)? Use this to know
* whether the next call to {@link #readChar()} will succeed. <p> Functionally
* equivalent to {@link #hasNextLine()}.
*/
public boolean hasNextChar() {
scanner.useDelimiter(EMPTY_PATTERN);
boolean result = scanner.hasNext();
scanner.useDelimiter(WHITESPACE_PATTERN);
return result;
}
/**
* Read and return the next line.
*/
public String readLine() {
String line;
try { line = scanner.nextLine(); }
catch (Exception e) { line = null; }
return line;
}
/**
* Read and return the next character.
*/
public char readChar() {
scanner.useDelimiter(EMPTY_PATTERN);
String ch = scanner.next();
assert (ch.length() == 1) : "Internal (Std)In.readChar() error!"
+ " Please contact the authors.";
scanner.useDelimiter(WHITESPACE_PATTERN);
return ch.charAt(0);
}
/**
* Read and return the remainder of the input as a string.
*/
public String readAll() {
if (!scanner.hasNextLine())
return "";
String result = scanner.useDelimiter(EVERYTHING_PATTERN).next();
// not that important to reset delimeter, since now scanner is empty
scanner.useDelimiter(WHITESPACE_PATTERN); // but let's do it anyway
return result;
}
/**
* Read and return the next string.
*/
public String readString() {
return scanner.next();
}
/**
* Read and return the next int.
*/
public int readInt() {
return scanner.nextInt();
}
/**
* Read and return the next double.
*/
public double readDouble() {
return scanner.nextDouble();
}
/**
* Read and return the next float.
*/
public float readFloat() {
return scanner.nextFloat();
}
/**
* Read and return the next long.
*/
public long readLong() {
return scanner.nextLong();
}
/**
* Read and return the next short.
*/
public short readShort() {
return scanner.nextShort();
}
/**
* Read and return the next byte.
*/
public byte readByte() {
return scanner.nextByte();
}
/**
* Read and return the next boolean, allowing case-insensitive
* "true" or "1" for true, and "false" or "0" for false.
*/
public boolean readBoolean() {
String s = readString();
if (s.equalsIgnoreCase("true")) return true;
if (s.equalsIgnoreCase("false")) return false;
if (s.equals("1")) return true;
if (s.equals("0")) return false;
throw new java.util.InputMismatchException();
}
/**
* Read all strings until the end of input is reached, and return them.
*/
public String[] readAllStrings() {
// we could use readAll.trim().split(), but that's not consistent
// since trim() uses characters 0x00..0x20 as whitespace
String[] tokens = WHITESPACE_PATTERN.split(readAll());
if (tokens.length == 0 || tokens[0].length() > 0)
return tokens;
String[] decapitokens = new String[tokens.length-1];
for (int i = 0; i < tokens.length-1; i++)
decapitokens[i] = tokens[i+1];
return decapitokens;
}
/**
* Read all ints until the end of input is reached, and return them.
*/
public int[] readAllInts() {
String[] fields = readAllStrings();
int[] vals = new int[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Integer.parseInt(fields[i]);
return vals;
}
/**
* Read all doubles until the end of input is reached, and return them.
*/
public double[] readAllDoubles() {
String[] fields = readAllStrings();
double[] vals = new double[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Double.parseDouble(fields[i]);
return vals;
}
/*** end: section (2 of 2) of code duplicated from In to StdIn */
/**
* Close the input stream.
*/
public void close() {
scanner.close();
}
/**
* Reads all ints from a file
* @deprecated Clearer to use
* <tt>new In(filename)</tt>.{@link #readAllInts()}
*/
public static int[] readInts(String filename) {
return new In(filename).readAllInts();
}
/**
* Reads all doubles from a file
* @deprecated Clearer to use
* <tt>new In(filename)</tt>.{@link #readAllDoubles()}
*/
public static double[] readDoubles(String filename) {
return new In(filename).readAllDoubles();
}
/**
* Reads all strings from a file
* @deprecated Clearer to use
* <tt>new In(filename)</tt>.{@link #readAllStrings()}
*/
public static String[] readStrings(String filename) {
return new In(filename).readAllStrings();
}
/**
* Reads all ints from stdin
* @deprecated Clearer to use {@link StdIn#readAllInts()}
*/
public static int[] readInts() {
return new In().readAllInts();
}
/**
* Reads all doubles from stdin
* @deprecated Clearer to use {@link StdIn#readAllDoubles()}
*/
public static double[] readDoubles() {
return new In().readAllDoubles();
}
/**
* Reads all strings from stdin
* @deprecated Clearer to use {@link StdIn#readAllStrings()}
*/
public static String[] readStrings() {
return new In().readAllStrings();
}
/**
* Test client.
*/
public static void main(String[] args) {
In in;
String urlName = "http://introcs.cs.princeton.edu/stdlib/InTest.txt";
// read from a URL
System.out.println("readAll() from URL " + urlName);
System.out.println("---------------------------------------------------------------------------");
try {
in = new In(urlName);
System.out.println(in.readAll());
}
catch (Exception e) { System.out.println(e); }
System.out.println();
// read one line at a time from URL
System.out.println("readLine() from URL " + urlName);
System.out.println("---------------------------------------------------------------------------");
try {
in = new In(urlName);
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
}
catch (Exception e) { System.out.println(e); }
System.out.println();
// read one string at a time from URL
System.out.println("readString() from URL " + urlName);
System.out.println("---------------------------------------------------------------------------");
try {
in = new In(urlName);
while (!in.isEmpty()) {
String s = in.readString();
System.out.println(s);
}
}
catch (Exception e) { System.out.println(e); }
System.out.println();
// read one line at a time from file in current directory
System.out.println("readLine() from current directory");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("./InTest.txt");
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
}
catch (Exception e) { System.out.println(e); }
System.out.println();
// read one line at a time from file using relative path
System.out.println("readLine() from relative path");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("../stdlib/InTest.txt");
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
}
catch (Exception e) { System.out.println(e); }
System.out.println();
// read one char at a time
System.out.println("readChar() from file");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("InTest.txt");
while (!in.isEmpty()) {
char c = in.readChar();
System.out.print(c);
}
}
catch (Exception e) { System.out.println(e); }
System.out.println();
System.out.println();
// read one line at a time from absolute OS X / Linux path
System.out.println("readLine() from absolute OS X / Linux path");
System.out.println("---------------------------------------------------------------------------");
in = new In("/n/fs/introcs/www/java/stdlib/InTest.txt");
try {
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
}
catch (Exception e) { System.out.println(e); }
System.out.println();
// read one line at a time from absolute Windows path
System.out.println("readLine() from absolute Windows path");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("G:\\www\\introcs\\stdlib\\InTest.txt");
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
System.out.println();
}
catch (Exception e) { System.out.println(e); }
System.out.println();
}
}
| nipra/Jafun | books/algorithms-4e/stdlib/In.java |
1,041 | import java.io.*;
import java_cup.runtime.*;
/**
* Main program to test the cflat parser.
*
* There should be 2 command-line arguments:
* 1. the file to be parsed
* 2. the output file into which the AST built by the parser should be
* unparsed
* The program opens the two files, creates a scanner and a parser, and
* calls the parser. If the parse is successful, the AST is unparsed.
*/
public class P3 {
public static void main(String[] args)
throws IOException // may be thrown by the scanner
{
// check for command-line args
if (args.length != 2) {
System.err.println("please supply name of file to be parsed " +
"and name of file for unparsed version.");
System.exit(-1);
}
// open input file
FileReader inFile = null;
try {
inFile = new FileReader(args[0]);
} catch (FileNotFoundException ex) {
System.err.println("File " + args[0] + " not found.");
System.exit(-1);
}
// open output file
PrintWriter outFile = null;
try {
outFile = new PrintWriter(args[1]);
} catch (FileNotFoundException ex) {
System.err.println("File " + args[1] +
" could not be opened for writing.");
System.exit(-1);
}
parser P = new parser(new Yylex(inFile));
Symbol root = null; // the parser will return a Symbol whose value
// field is the translation of the root nonterminal
// (i.e., of the nonterminal "program")
try {
root = P.parse(); // do the parse
System.out.println ("program parsed correctly.");
} catch (Exception ex){
System.err.println("Exception occured during parse: " + ex);
System.exit(-1);
}
((ASTnode)root.value).unparse(outFile, 0);
outFile.close();
return;
}
}
| edydfang/UW-Madison-CS536 | P3/P3.java |
1,042 | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
Refer the following link for original code of Google Services Gradle Plugin(this is modified from that code to use it with java):
https://github.com/google/play-services-plugins/tree/master/google-services-plugin
*/
import java.io.File;
import java.util.TreeMap;
import java.util.Map;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import java.io.IOException;
import com.google.common.base.Strings;
public class gs{
private static File intermediateDir;
private static final String STATUS_DISABLED = "1";
private static final String STATUS_ENABLED = "2";
private static final String OAUTH_CLIENT_TYPE_WEB = "3";
public static void main(String[] args) throws IOException{
System.out.println("Started");
File quickstartFile = new File("google-services.json");
if (quickstartFile == null || !quickstartFile.isFile()) {
System.out.println("The Google Services Plugin cannot function without it.");
}
System.out.println("Parsing json file: " + quickstartFile.getPath());
// delete content of outputdir.
intermediateDir = new File("Interm");
deleteFolder(intermediateDir);
if (!intermediateDir.mkdirs()) {
System.out.println("Failed to create folder: " + intermediateDir);
}
try
{
JsonElement root = new JsonParser().parse(Files.newReader(quickstartFile, Charsets.UTF_8));
if (!root.isJsonObject()) {
System.out.println("Malformed root json");
}
JsonObject rootObject = root.getAsJsonObject();
Map<String, String> resValues = new TreeMap<>();
Map<String, Map<String, String>> resAttributes = new TreeMap<>();
handleProjectNumberAndProjectId(rootObject, resValues);
handleFirebaseUrl(rootObject, resValues);
JsonObject clientObject = getClientForPackageName(rootObject);
if (clientObject != null) {
handleAnalytics(clientObject, resValues);
handleMapsService(clientObject, resValues);
handleGoogleApiKey(clientObject, resValues);
handleGoogleAppId(clientObject, resValues);
handleWebClientId(clientObject, resValues);
} else {
System.out.println("No matching client found for package name ");
}
// write the values file.
File values = new File(intermediateDir, "values");
if (!values.exists() && !values.mkdirs()) {
System.out.println("Failed to create folder: " + values);
}
Files.asCharSink(new File(values, "values.xml"), Charsets.UTF_8)
.write(getValuesContent(resValues, resAttributes));
}
catch (IOException ex)
{
System.out.println("FileNotFoundException");
}
}
static void deleteFolder(final File folder) {
if (!folder.exists()) {
return;
}
File[] files = folder.listFiles();
if (files != null) {
for (final File file : files) {
if (file.isDirectory()) {
deleteFolder(file);
} else {
if (!file.delete()) {
System.out.println("Failed to delete: " + file);
}
}
}
}
if (!folder.delete()) {
System.out.println("Failed to delete: " + folder);
}
}
static void handleProjectNumberAndProjectId(JsonObject rootObject, Map<String, String> resValues)
throws IOException {
JsonObject projectInfo = rootObject.getAsJsonObject("project_info");
if (projectInfo == null) {
System.out.println("Missing project_info object");
}
JsonPrimitive projectNumber = projectInfo.getAsJsonPrimitive("project_number");
if (projectNumber == null) {
System.out.println("Missing project_info/project_number object");
}
resValues.put("gcm_defaultSenderId", projectNumber.getAsString());
JsonPrimitive projectId = projectInfo.getAsJsonPrimitive("project_id");
if (projectId == null) {
System.out.println("Missing project_info/project_id object");
}
resValues.put("project_id", projectId.getAsString());
JsonPrimitive bucketName = projectInfo.getAsJsonPrimitive("storage_bucket");
if (bucketName != null) {
resValues.put("google_storage_bucket", bucketName.getAsString());
}
}
static void handleFirebaseUrl(JsonObject rootObject, Map<String, String> resValues)
throws IOException {
JsonObject projectInfo = rootObject.getAsJsonObject("project_info");
if (projectInfo == null) {
System.out.println("Missing project_info object");
}
JsonPrimitive firebaseUrl = projectInfo.getAsJsonPrimitive("firebase_url");
if (firebaseUrl != null) {
resValues.put("firebase_database_url", firebaseUrl.getAsString());
}
}
static void handleAnalytics(JsonObject clientObject, Map<String, String> resValues)
throws IOException {
JsonObject analyticsService = getServiceByName(clientObject, "analytics_service");
if (analyticsService == null) return;
JsonObject analyticsProp = analyticsService.getAsJsonObject("analytics_property");
if (analyticsProp == null) return;
JsonPrimitive trackingId = analyticsProp.getAsJsonPrimitive("tracking_id");
if (trackingId == null) return;
resValues.put("ga_trackingId", trackingId.getAsString());
File xml = new File(intermediateDir, "xml");
if (!xml.exists() && !xml.mkdirs()) {
System.out.println("Failed to create folder: " + xml);
}
Files.asCharSink(new File(xml, "global_tracker.xml"), Charsets.UTF_8)
.write(getGlobalTrackerContent(trackingId.getAsString()));
}
static void handleMapsService(JsonObject clientObject, Map<String, String> resValues)
throws IOException {
JsonObject mapsService = getServiceByName(clientObject, "maps_service");
if (mapsService == null) return;
String apiKey = getAndroidApiKey(clientObject);
if (apiKey != null) {
resValues.put("google_maps_key", apiKey);
return;
}
System.out.println("Missing api_key/current_key object");
}
static JsonObject getClientForPackageName(JsonObject jsonObject) {
JsonArray array = jsonObject.getAsJsonArray("client");
if (array != null) {
final int count = array.size();
for (int i = 0; i < count; i++) {
JsonElement clientElement = array.get(i);
if (clientElement == null || !clientElement.isJsonObject()) {
continue;
}
JsonObject clientObject = clientElement.getAsJsonObject();
JsonObject clientInfo = clientObject.getAsJsonObject("client_info");
if (clientInfo == null) continue;
JsonObject androidClientInfo = clientInfo.getAsJsonObject("android_client_info");
if (androidClientInfo == null) continue;
JsonPrimitive clientPackageName = androidClientInfo.getAsJsonPrimitive("package_name");
if (clientPackageName == null) continue;
if (getApplicationId().equals(clientPackageName.getAsString())) {
return clientObject;
}
}
}
return null;
}
static JsonObject getServiceByName(JsonObject clientObject, String serviceName) {
JsonObject services = clientObject.getAsJsonObject("services");
if (services == null) return null;
JsonObject service = services.getAsJsonObject(serviceName);
if (service == null) return null;
JsonPrimitive status = service.getAsJsonPrimitive("status");
if (status == null) return null;
String statusStr = status.getAsString();
if (STATUS_DISABLED.equals(statusStr)) return null;
if (!STATUS_ENABLED.equals(statusStr)) {
System.out.println(
String.format(
"Status with value '%1$s' for service '%2$s' is unknown",
statusStr, serviceName));
return null;
}
return service;
}
static String getGlobalTrackerContent(String ga_trackingId) {
return "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
+ "<resources>\n"
+ " <string name=\"ga_trackingId\" translatable=\"false\">"
+ ga_trackingId
+ "</string>\n"
+ "</resources>\n";
}
static String getAndroidApiKey(JsonObject clientObject) {
JsonArray array = clientObject.getAsJsonArray("api_key");
if (array != null) {
final int count = array.size();
for (int i = 0; i < count; i++) {
JsonElement apiKeyElement = array.get(i);
if (apiKeyElement == null || !apiKeyElement.isJsonObject()) {
continue;
}
JsonObject apiKeyObject = apiKeyElement.getAsJsonObject();
JsonPrimitive currentKey = apiKeyObject.getAsJsonPrimitive("current_key");
if (currentKey == null) {
continue;
}
return currentKey.getAsString();
}
}
return null;
}
static String getApplicationId(){
return "com.example.testjsontostrings";
}
static void handleGoogleApiKey(JsonObject clientObject, Map<String, String> resValues) {
String apiKey = getAndroidApiKey(clientObject);
if (apiKey != null) {
resValues.put("google_api_key", apiKey);
// TODO: remove this once SDK starts to use google_api_key.
resValues.put("google_crash_reporting_api_key", apiKey);
return;
}
// if google_crash_reporting_api_key is missing.
System.out.println("Missing api_key/current_key object");
}
static void handleGoogleAppId(JsonObject clientObject, Map<String, String> resValues)
throws IOException {
JsonObject clientInfo = clientObject.getAsJsonObject("client_info");
if (clientInfo == null) {
// Should not happen
System.out.println("Client does not have client info");
}
JsonPrimitive googleAppId = clientInfo.getAsJsonPrimitive("mobilesdk_app_id");
String googleAppIdStr = googleAppId == null ? null : googleAppId.getAsString();
if (Strings.isNullOrEmpty(googleAppIdStr)) {
System.out.println(
"Missing Google App Id. "
+ "Please follow instructions on https://firebase.google.com/ to get a valid "
+ "config file that contains a Google App Id");
}
resValues.put("google_app_id", googleAppIdStr);
}
static void handleWebClientId(JsonObject clientObject, Map<String, String> resValues) {
JsonArray array = clientObject.getAsJsonArray("oauth_client");
if (array != null) {
final int count = array.size();
for (int i = 0; i < count; i++) {
JsonElement oauthClientElement = array.get(i);
if (oauthClientElement == null || !oauthClientElement.isJsonObject()) {
continue;
}
JsonObject oauthClientObject = oauthClientElement.getAsJsonObject();
JsonPrimitive clientType = oauthClientObject.getAsJsonPrimitive("client_type");
if (clientType == null) {
continue;
}
String clientTypeStr = clientType.getAsString();
if (!OAUTH_CLIENT_TYPE_WEB.equals(clientTypeStr)) {
continue;
}
JsonPrimitive clientId = oauthClientObject.getAsJsonPrimitive("client_id");
if (clientId == null) {
continue;
}
resValues.put("default_web_client_id", clientId.getAsString());
return;
}
}
}
static String getValuesContent(
Map<String, String> values, Map<String, Map<String, String>> attributes) {
StringBuilder sb = new StringBuilder(256);
sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<resources>\n");
for (Map.Entry<String, String> entry : values.entrySet()) {
String name = entry.getKey();
sb.append(" <string name=\"").append(name).append("\" translatable=\"false\"");
if (attributes.containsKey(name)) {
for (Map.Entry<String, String> attr : attributes.get(name).entrySet()) {
sb.append(" ").append(attr.getKey()).append("=\"").append(attr.getValue()).append("\"");
}
}
sb.append(">").append(entry.getValue()).append("</string>\n");
}
sb.append("</resources>\n");
return sb.toString();
}
}
| rupeshkumar22/google-services-java-plugin | gs.java |
1,043 | // Java program to print DFS
// traversal from a given
// graph
import java.io.*;
import java.util.*;
// This class represents a
// directed graph using adjacency
// list representation
class Graph {
private int V; // No. of vertices
// Array of lists for
// Adjacency List Representation
private LinkedList<Integer> adj[];
// Constructor
@SuppressWarnings("unchecked") Graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i = 0; i < v; ++i)
adj[i] = new LinkedList();
}
// Function to add an edge into the graph
void addEdge(int v, int w)
{
adj[v].add(w); // Add w to v's list.
}
// A function used by DFS
void DFSUtil(int v, boolean visited[])
{
// Mark the current node as visited and print it
visited[v] = true;
System.out.print(v + " ");
// Recur for all the vertices adjacent to this
// vertex
Iterator<Integer> i = adj[v].listIterator();
while (i.hasNext()) {
int n = i.next();
if (!visited[n])
DFSUtil(n, visited);
}
}
// The function to do DFS traversal.
// It uses recursive
// DFSUtil()
void DFS(int v)
{
// Mark all the vertices as
// not visited(set as
// false by default in java)
boolean visited[] = new boolean[V];
// Call the recursive helper
// function to print DFS
// traversal
DFSUtil(v, visited);
}
// Driver's Code
public static void main(String args[])
{
Graph g = new Graph(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
System.out.println(
"Following is Depth First Traversal "
+ "(starting from vertex 2)");
// Function call
g.DFS(2);
}
}
// This code is contributed by Aakash Hasija
| Ashutoshak5384/html-basic-web-page | 01.java |
1,044 | import java.io.*;
import java.util.*;
/**
* IO class: Input and Output for Primitive data types
* Written by Spandan
* Pass a FileReader object to the constructer to read Files
*/
public class IO {
static BufferedReader in;
IO () {
in = new BufferedReader(new InputStreamReader(System.in));
}
IO (FileReader f) {
in = new BufferedReader(f);
}
// Input
String getLine () {
try {
return in.readLine();
} catch (IOException ioe) {}
return "";
}
int getInt () {
try {
return Integer.parseInt(in.readLine());
} catch (NumberFormatException n) {
System.err.println("Input mismatch: Returning default value 0");
return 0;
} catch (IOException ioe) {}
return 0;
}
float getFloat () {
try {
return Float.parseFloat(in.readLine());
} catch (NumberFormatException n) {
System.err.println("Input mismatch: Returning default value 0");
return 0.0f;
} catch (IOException ioe) {}
return 0.0f;
}
double getDouble () {
try {
return Double.parseDouble(in.readLine());
} catch (NumberFormatException n) {
System.err.println("Input mismatch: Returning default value 0");
return 0.0;
} catch (IOException ioe) {}
return 0.0;
}
short getShort () {
try {
return Short.parseShort(in.readLine());
} catch (NumberFormatException n) {
System.err.println("Input mismatch: Returning default value 0");
return 0;
} catch (IOException ioe) {}
return 0;
}
long getLong () {
try {
return Long.parseLong(in.readLine());
} catch (NumberFormatException n) {
System.err.println("Input mismatch: Returning default value 0");
return 0;
} catch (IOException ioe) {}
return 0;
}
char getChar () {
try {
return in.readLine().charAt(0);
} catch (IOException ioe) {}
return '\0';
}
byte getByte () {
try {
return Byte.parseByte(in.readLine());
} catch (NumberFormatException n) {
System.err.println("Input mismatch: Returning default value 0");
return 0;
} catch (IOException ioe) {}
return 0;
}
boolean getBool () {
try {
return Boolean.parseBoolean(in.readLine());
} catch (NumberFormatException n) {
System.err.println("Input mismatch: Returning default value false");
return false;
} catch (IOException ioe) {}
return false;
}
// Output functions
public static void print (String s) {
System.out.print(s);
}
public static void println (String s) {
System.out.println(s);
}
public static void println (int s) {
System.out.println(s);
}
public static void println (float s) {
System.out.println(s);
}
public static void println (double s) {
System.out.println(s);
}
public static void println (long s) {
System.out.println(s);
}
public static void println (short s) {
System.out.println(s);
}
public static void println (byte s) {
System.out.println(s);
}
public static void println (boolean s) {
System.out.println(s);
}
public static void println (char s) {
System.out.println(s);
}
public static String toId (String text) {
String newStr = "";
if (text == null) return "";
text = text.toLowerCase();
for (int i = 0; i < text.length(); i++) {
int c = (int)text.charAt(i);
if (c >= 97 && c <= 122 || c >= ((int)'0') && c <= ((int)'9')) {
newStr += (char)c;
}
}
return newStr;
}
public static String[] arrayMod (String arr[], String opt) {
String[] arrr = Arrays.copyOf(arr, arr.length);
if (opt.startsWith("del")) {
arrr = new String[arr.length - 1];
int j = 0;
for (int i = 0; i < arr.length; i++) {
if (IO.toId(arr[i]).equals(IO.toId(opt.substring(3)))) {
i = i + 1;
continue;
}
arrr[j++] = arr[i];
}
} else if (opt.startsWith("add")) {
arrr = Arrays.copyOf(arr, arr.length + 1);
arrr[arr.length] = opt.substring(3);
}
return arrr;
}
public static String join (char[] arr, String s) {
String n = "";
for (int i = 0; i < arr.length; i++) {
n = n + arr[i] + ((i == arr.length - 1) ? "" : s);
}
return n;
}
public static int indexOf(char[] array, char key) {
for (int i = 0; i < array.length; i++) {
if (key == array[i]) {
return i;
}
}
return -1;
}
public static int indexOf(String[] array, String key) {
for (int i = 0; i < array.length; i++) {
if (key.equals(array[i])) {
return i;
}
}
return -1;
}
}
| Spandamn/Pokemon-Showdown-Java-Bot | IO.java |
1,045 | /**
* @name Simple Java Calculator
* @package ph.calculator
* @file UI.java
* @author SORIA Pierre-Henry
* @email pierrehs@hotmail.com
* @link http://github.com/pH-7
* @copyright Copyright Pierre-Henry SORIA, All Rights Reserved.
* @license Apache (http://www.apache.org/licenses/LICENSE-2.0)
* @create 2012-03-30
*
* @modifiedby Achintha Gunasekara
* @modifiedby Kydon Chantzaridis
* @modweb http://www.achinthagunasekara.com
* @modemail contact@achinthagunasekara.com
* @modemail kchantza@csd.auth.gr
*/
//package simplejavacalculator;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import java.awt.Font;
import javax.swing.Box;
import javax.swing.BoxLayout;
import java.awt.Image;
import javax.swing.ImageIcon;
import java.io.*;
public class UI implements ActionListener {
private final JFrame frame;
private final JPanel panel;
private final JPanel panelSub1;
private final JPanel panelSub2;
private final JPanel panelSub3;
private final JPanel panelSub4;
private final JPanel panelSub5;
private final JPanel panelSub6;
private final JPanel panelSub7;
private final JPanel panelSub8;
private final JTextArea text;
private final JButton but[], butAdd, butMinus, butMultiply, butDivide,
butEqual, butCancel, butSquareRoot, butSquare, butOneDividedBy,
butCos, butSin, butTan, butxpowerofy, butlog, butrate, butabs, butBinary;
private final Calculator calc;
private final String[] buttonValue = {"0", "1", "2", "3", "4", "5", "6",
"7", "8", "9"};
private final Font font;
private final Font textFont;
private ImageIcon image;
private BufferedImageCustom imageReturn;
public UI() throws IOException {
frame = new JFrame("Calculator PH");
imageReturn = new BufferedImageCustom();
image = new ImageIcon(imageReturn.imageReturn());
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panelSub1 = new JPanel(new FlowLayout());
panelSub2 = new JPanel(new FlowLayout());
panelSub3 = new JPanel(new FlowLayout());
panelSub4 = new JPanel(new FlowLayout());
panelSub5 = new JPanel(new FlowLayout());
panelSub6 = new JPanel(new FlowLayout());
panelSub7 = new JPanel(new FlowLayout());
panelSub8 = new JPanel(new FlowLayout());
font = new Font("Consolas",Font.PLAIN, 18);
text = new JTextArea(1, 30);
textFont = new Font("Consolas",Font.BOLD, 24);
but = new JButton[10];
for (int i = 0; i < 10; i++) {
but[i] = new JButton(String.valueOf(i));
}
butAdd = new JButton("+");
butMinus = new JButton("-");
butMultiply = new JButton("*");
butDivide = new JButton("/");
butEqual = new JButton("=");
butSquareRoot = new JButton("sqrt");
butSquare = new JButton("x*x");
butOneDividedBy = new JButton("1/x");
butCos = new JButton("Cos");
butSin = new JButton("Sin");
butTan = new JButton("Tan");
butxpowerofy = new JButton("x^y");
butlog = new JButton("log10(x)");
butrate = new JButton("x%");
butabs = new JButton("abs(x)");
butCancel = new JButton("C");
butBinary = new JButton("Bin");
calc = new Calculator();
}
public void init() {
frame.setSize(450, 450);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setIconImage(image.getImage());
text.setFont(textFont);
text.setEditable(false);
for (int i = 0; i < 10; i++) {
but[i].setFont(font);
}
butAdd.setFont(font);
butMinus.setFont(font);
butMultiply.setFont(font);
butDivide.setFont(font);
butEqual.setFont(font);
butSquareRoot.setFont(font);
butSquare.setFont(font);
butOneDividedBy.setFont(font);
butCos.setFont(font);
butSin.setFont(font);
butTan.setFont(font);
butxpowerofy.setFont(font);
butlog.setFont(font);
butrate.setFont(font);
butabs.setFont(font);
butCancel.setFont(font);
butBinary.setFont(font);
panel.add(Box.createHorizontalStrut(100));
panelSub1.add(text);
panel.add(panelSub1);
panelSub2.add(but[1]);
panelSub2.add(but[2]);
panelSub2.add(but[3]);
panelSub2.add(Box.createHorizontalStrut(15));
panelSub2.add(butAdd);
panelSub2.add(butMinus);
panel.add(panelSub2);
panelSub3.add(but[4]);
panelSub3.add(but[5]);
panelSub3.add(but[6]);
panelSub3.add(Box.createHorizontalStrut(15));
panelSub3.add(butMultiply);
panelSub3.add(butDivide);
panel.add(panelSub3);
panelSub4.add(but[7]);
panelSub4.add(but[8]);
panelSub4.add(but[9]);
panelSub4.add(Box.createHorizontalStrut(15));
panelSub4.add(butEqual);
panelSub4.add(butCancel);
panel.add(panelSub4);
panelSub5.add(Box.createHorizontalStrut(92));
panelSub5.add(but[0]);
panelSub5.add(Box.createHorizontalStrut(210));
panel.add(panelSub5);
panelSub6.add(butSquare);
panelSub6.add(butSquareRoot);
panelSub6.add(butOneDividedBy);
panelSub6.add(butxpowerofy);
panel.add(panelSub6);
panelSub7.add(butCos);
panelSub7.add(butSin);
panelSub7.add(butTan);
panel.add(panelSub7);
panelSub8.add(butlog);
panelSub8.add(butrate);
panelSub8.add(butabs);
panelSub8.add(butBinary);
panel.add(panelSub8);
for (int i = 0; i < 10; i++) {
but[i].addActionListener(this);
}
butAdd.addActionListener(this);
butMinus.addActionListener(this);
butMultiply.addActionListener(this);
butDivide.addActionListener(this);
butSquare.addActionListener(this);
butSquareRoot.addActionListener(this);
butOneDividedBy.addActionListener(this);
butCos.addActionListener(this);
butSin.addActionListener(this);
butTan.addActionListener(this);
butxpowerofy.addActionListener(this);
butlog.addActionListener(this);
butrate.addActionListener(this);
butabs.addActionListener(this);
butBinary.addActionListener(this);
butEqual.addActionListener(this);
butCancel.addActionListener(this);
frame.add(panel);
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
final Object source = e.getSource();
Double checkNum = null;
for (int i = 0; i < 10; i++) {
if (source == but[i]) {
text.replaceSelection(buttonValue[i]);
return;
}
}
try {
checkNum = Double.parseDouble(text.getText());
} catch(NumberFormatException k) {
}
if (checkNum != null || source == butCancel) {
if (source == butAdd) {
writer(calc.calculateBi(Calculator.BiOperatorModes.add, reader()));
text.replaceSelection(butAdd.getText());
}
if (source == butMinus) {
writer(calc.calculateBi(Calculator.BiOperatorModes.minus, reader()));
text.replaceSelection(butMinus.getText());
}
if (source == butMultiply) {
writer(calc.calculateBi(Calculator.BiOperatorModes.multiply, reader()));
text.replaceSelection(butMultiply.getText());
}
if (source == butDivide) {
writer(calc.calculateBi(Calculator.BiOperatorModes.divide, reader()));
text.replaceSelection(butDivide.getText());
}
if (source == butxpowerofy) {
writer(calc.calculateBi(Calculator.BiOperatorModes.xpowerofy, reader()));
}
if (source == butSquare) {
writer(calc.calculateMono(Calculator.MonoOperatorModes.square, reader()));
}
if (source == butSquareRoot)
writer(calc.calculateMono(Calculator.MonoOperatorModes.squareRoot, reader()));
if (source == butOneDividedBy)
writer(calc.calculateMono(Calculator.MonoOperatorModes.oneDividedBy, reader()));
if (source == butCos)
writer(calc.calculateMono(Calculator.MonoOperatorModes.cos, reader()));
if (source == butSin)
writer(calc.calculateMono(Calculator.MonoOperatorModes.sin, reader()));
if (source == butTan)
writer(calc.calculateMono(Calculator.MonoOperatorModes.tan, reader()));
if (source == butlog)
writer(calc.calculateMono(Calculator.MonoOperatorModes.log, reader()));
if (source == butrate)
writer(calc.calculateMono(Calculator.MonoOperatorModes.rate, reader()));
if (source == butabs)
writer(calc.calculateMono(Calculator.MonoOperatorModes.abs, reader()));
if (source == butEqual)
writer(calc.calculateEqual(reader()));
if (source == butCancel)
writer(calc.reset());
if (source == butBinary)
parsetoBinary();
}
text.selectAll();
}
private void parsetoBinary() {
try {
text.setText("" + Long.toBinaryString(Long.parseLong(text.getText())));
} catch (NumberFormatException ex) {
System.err.println("Error while parse to binary." + ex.toString());
}
}
public Double reader() {
Double num;
String str;
str = text.getText();
num = Double.valueOf(str);
return num;
}
public void writer(final Double num) {
if (Double.isNaN(num)) {
text.setText("");
} else {
text.setText(Double.toString(num));
}
}
}
| JasmineOjeda/JQF-With-Calc | UI.java |
1,046 | /**
* I
public void bye(String s);
public void hello(String s);*/
interface I {
public void bye(String s);
public void hello(String s);
}
class B implements I{
B(){}
public void hello(String s){
System.out.println("Hello "+s+" in B");
}
public void bye(String s){
System.out.println("bye"+s+" in B");
}
}
class C{
int val;
C(int v){
val=v;
}
int add(int x){
val+=x;
return val;
}
}
class D extends C implements I{
D(int v){
super(v);
}
public void hello(String s){
System.out.println("Hello "+s+" in D("+val+")");
}
public void bye(String s){
System.out.println("Bye "+s+" in D("+val+")");
}
}
public class t {
static void callHello(I i, String s){
i.hello(s);
}
static void callBye(I i, String s){
i.bye(s);
}
public static void main(String[] args) {
B b=new B();
callHello(b, "B");
D d=new D(3);
callHello(d, args[0]);
d.add(4);
callHello(d, args[0]);
callBye(b, args[0]);
callBye(d, args[0]);
}
}
| toitataiyo/java_program | t.java |
1,048 | /**
* Solution to R2
* Created by Tim on 2017-04-17.
*/
public class R2 {
static Kattio io = new Kattio(System.in, System.out);
public static void main(String[] args) {
int r1 = io.getInt();
int Sdouble = io.getInt() * 2;
io.println(Sdouble - r1);
io.close();
}
}
| timwayburn/Kattis-Solutions-Java | R2.java |
1,052 | void deleByCopy(int xPrice)
{if(root==null)
{System.out.println(" The tree is empty, no deletion");
return;
}
Node f,p; // f will be the father of p
p=root;f=null;
while(p!=null)
{if(p.info.price == xPrice) break;//Found key x
if(xPrice < p.info.price)
{f=p;p=p.left;}
else
{f=p;p=p.right;}
}
if(p==null)
{System.out.println(" The key " + xPrice + " does not exist, no deletion");
return;
}
if(p.left==null && p.right==null) // p is a leaf node
{if(f==null) // The tree is one node
root=null;
else
{if(f.left==p)
f.left=null;
else
f.right=null;
}
return;
}
if(p.left!=null && p.right==null) // p has only left child
{if(f==null) // p is a root
root=p.left;
else
{if(f.left==p) // p is a left child
f.left=p.left;
else
f.right=p.left;
}
return;
}
if(p.left==null && p.right!=null) // p has only right child
{if(f==null) // p is a root
root=p.right;
else
{if(f.left==p) // p is aleft child
f.left=p.right;
else
f.right=p.right;
}
return;
}
if(p.left!=null && p.right!=null) // p has both left and right children
{Node q,fr,rp; // p's key will be replaced by rp's one
fr=null;
q = p.left;
rp = q;
while(rp.right!=null)
{fr=rp; rp = rp.right; // Find the right most node on the left sub-tree
}
p.info = rp.info;
if(fr==null) // rp is just a left son of p
p.left=rp.left;
else
fr.right=rp.left;
}
}
void breadth(Node p, RandomAccessFile f) throws Exception
{if(p==null) return;
Queue q = new Queue();
q.enqueue(p);Node r;
while(!q.isEmpty())
{r = q.dequeue();
fvisit(r,f);
if(r.left!=null) q.enqueue(r.left);
if(r.right!=null) q.enqueue(r.right);
}
}
Node q123= null;
void breadth2(Node p)
{if(p==null) return;
Queue q = new Queue();
q.enqueue(p);Node r;
while(!q.isEmpty())
{r = q.dequeue();
if(r.left!=null && r.right!=null && r.info.price < 7) {q123=r;break;};
if(r.left!=null) q.enqueue(r.left);
if(r.right!=null) q.enqueue(r.right);
}
}
void f3() throws Exception
{clear();
loadData(7);
String fname = "f3.txt";
File g123 = new File(fname);
if(g123.exists()) g123.delete();
RandomAccessFile f = new RandomAccessFile(fname, "rw");
breadth(root,f);
f.writeBytes("\r\n");
//------------------------------------------------------------------------------------
/*You must keep statements pre-given in this function.
Your task is to insert statements here, just after this comment,
to complete the question in the exam paper.*/
//------------------------------------------------------------------------------------
q123=null;
breadth2(root);
if(q123!=null) deleByCopy(q123.info.price);
//--------------------------------------------------------
breadth(root,f);
f.writeBytes("\r\n");
f.close();
}
| vuvanhieu/CSD201 | f3.java |
1,054 | /******************************************************************************
* Compilation: javac In.java
* Execution: java In (basic test --- see source for required files)
* Dependencies: none
*
* Reads in data of various types from standard input, files, and URLs.
*
******************************************************************************/
package edu.princeton.cs.algs4;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.Socket;
// import java.net.HttpURLConnection;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Locale;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.regex.Pattern;
/**
* <i>Input</i>. This class provides methods for reading strings
* and numbers from standard input, file input, URLs, and sockets.
* <p>
* The Locale used is: language = English, country = US. This is consistent
* with the formatting conventions with Java floating-point literals,
* command-line arguments (via {@link Double#parseDouble(String)})
* and standard output.
* <p>
* For additional documentation, see
* <a href="http://introcs.cs.princeton.edu/31datatype">Section 3.1</a> of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i>
* by Robert Sedgewick and Kevin Wayne.
* <p>
* Like {@link Scanner}, reading a token also consumes preceding Java
* whitespace, reading a full line consumes
* the following end-of-line delimeter, while reading a character consumes
* nothing extra.
* <p>
* Whitespace is defined in {@link Character#isWhitespace(char)}. Newlines
* consist of \n, \r, \r\n, and Unicode hex code points 0x2028, 0x2029, 0x0085;
* see <tt><a href="http://www.docjar.com/html/api/java/util/Scanner.java.html">
* Scanner.java</a></tt> (NB: Java 6u23 and earlier uses only \r, \r, \r\n).
*
* @author David Pritchard
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class In {
///// begin: section (1 of 2) of code duplicated from In to StdIn.
// assume Unicode UTF-8 encoding
private static final String CHARSET_NAME = "UTF-8";
// assume language = English, country = US for consistency with System.out.
private static final Locale LOCALE = Locale.US;
// the default token separator; we maintain the invariant that this value
// is held by the scanner's delimiter between calls
private static final Pattern WHITESPACE_PATTERN
= Pattern.compile("\\p{javaWhitespace}+");
// makes whitespace characters significant
private static final Pattern EMPTY_PATTERN
= Pattern.compile("");
// used to read the entire input. source:
// http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html
private static final Pattern EVERYTHING_PATTERN
= Pattern.compile("\\A");
//// end: section (1 of 2) of code duplicated from In to StdIn.
private Scanner scanner;
/**
* Initializes an input stream from standard input.
*/
public In() {
scanner = new Scanner(new BufferedInputStream(System.in), CHARSET_NAME);
scanner.useLocale(LOCALE);
}
/**
* Initializes an input stream from a socket.
*
* @param socket the socket
* @throws IllegalArgumentException if cannot open {@code socket}
* @throws NullPointerException if {@code socket} is {@code null}
*/
public In(Socket socket) {
if (socket == null) throw new NullPointerException("argument is null");
try {
InputStream is = socket.getInputStream();
scanner = new Scanner(new BufferedInputStream(is), CHARSET_NAME);
scanner.useLocale(LOCALE);
}
catch (IOException ioe) {
throw new IllegalArgumentException("Could not open " + socket);
}
}
/**
* Initializes an input stream from a URL.
*
* @param url the URL
* @throws IllegalArgumentException if cannot open {@code url}
* @throws NullPointerException if {@code url} is {@code null}
*/
public In(URL url) {
if (url == null) throw new NullPointerException("argument is null");
try {
URLConnection site = url.openConnection();
InputStream is = site.getInputStream();
scanner = new Scanner(new BufferedInputStream(is), CHARSET_NAME);
scanner.useLocale(LOCALE);
}
catch (IOException ioe) {
throw new IllegalArgumentException("Could not open " + url);
}
}
/**
* Initializes an input stream from a file.
*
* @param file the file
* @throws IllegalArgumentException if cannot open {@code file}
* @throws NullPointerException if {@code file} is {@code null}
*/
public In(File file) {
if (file == null) throw new NullPointerException("argument is null");
try {
// for consistency with StdIn, wrap with BufferedInputStream instead of use
// file as argument to Scanner
FileInputStream fis = new FileInputStream(file);
scanner = new Scanner(new BufferedInputStream(fis), CHARSET_NAME);
scanner.useLocale(LOCALE);
}
catch (IOException ioe) {
throw new IllegalArgumentException("Could not open " + file);
}
}
/**
* Initializes an input stream from a filename or web page name.
*
* @param name the filename or web page name
* @throws IllegalArgumentException if cannot open {@code name} as
* a file or URL
* @throws NullPointerException if {@code name} is {@code null}
*/
public In(String name) {
if (name == null) throw new NullPointerException("argument is null");
try {
// first try to read file from local file system
File file = new File(name);
if (file.exists()) {
// for consistency with StdIn, wrap with BufferedInputStream instead of use
// file as argument to Scanner
FileInputStream fis = new FileInputStream(file);
scanner = new Scanner(new BufferedInputStream(fis), CHARSET_NAME);
scanner.useLocale(LOCALE);
return;
}
// next try for files included in jar
URL url = getClass().getResource(name);
// or URL from web
if (url == null) {
url = new URL(name);
}
URLConnection site = url.openConnection();
// in order to set User-Agent, replace above line with these two
// HttpURLConnection site = (HttpURLConnection) url.openConnection();
// site.addRequestProperty("User-Agent", "Mozilla/4.76");
InputStream is = site.getInputStream();
scanner = new Scanner(new BufferedInputStream(is), CHARSET_NAME);
scanner.useLocale(LOCALE);
}
catch (IOException ioe) {
throw new IllegalArgumentException("Could not open " + name);
}
}
/**
* Initializes an input stream from a given {@link Scanner} source; use with
* <tt>new Scanner(String)</tt> to read from a string.
* <p>
* Note that this does not create a defensive copy, so the
* scanner will be mutated as you read on.
*
* @param scanner the scanner
* @throws NullPointerException if {@code scanner} is {@code null}
*/
public In(Scanner scanner) {
if (scanner == null) throw new NullPointerException("argument is null");
this.scanner = scanner;
}
/**
* Returns true if this input stream exists.
*
* @return <tt>true</tt> if this input stream exists; <tt>false</tt> otherwise
*/
public boolean exists() {
return scanner != null;
}
//// begin: section (2 of 2) of code duplicated from In to StdIn,
//// with all methods changed from "public" to "public static".
/**
* Returns true if input stream is empty (except possibly whitespace).
* Use this to know whether the next call to {@link #readString()},
* {@link #readDouble()}, etc will succeed.
*
* @return <tt>true</tt> if this input stream is empty (except possibly whitespace);
* <tt>false</tt> otherwise
*/
public boolean isEmpty() {
return !scanner.hasNext();
}
/**
* Returns true if this input stream has a next line.
* Use this method to know whether the
* next call to {@link #readLine()} will succeed.
* This method is functionally equivalent to {@link #hasNextChar()}.
*
* @return <tt>true</tt> if this input stream is empty;
* <tt>false</tt> otherwise
*/
public boolean hasNextLine() {
return scanner.hasNextLine();
}
/**
* Returns true if this input stream has more inputy (including whitespace).
* Use this method to know whether the next call to {@link #readChar()} will succeed.
* This method is functionally equivalent to {@link #hasNextLine()}.
*
* @return <tt>true</tt> if this input stream has more input (including whitespace);
* <tt>false</tt> otherwise
*/
public boolean hasNextChar() {
scanner.useDelimiter(EMPTY_PATTERN);
boolean result = scanner.hasNext();
scanner.useDelimiter(WHITESPACE_PATTERN);
return result;
}
/**
* Reads and returns the next line in this input stream.
*
* @return the next line in this input stream; <tt>null</tt> if no such line
*/
public String readLine() {
String line;
try {
line = scanner.nextLine();
}
catch (NoSuchElementException e) {
line = null;
}
return line;
}
/**
* Reads and returns the next character in this input stream.
*
* @return the next character in this input stream
*/
public char readChar() {
scanner.useDelimiter(EMPTY_PATTERN);
String ch = scanner.next();
assert ch.length() == 1 : "Internal (Std)In.readChar() error!"
+ " Please contact the authors.";
scanner.useDelimiter(WHITESPACE_PATTERN);
return ch.charAt(0);
}
/**
* Reads and returns the remainder of this input stream, as a string.
*
* @return the remainder of this input stream, as a string
*/
public String readAll() {
if (!scanner.hasNextLine())
return "";
String result = scanner.useDelimiter(EVERYTHING_PATTERN).next();
// not that important to reset delimeter, since now scanner is empty
scanner.useDelimiter(WHITESPACE_PATTERN); // but let's do it anyway
return result;
}
/**
* Reads the next token from this input stream and returns it as a <tt>String</tt>.
*
* @return the next <tt>String</tt> in this input stream
*/
public String readString() {
return scanner.next();
}
/**
* Reads the next token from this input stream, parses it as a <tt>int</tt>,
* and returns the <tt>int</tt>.
*
* @return the next <tt>int</tt> in this input stream
*/
public int readInt() {
return scanner.nextInt();
}
/**
* Reads the next token from this input stream, parses it as a <tt>double</tt>,
* and returns the <tt>double</tt>.
*
* @return the next <tt>double</tt> in this input stream
*/
public double readDouble() {
return scanner.nextDouble();
}
/**
* Reads the next token from this input stream, parses it as a <tt>float</tt>,
* and returns the <tt>float</tt>.
*
* @return the next <tt>float</tt> in this input stream
*/
public float readFloat() {
return scanner.nextFloat();
}
/**
* Reads the next token from this input stream, parses it as a <tt>long</tt>,
* and returns the <tt>long</tt>.
*
* @return the next <tt>long</tt> in this input stream
*/
public long readLong() {
return scanner.nextLong();
}
/**
* Reads the next token from this input stream, parses it as a <tt>short</tt>,
* and returns the <tt>short</tt>.
*
* @return the next <tt>short</tt> in this input stream
*/
public short readShort() {
return scanner.nextShort();
}
/**
* Reads the next token from this input stream, parses it as a <tt>byte</tt>,
* and returns the <tt>byte</tt>.
* <p>
* To read binary data, use {@link BinaryIn}.
*
* @return the next <tt>byte</tt> in this input stream
*/
public byte readByte() {
return scanner.nextByte();
}
/**
* Reads the next token from this input stream, parses it as a <tt>boolean</tt>
* (interpreting either <tt>"true"</tt> or <tt>"1"</tt> as <tt>true</tt>,
* and either <tt>"false"</tt> or <tt>"0"</tt> as <tt>false</tt>).
*
* @return the next <tt>boolean</tt> in this input stream
*/
public boolean readBoolean() {
String s = readString();
if (s.equalsIgnoreCase("true")) return true;
if (s.equalsIgnoreCase("false")) return false;
if (s.equals("1")) return true;
if (s.equals("0")) return false;
throw new InputMismatchException();
}
/**
* Reads all remaining tokens from this input stream and returns them as
* an array of strings.
*
* @return all remaining tokens in this input stream, as an array of strings
*/
public String[] readAllStrings() {
// we could use readAll.trim().split(), but that's not consistent
// since trim() uses characters 0x00..0x20 as whitespace
String[] tokens = WHITESPACE_PATTERN.split(readAll());
if (tokens.length == 0 || tokens[0].length() > 0)
return tokens;
String[] decapitokens = new String[tokens.length-1];
for (int i = 0; i < tokens.length-1; i++)
decapitokens[i] = tokens[i+1];
return decapitokens;
}
/**
* Reads all remaining lines from this input stream and returns them as
* an array of strings.
*
* @return all remaining lines in this input stream, as an array of strings
*/
public String[] readAllLines() {
ArrayList<String> lines = new ArrayList<String>();
while (hasNextLine()) {
lines.add(readLine());
}
return lines.toArray(new String[0]);
}
/**
* Reads all remaining tokens from this input stream, parses them as integers,
* and returns them as an array of integers.
*
* @return all remaining lines in this input stream, as an array of integers
*/
public int[] readAllInts() {
String[] fields = readAllStrings();
int[] vals = new int[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Integer.parseInt(fields[i]);
return vals;
}
/**
* Reads all remaining tokens from this input stream, parses them as doubles,
* and returns them as an array of doubles.
*
* @return all remaining lines in this input stream, as an array of doubles
*/
public double[] readAllDoubles() {
String[] fields = readAllStrings();
double[] vals = new double[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Double.parseDouble(fields[i]);
return vals;
}
///// end: section (2 of 2) of code duplicated from In to StdIn */
/**
* Closes this input stream.
*/
public void close() {
scanner.close();
}
/**
* Reads all integers from a file and returns them as
* an array of integers.
*
* @param filename the name of the file
* @return the integers in the file
* @deprecated Replaced by <tt>new In(filename)</tt>.{@link #readAllInts()}.
*/
public static int[] readInts(String filename) {
return new In(filename).readAllInts();
}
/**
* Reads all doubles from a file and returns them as
* an array of doubles.
*
* @param filename the name of the file
* @return the doubles in the file
* @deprecated Replaced by <tt>new In(filename)</tt>.{@link #readAllDoubles()}.
*/
public static double[] readDoubles(String filename) {
return new In(filename).readAllDoubles();
}
/**
* Reads all strings from a file and returns them as
* an array of strings.
*
* @param filename the name of the file
* @return the strings in the file
* @deprecated Replaced by <tt>new In(filename)</tt>.{@link #readAllStrings()}.
*/
public static String[] readStrings(String filename) {
return new In(filename).readAllStrings();
}
/**
* Reads all integers from standard input and returns them
* an array of integers.
*
* @return the integers on standard input
* @deprecated Replaced by {@link StdIn#readAllInts()}.
*/
public static int[] readInts() {
return new In().readAllInts();
}
/**
* Reads all doubles from standard input and returns them as
* an array of doubles.
*
* @return the doubles on standard input
* @deprecated Replaced by {@link StdIn#readAllDoubles()}.
*/
public static double[] readDoubles() {
return new In().readAllDoubles();
}
/**
* Reads all strings from standard input and returns them as
* an array of strings.
*
* @return the strings on standard input
* @deprecated Replaced by {@link StdIn#readAllStrings()}.
*/
public static String[] readStrings() {
return new In().readAllStrings();
}
/**
* Unit tests the <tt>In</tt> data type.
*/
public static void main(String[] args) {
In in;
String urlName = "http://introcs.cs.princeton.edu/stdlib/InTest.txt";
// read from a URL
System.out.println("readAll() from URL " + urlName);
System.out.println("---------------------------------------------------------------------------");
try {
in = new In(urlName);
System.out.println(in.readAll());
}
catch (Exception e) {
System.out.println(e);
}
System.out.println();
// read one line at a time from URL
System.out.println("readLine() from URL " + urlName);
System.out.println("---------------------------------------------------------------------------");
try {
in = new In(urlName);
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
}
catch (Exception e) {
System.out.println(e);
}
System.out.println();
// read one string at a time from URL
System.out.println("readString() from URL " + urlName);
System.out.println("---------------------------------------------------------------------------");
try {
in = new In(urlName);
while (!in.isEmpty()) {
String s = in.readString();
System.out.println(s);
}
}
catch (Exception e) {
System.out.println(e);
}
System.out.println();
// read one line at a time from file in current directory
System.out.println("readLine() from current directory");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("./InTest.txt");
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
}
catch (Exception e) {
System.out.println(e);
}
System.out.println();
// read one line at a time from file using relative path
System.out.println("readLine() from relative path");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("../stdlib/InTest.txt");
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
}
catch (Exception e) {
System.out.println(e);
}
System.out.println();
// read one char at a time
System.out.println("readChar() from file");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("InTest.txt");
while (!in.isEmpty()) {
char c = in.readChar();
System.out.print(c);
}
}
catch (Exception e) {
System.out.println(e);
}
System.out.println();
System.out.println();
// read one line at a time from absolute OS X / Linux path
System.out.println("readLine() from absolute OS X / Linux path");
System.out.println("---------------------------------------------------------------------------");
in = new In("/n/fs/introcs/www/java/stdlib/InTest.txt");
try {
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
}
catch (Exception e) {
System.out.println(e);
}
System.out.println();
// read one line at a time from absolute Windows path
System.out.println("readLine() from absolute Windows path");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("G:\\www\\introcs\\stdlib\\InTest.txt");
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
System.out.println();
}
catch (Exception e) {
System.out.println(e);
}
System.out.println();
}
}
| bsdfzzzy/Algorithms | In.java |
1,057 | // Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: packimports(3) nonlb space
public class k {
public k() {
}
public static int rp = 72;
public static int sp = 72;
public static int tp = 31;
public static int up = 22;
public static int vp = 20;
public static int wp = 7;
public static int xp = 6;
public static int yp = 6;
}
| cath-mawr/mapviewer72 | k.java |
1,058 | // Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: packimports(3) nonlb space
import jagex.client.i;
import java.awt.Component;
public class g extends i {
public g(int j, int k, int l, Component component) {
super(j, k, l, component);
boolean flag = false;
if (flag)
new i(j, k, l, component);
}
public void nf(int j, int k, int l, int i1, int j1, int k1, int l1) {
if (j1 >= 40000) {
pg.op(j, k, l, i1, j1 - 40000, k1, l1);
return;
}
if (j1 >= 20000) {
pg.gp(j, k, l, i1, j1 - 20000, k1, l1);
return;
}
if (j1 >= 5000) {
pg.ko(j, k, l, i1, j1 - 5000, k1, l1);
return;
} else {
super.ug(j, k, l, i1, j1);
return;
}
}
public mudclient pg;
}
| cath-mawr/mapviewer72 | g.java |
1,059 | // Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: packimports(3) nonlb space
public class r {
public r() {
uy = new int[10];
vy = new int[10];
wy = new int[12];
gz = -1;
pz = false;
qz = -1;
}
public long iy;
public String jy;
public int ky;
public int ly;
public int my;
public int ny;
public int oy;
public int py;
public int qy;
public int ry;
public int sy;
public int ty;
public int uy[];
public int vy[];
public int wy[];
public String xy;
public int yy;
public int zy;
public int az;
public int bz;
public int cz;
public int dz;
public int ez;
public int fz;
public int gz;
public int hz;
public int iz;
public int jz;
public int kz;
public int lz;
public int mz;
public int nz;
public int oz;
public boolean pz;
public int qz;
public int rz;
}
| cath-mawr/mapviewer72 | r.java |
1,060 | package Fundamentals;
/*************************************************************************
* Compilation: javac In.java
* Execution: java In
*
* Reads in data of various types from: stdin, file, URL.
*
* % java In
*
* Remarks
* -------
* - isEmpty() returns true if there is no more input or
* it is all whitespace. This might lead to surprising behavior
* when used with readChar()
*
*************************************************************************/
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Locale;
import java.util.Scanner;
/**
* <i>Input</i>. This class provides methods for reading strings
* and numbers from standard input, file input, URL, and socket.
* <p>
* The Locale used is: language = English, country = US. This is consistent
* with the formatting conventions with Java floating-point literals,
* command-line arguments (via <tt>Double.parseDouble()</tt>)
* and standard output (via <tt>System.out.print()</tt>). It ensures that
* standard input works the number formatting used in the textbook.
* <p>
* For additional documentation, see <a href="http://introcs.cs.princeton.edu/31datatype">Section 3.1</a> of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i> by Robert Sedgewick and Kevin Wayne.
*/
public final class In {
private Scanner scanner;
// assume Unicode UTF-8 encoding
//private String charsetName = "UTF-8";
private String charsetName = "ISO-8859-1";
// assume language = English, country = US for consistency with System.out.
private Locale usLocale = new Locale("en", "US");
/**
* Create an input stream for standard input.
*/
public In() {
scanner = new Scanner(new BufferedInputStream(System.in), charsetName);
scanner.useLocale(usLocale);
}
/**
* Create an input stream from a socket.
*/
public In(Socket socket) {
try {
InputStream is = socket.getInputStream();
scanner = new Scanner(new BufferedInputStream(is), charsetName);
scanner.useLocale(usLocale);
}
catch (IOException ioe) {
System.err.println("Could not open " + socket);
}
}
/**
* Create an input stream from a URL.
*/
public In(URL url) {
try {
URLConnection site = url.openConnection();
InputStream is = site.getInputStream();
scanner = new Scanner(new BufferedInputStream(is), charsetName);
scanner.useLocale(usLocale);
}
catch (IOException ioe) {
System.err.println("Could not open " + url);
}
}
/**
* Create an input stream from a file.
*/
public In(File file) {
try {
scanner = new Scanner(file, charsetName);
scanner.useLocale(usLocale);
}
catch (IOException ioe) {
System.err.println("Could not open " + file);
}
}
/*
* Added 11/1/2012
*/
public In(String dirname, String filename) {
Path inputPath= Paths.get(dirname, filename);
String inputPathString = dirname + File.separator + filename;
if (! Files.isReadable(inputPath)) {
System.out.printf("File %s does not exist.", inputPathString);
return;
}
File file = inputPath.toFile();
try {
scanner = new Scanner(file, charsetName);
scanner.useLocale(usLocale);
}
catch (IOException ioe) {
System.err.println("Could not open " + file);
}
}
/**
* Create an input stream from a filename or web page name.
*/
public In(String s) {
try {
// first try to read file from local file system
File file = new File(s);
if (file.exists()) {
scanner = new Scanner(file, charsetName);
scanner.useLocale(usLocale);
return;
}
// next try for files included in jar
URL url = getClass().getResource(s);
// or URL from web
if (url == null) { url = new URL(s); }
URLConnection site = url.openConnection();
InputStream is = site.getInputStream();
scanner = new Scanner(new BufferedInputStream(is), charsetName);
scanner.useLocale(usLocale);
}
catch (IOException ioe) {
System.err.println("Could not open " + s);
}
}
/**
* Does the input stream exist?
*/
public boolean exists() {
return scanner != null;
}
/**
* Is the input stream empty?
*/
public boolean isEmpty() {
return !scanner.hasNext();
}
/**
* Does the input stream have a next line?
*/
public boolean hasNextLine() {
return scanner.hasNextLine();
}
/**
* Read and return the next line.
*/
public String readLine() {
String line;
try { line = scanner.nextLine(); }
catch (Exception e) { line = null; }
return line;
}
/**
* Read and return the next character.
*/
public char readChar() {
// (?s) for DOTALL mode so . matches any character, including a line termination character
// 1 says look only one character ahead
// consider precompiling the pattern
String s = scanner.findWithinHorizon("(?s).", 1);
return s.charAt(0);
}
// return rest of input as string
/**
* Read and return the remainder of the input as a string.
*/
public String readAll() {
if (!scanner.hasNextLine()) { return null; }
// reference: http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html
return scanner.useDelimiter("\\A").next();
}
/**
* Return the next string from the input stream.
*/
public String readString() {
return scanner.next();
}
/**
* Return the next int from the input stream.
*/
public int readInt() {
return scanner.nextInt();
}
/**
* Return the next double from the input stream.
*/
public double readDouble() {
return scanner.nextDouble();
}
/**
* Return the next float from the input stream.
*/
public double readFloat() {
return scanner.nextFloat();
}
/**
* Return the next long from the input stream.
*/
public long readLong() {
return scanner.nextLong();
}
/**
* Return the next byte from the input stream.
*/
public byte readByte() {
return scanner.nextByte();
}
/**
* Return the next boolean from the input stream, allowing "true" or "1"
* for true and "false" or "0" for false.
*/
public boolean readBoolean() {
String s = readString();
if (s.equalsIgnoreCase("true")) return true;
if (s.equalsIgnoreCase("false")) return false;
if (s.equals("1")) return true;
if (s.equals("0")) return false;
throw new java.util.InputMismatchException();
}
/**
* Read ints from file
*/
public static int[] readInts(String filename) {
In in = new In(filename);
String[] fields = in.readAll().trim().split("\\s+");
int[] vals = new int[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Integer.parseInt(fields[i]);
return vals;
}
/**
* Read doubles from file
*/
public static double[] readDoubles(String filename) {
In in = new In(filename);
String[] fields = in.readAll().trim().split("\\s+");
double[] vals = new double[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Double.parseDouble(fields[i]);
return vals;
}
/**
* Read strings from a file
*/
public static String[] readStrings(String filename) {
In in = new In(filename);
String[] fields = in.readAll().trim().split("\\s+");
return fields;
}
/**
* Read ints from standard input
*/
public static int[] readInts() {
In in = new In();
String[] fields = in.readAll().trim().split("\\s+");
int[] vals = new int[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Integer.parseInt(fields[i]);
return vals;
}
/**
* Read doubles from standard input
*/
public static double[] readDoubles() {
In in = new In();
String[] fields = in.readAll().trim().split("\\s+");
double[] vals = new double[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Double.parseDouble(fields[i]);
return vals;
}
/**
* Read strings from standard input
*/
public static String[] readStrings() {
In in = new In();
String[] fields = in.readAll().trim().split("\\s+");
return fields;
}
/**
* Close the input stream.
*/
public void close() { scanner.close(); }
/**
* Test client.
*/
public static void main(String[] args) {
In in;
String urlName = "http://introcs.cs.princeton.edu/stdlib/InTest.txt";
// read from a URL
System.out.println("readAll() from URL " + urlName);
System.out.println("---------------------------------------------------------------------------");
try {
in = new In(urlName);
System.out.println(in.readAll());
}
catch (Exception e) { System.out.println(e); }
System.out.println();
// read one line at a time from URL
System.out.println("readLine() from URL " + urlName);
System.out.println("---------------------------------------------------------------------------");
try {
in = new In(urlName);
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
}
catch (Exception e) { System.out.println(e); }
System.out.println();
// read one string at a time from URL
System.out.println("readString() from URL " + urlName);
System.out.println("---------------------------------------------------------------------------");
try {
in = new In(urlName);
while (!in.isEmpty()) {
String s = in.readString();
System.out.println(s);
}
}
catch (Exception e) { System.out.println(e); }
System.out.println();
// read one line at a time from file in current directory
System.out.println("readLine() from current directory");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("./InTest.txt");
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
}
catch (Exception e) { System.out.println(e); }
System.out.println();
// read one line at a time from file using relative path
System.out.println("readLine() from relative path");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("../stdlib/InTest.txt");
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
}
catch (Exception e) { System.out.println(e); }
System.out.println();
// read one char at a time
System.out.println("readChar() from file");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("InTest.txt");
while (!in.isEmpty()) {
char c = in.readChar();
System.out.print(c);
}
}
catch (Exception e) { System.out.println(e); }
System.out.println();
System.out.println();
// read one line at a time from absolute OS X / Linux path
System.out.println("readLine() from absolute OS X / Linux path");
System.out.println("---------------------------------------------------------------------------");
in = new In("/n/fs/csweb/introcs/stdlib/InTest.txt");
try {
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
}
catch (Exception e) { System.out.println(e); }
System.out.println();
// read one line at a time from absolute Windows path
System.out.println("readLine() from absolute Windows path");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("G:\\www\\introcs\\stdlib\\InTest.txt");
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
System.out.println();
}
catch (Exception e) { System.out.println(e); }
System.out.println();
}
}
| stefanzero/JavaFundamentals | In.java |
1,061 | /******************************************************************************
* Compilation: javac In.java
* Execution: java In (basic test --- see source for required files)
* Dependencies: none
*
* Reads in data of various types from standard input, files, and URLs.
*
******************************************************************************/
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
// import java.net.HttpURLConnection;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Locale;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.regex.Pattern;
/**
* <i>Input</i>. This class provides methods for reading strings
* and numbers from standard input, file input, URLs, and sockets.
* <p>
* The Locale used is: language = English, country = US. This is consistent
* with the formatting conventions with Java floating-point literals,
* command-line arguments (via {@link Double#parseDouble(String)})
* and standard output.
* <p>
* For additional documentation, see
* <a href="http://introcs.cs.princeton.edu/31datatype">Section 3.1</a> of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i>
* by Robert Sedgewick and Kevin Wayne.
* <p>
* Like {@link Scanner}, reading a token also consumes preceding Java
* whitespace, reading a full line consumes
* the following end-of-line delimeter, while reading a character consumes
* nothing extra.
* <p>
* Whitespace is defined in {@link Character#isWhitespace(char)}. Newlines
* consist of \n, \r, \r\n, and Unicode hex code points 0x2028, 0x2029, 0x0085;
* see <tt><a href="http://www.docjar.com/html/api/java/util/Scanner.java.html">
* Scanner.java</a></tt> (NB: Java 6u23 and earlier uses only \r, \r, \r\n).
*
* @author David Pritchard
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class In {
/*** begin: section (1 of 2) of code duplicated from In to StdIn. */
// assume Unicode UTF-8 encoding
private static final String CHARSET_NAME = "UTF-8";
// assume language = English, country = US for consistency with System.out.
private static final Locale LOCALE = Locale.US;
// the default token separator; we maintain the invariant that this value
// is held by the scanner's delimiter between calls
private static final Pattern WHITESPACE_PATTERN
= Pattern.compile("\\p{javaWhitespace}+");
// makes whitespace characters significant
private static final Pattern EMPTY_PATTERN
= Pattern.compile("");
// used to read the entire input. source:
// http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html
private static final Pattern EVERYTHING_PATTERN
= Pattern.compile("\\A");
/*** end: section (1 of 2) of code duplicated from In to StdIn. */
private Scanner scanner;
/**
* Initializes an input stream from standard input.
*/
public In() {
scanner = new Scanner(new BufferedInputStream(System.in), CHARSET_NAME);
scanner.useLocale(LOCALE);
}
/**
* Initializes an input stream from a socket.
*
* @param socket the socket
*/
public In(java.net.Socket socket) {
try {
InputStream is = socket.getInputStream();
scanner = new Scanner(new BufferedInputStream(is), CHARSET_NAME);
scanner.useLocale(LOCALE);
}
catch (IOException ioe) {
System.err.println("Could not open " + socket);
}
}
/**
* Initializes an input stream from a URL.
*
* @param url the URL
*/
public In(URL url) {
try {
URLConnection site = url.openConnection();
InputStream is = site.getInputStream();
scanner = new Scanner(new BufferedInputStream(is), CHARSET_NAME);
scanner.useLocale(LOCALE);
}
catch (IOException ioe) {
System.err.println("Could not open " + url);
}
}
/**
* Initializes an input stream from a file.
*
* @param file the file
*/
public In(File file) {
try {
scanner = new Scanner(file, CHARSET_NAME);
scanner.useLocale(LOCALE);
}
catch (IOException ioe) {
System.err.println("Could not open " + file);
}
}
/**
* Initializes an input stream from a filename or web page name.
*
* @param s the filename or web page name
*/
public In(String s) {
try {
// first try to read file from local file system
File file = new File(s);
if (file.exists()) {
scanner = new Scanner(file, CHARSET_NAME);
scanner.useLocale(LOCALE);
return;
}
// next try for files included in jar
URL url = getClass().getResource(s);
// or URL from web
if (url == null) {
url = new URL(s);
}
URLConnection site = url.openConnection();
// in order to set User-Agent, replace above line with these two
// HttpURLConnection site = (HttpURLConnection) url.openConnection();
// site.addRequestProperty("User-Agent", "Mozilla/4.76");
InputStream is = site.getInputStream();
scanner = new Scanner(new BufferedInputStream(is), CHARSET_NAME);
scanner.useLocale(LOCALE);
}
catch (IOException ioe) {
System.err.println("Could not open " + s);
}
}
/**
* Initializes an input stream from a given {@link Scanner} source; use with
* <tt>new Scanner(String)</tt> to read from a string.
* <p>
* Note that this does not create a defensive copy, so the
* scanner will be mutated as you read on.
*
* @param scanner the scanner
*/
public In(Scanner scanner) {
this.scanner = scanner;
}
/**
* Does the input stream exist?
*
* @return <tt>true</tt> if the input stream exists; <tt>false</tt> otherwise
*/
public boolean exists() {
return scanner != null;
}
/*** begin: section (2 of 2) of code duplicated from In to StdIn,
* with all methods changed from "public" to "public static". ***/
/**
* Is this input stream empty (except possibly whitespace)?
* Use this to know whether the next call to {@link #readString()},
* {@link #readDouble()}, etc will succeed.
*
* @return <tt>true</tt> if this input stream is empty (except possibly whitespace);
* <tt>false</tt> otherwise
*/
public boolean isEmpty() {
return !scanner.hasNext();
}
/**
* Does this input stream have a next line?
* Use this to know whether the next call to {@link #readLine()} will succeed.
* <p>
* Functionally equivalent to {@link #hasNextChar()}.
*
* @return <tt>true</tt> if this input stream has a next line;
* <tt>false</tt> otherwise
*/
public boolean hasNextLine() {
return scanner.hasNextLine();
}
/**
* Is this input empty (including whitespace)?
* Use this to know whether the next call to {@link #readChar()} will succeed.
* <p>
* Functionally equivalent to {@link #hasNextLine()}.
*
* @return <tt>true</tt> if this input stream is empty (including whitespace);
* <tt>false</tt> otherwise
*/
public boolean hasNextChar() {
scanner.useDelimiter(EMPTY_PATTERN);
boolean result = scanner.hasNext();
scanner.useDelimiter(WHITESPACE_PATTERN);
return result;
}
/**
* Reads and returns the next line in this input stream.
*
* @return the next line in this input stream; <tt>null</tt> if no such line
*/
public String readLine() {
String line;
try {
line = scanner.nextLine();
}
catch (NoSuchElementException e) {
line = null;
}
return line;
}
/**
* Reads and returns the next character in this input stream.
*
* @return the next character in this input stream
*/
public char readChar() {
scanner.useDelimiter(EMPTY_PATTERN);
String ch = scanner.next();
assert ch.length() == 1 : "Internal (Std)In.readChar() error!"
+ " Please contact the authors.";
scanner.useDelimiter(WHITESPACE_PATTERN);
return ch.charAt(0);
}
/**
* Reads and returns the remainder of the input stream, as a string.
*
* @return the remainder of this input stream, as a string
*/
public String readAll() {
if (!scanner.hasNextLine())
return "";
String result = scanner.useDelimiter(EVERYTHING_PATTERN).next();
// not that important to reset delimeter, since now scanner is empty
scanner.useDelimiter(WHITESPACE_PATTERN); // but let's do it anyway
return result;
}
/**
* Reads the next token from this input stream and returns it as a <tt>String</tt>
*
* @return the next <tt>String</tt> in this input stream
*/
public String readString() {
return scanner.next();
}
/**
* Reads the next token from this input stream, parses it as a <tt>int</tt>,
* and returns the <tt>int</tt>.
*
* @return the next <tt>int</tt> in this input stream
*/
public int readInt() {
return scanner.nextInt();
}
/**
* Reads the next token from this input stream, parses it as a <tt>double</tt>,
* and returns the <tt>double</tt>.
*
* @return the next <tt>double</tt> in this input stream
*/
public double readDouble() {
return scanner.nextDouble();
}
/**
* Reads the next token from this input stream, parses it as a <tt>float</tt>,
* and returns the <tt>float</tt>.
*
* @return the next <tt>float</tt> in this input stream
*/
public float readFloat() {
return scanner.nextFloat();
}
/**
* Reads the next token from this input stream, parses it as a <tt>long</tt>,
* and returns the <tt>long</tt>.
*
* @return the next <tt>long</tt> in this input stream
*/
public long readLong() {
return scanner.nextLong();
}
/**
* Reads the next token from this input stream, parses it as a <tt>short</tt>,
* and returns the <tt>short</tt>.
*
* @return the next <tt>short</tt> in this input stream
*/
public short readShort() {
return scanner.nextShort();
}
/**
* Reads the next token from this input stream, parses it as a <tt>byte</tt>,
* and returns the <tt>byte</tt>.
* <p>
* To read binary data, use {@link BinaryIn}.
*
* @return the next <tt>byte</tt> in this input stream
*/
public byte readByte() {
return scanner.nextByte();
}
/**
* Reads the next token from this input stream, parses it as a <tt>boolean</tt>
* (interpreting either <tt>"true"</tt> or <tt>"1"</tt> as <tt>true</tt>,
* and either <tt>"false"</tt> or <tt>"0"</tt> as <tt>false</tt>).
*
* @return the next <tt>boolean</tt> in this input stream
*/
public boolean readBoolean() {
String s = readString();
if (s.equalsIgnoreCase("true")) return true;
if (s.equalsIgnoreCase("false")) return false;
if (s.equals("1")) return true;
if (s.equals("0")) return false;
throw new InputMismatchException();
}
/**
* Reads all remaining tokens from this input stream and returns them as
* an array of strings.
*
* @return all remaining tokens in this input stream, as an array of strings
*/
public String[] readAllStrings() {
// we could use readAll.trim().split(), but that's not consistent
// since trim() uses characters 0x00..0x20 as whitespace
String[] tokens = WHITESPACE_PATTERN.split(readAll());
if (tokens.length == 0 || tokens[0].length() > 0)
return tokens;
String[] decapitokens = new String[tokens.length-1];
for (int i = 0; i < tokens.length-1; i++)
decapitokens[i] = tokens[i+1];
return decapitokens;
}
/**
* Reads all remaining lines from this input stream and returns them as
* an array of strings.
*
* @return all remaining lines in this input stream, as an array of strings
*/
public String[] readAllLines() {
ArrayList<String> lines = new ArrayList<String>();
while (hasNextLine()) {
lines.add(readLine());
}
return lines.toArray(new String[0]);
}
/**
* Reads all remaining tokens from this input stream, parses them as integers,
* and returns them as an array of integers.
*
* @return all remaining lines in this input stream, as an array of integers
*/
public int[] readAllInts() {
String[] fields = readAllStrings();
int[] vals = new int[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Integer.parseInt(fields[i]);
return vals;
}
/**
* Reads all remaining tokens from this input stream, parses them as doubles,
* and returns them as an array of doubles.
*
* @return all remaining lines in this input stream, as an array of doubles
*/
public double[] readAllDoubles() {
String[] fields = readAllStrings();
double[] vals = new double[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Double.parseDouble(fields[i]);
return vals;
}
/*** end: section (2 of 2) of code duplicated from In to StdIn */
/**
* Closes this input stream.
*/
public void close() {
scanner.close();
}
/**
* Reads all integers from a file and returns them as
* an array of integers.
*
* @param filename the name of the file
* @return the integers in the file
* @deprecated Clearer to use <tt>new In(filename)</tt>.{@link #readAllInts()}
*/
public static int[] readInts(String filename) {
return new In(filename).readAllInts();
}
/**
* Reads all doubles from a file and returns them as
* an array of doubles.
*
* @param filename the name of the file
* @return the doubles in the file
* @deprecated Clearer to use <tt>new In(filename)</tt>.{@link #readAllDoubles()}
*/
public static double[] readDoubles(String filename) {
return new In(filename).readAllDoubles();
}
/**
* Reads all strings from a file and returns them as
* an array of strings.
*
* @param filename the name of the file
* @return the strings in the file
* @deprecated Clearer to use <tt>new In(filename)</tt>.{@link #readAllStrings()}
*/
public static String[] readStrings(String filename) {
return new In(filename).readAllStrings();
}
/**
* Reads all integers from standard input and returns them
* an array of integers.
*
* @return the integers on standard input
* @deprecated Clearer to use {@link StdIn#readAllInts()}
*/
public static int[] readInts() {
return new In().readAllInts();
}
/**
* Reads all doubles from standard input and returns them as
* an array of doubles.
*
* @return the doubles on standard input
* @deprecated clearer to use {@link StdIn#readAllDoubles()}
*/
public static double[] readDoubles() {
return new In().readAllDoubles();
}
/**
* Reads all strings from standard input and returns them as
* an array of strings.
*
* @return the strings on standard input
* @deprecated clearer to use {@link StdIn#readAllStrings()}
*/
public static String[] readStrings() {
return new In().readAllStrings();
}
/**
* Test client.
*/
public static void main(String[] args) {
In in;
String urlName = "http://introcs.cs.princeton.edu/stdlib/InTest.txt";
// read from a URL
System.out.println("readAll() from URL " + urlName);
System.out.println("---------------------------------------------------------------------------");
try {
in = new In(urlName);
System.out.println(in.readAll());
}
catch (Exception e) {
System.out.println(e);
}
System.out.println();
// read one line at a time from URL
System.out.println("readLine() from URL " + urlName);
System.out.println("---------------------------------------------------------------------------");
try {
in = new In(urlName);
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
}
catch (Exception e) {
System.out.println(e);
}
System.out.println();
// read one string at a time from URL
System.out.println("readString() from URL " + urlName);
System.out.println("---------------------------------------------------------------------------");
try {
in = new In(urlName);
while (!in.isEmpty()) {
String s = in.readString();
System.out.println(s);
}
}
catch (Exception e) {
System.out.println(e);
}
System.out.println();
// read one line at a time from file in current directory
System.out.println("readLine() from current directory");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("./InTest.txt");
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
}
catch (Exception e) {
System.out.println(e);
}
System.out.println();
// read one line at a time from file using relative path
System.out.println("readLine() from relative path");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("../stdlib/InTest.txt");
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
}
catch (Exception e) {
System.out.println(e);
}
System.out.println();
// read one char at a time
System.out.println("readChar() from file");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("InTest.txt");
while (!in.isEmpty()) {
char c = in.readChar();
System.out.print(c);
}
}
catch (Exception e) {
System.out.println(e);
}
System.out.println();
System.out.println();
// read one line at a time from absolute OS X / Linux path
System.out.println("readLine() from absolute OS X / Linux path");
System.out.println("---------------------------------------------------------------------------");
in = new In("/n/fs/introcs/www/java/stdlib/InTest.txt");
try {
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
}
catch (Exception e) {
System.out.println(e);
}
System.out.println();
// read one line at a time from absolute Windows path
System.out.println("readLine() from absolute Windows path");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("G:\\www\\introcs\\stdlib\\InTest.txt");
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
System.out.println();
}
catch (Exception e) {
System.out.println(e);
}
System.out.println();
}
}
| yalechang/java_projects | In.java |
1,062 | //Changes by danbiocchi (https://github.com/danbiocchi/JavaPI/pull/1)
import java.math.BigDecimal;
public class PI {
public static void main(String[] args) {
// Prints Math.PI and the extended Math.PI to the terminal window.
System.out.println("Standard Math.PI: "+ Math.PI);
System.out.println("Extended Math.PI: "+ new BigDecimal(Math.PI)); //Creates a new big decimal with the value of Math.PI
System.out.println("Used java.math.BigDecimal to extend Math.PI to the system's legnth");
}
}
| MajickTek/JavaPI | PI.java |
1,064 | import java.io.*;
import java_cup.runtime.*;
/**
* Main program to test the moo parser.
*
* There should be 2 command-line arguments:
* 1. the file to be parsed
* 2. the output file into which the AST built by the parser should be
* unparsed
* The program opens the two files, creates a scanner and a parser, and
* calls the parser. If the parse is successful, the AST is unparsed.
*/
public class P4 {
public static void main(String[] args)
throws IOException // may be thrown by the scanner
{
// check for command-line args
if (args.length != 2) {
System.err.println("please supply name of file to be parsed " +
"and name of file for unparsed version.");
System.exit(-1);
}
// open input file
FileReader inFile = null;
try {
inFile = new FileReader(args[0]);
} catch (FileNotFoundException ex) {
System.err.println("File " + args[0] + " not found.");
System.exit(-1);
}
// open output file
PrintWriter outFile = null;
try {
outFile = new PrintWriter(args[1]);
} catch (FileNotFoundException ex) {
System.err.println("File " + args[1] +
" could not be opened for writing.");
System.exit(-1);
}
parser P = new parser(new Yylex(inFile));
Symbol root = null; // the parser will return a Symbol whose value
// field is the translation of the root nonterminal
// (i.e., of the nonterminal "program")
try {
root = P.parse(); // do the parse
System.out.println ("program parsed correctly.");
} catch (Exception ex){
System.err.println("Exception occured during parse: " + ex);
System.exit(-1);
}
((ProgramNode)root.value).nameAnalysis();
if (ErrMsg.fatalErrors == true)
System.exit(1); //name analysis errors were present
((ASTnode)root.value).unparse(outFile, 0);
outFile.close();
return;
}
}
| jkoritzinsky/Moo-Name-Analysis | P4.java |
1,067 | /*************************************************************************
* Compilation: javac In.java
* Execution: java In (basic test --- see source for required files)
* <p>
* Reads in data of various types from standard input, files, and URLs.
*************************************************************************/
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
import java.util.regex.Pattern;
/**
* <i>Input</i>. This class provides methods for reading strings
* and numbers from standard input, file input, URLs, and sockets.
* <p>
* The Locale used is: language = English, country = US. This is consistent
* with the formatting conventions with Java floating-point literals,
* command-line arguments (via {@link Double#parseDouble(String)})
* and standard output.
* <p>
* For additional documentation, see
* <a href="http://introcs.cs.princeton.edu/31datatype">Section 3.1</a> of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i>
* by Robert Sedgewick and Kevin Wayne.
* <p>
* Like {@link Scanner}, reading a token also consumes preceding Java
* whitespace, reading a full line consumes
* the following end-of-line delimeter, while reading a character consumes
* nothing extra.
* <p>
* Whitespace is defined in {@link Character#isWhitespace(char)}. Newlines
* consist of \n, \r, \r\n, and Unicode hex code points 0x2028, 0x2029, 0x0085;
* see <tt><a href="http://www.docjar.com/html/api/java/util/Scanner.java.html">
* Scanner.java</a></tt> (NB: Java 6u23 and earlier uses only \r, \r, \r\n).
*
* @author David Pritchard
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class In {
private Scanner scanner;
/*** begin: section (1 of 2) of code duplicated from In to StdIn */
// assume Unicode UTF-8 encoding
private static final String charsetName = "UTF-8";
// assume language = English, country = US for consistency with System.out.
private static final java.util.Locale usLocale =
new java.util.Locale("en", "US");
// the default token separator; we maintain the invariant that this value
// is held by the scanner's delimiter between calls
private static final Pattern WHITESPACE_PATTERN
= Pattern.compile("\\p{javaWhitespace}+");
// makes whitespace characters significant
private static final Pattern EMPTY_PATTERN
= Pattern.compile("");
// used to read the entire input. source:
// http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html
private static final Pattern EVERYTHING_PATTERN
= Pattern.compile("\\A");
/*** end: section (1 of 2) of code duplicated from In to StdIn */
/**
* Create an input stream from standard input.
*/
public In() {
scanner = new Scanner(new BufferedInputStream(System.in), charsetName);
scanner.useLocale(usLocale);
}
/**
* Create an input stream from a socket.
*/
public In(java.net.Socket socket) {
try {
InputStream is = socket.getInputStream();
scanner = new Scanner(new BufferedInputStream(is), charsetName);
scanner.useLocale(usLocale);
} catch (IOException ioe) {
System.err.println("Could not open " + socket);
}
}
/**
* Create an input stream from a URL.
*/
public In(URL url) {
try {
URLConnection site = url.openConnection();
InputStream is = site.getInputStream();
scanner = new Scanner(new BufferedInputStream(is), charsetName);
scanner.useLocale(usLocale);
} catch (IOException ioe) {
System.err.println("Could not open " + url);
}
}
/**
* Create an input stream from a file.
*/
public In(File file) {
try {
scanner = new Scanner(file, charsetName);
scanner.useLocale(usLocale);
} catch (IOException ioe) {
System.err.println("Could not open " + file);
}
}
/**
* Create an input stream from a filename or web page name.
*/
public In(String s) {
try {
// first try to read file from local file system
File file = new File(s);
if (file.exists()) {
scanner = new Scanner(file, charsetName);
scanner.useLocale(usLocale);
return;
}
// next try for files included in jar
URL url = getClass().getResource(s);
// or URL from web
if (url == null) {
url = new URL(s);
}
URLConnection site = url.openConnection();
// in order to set User-Agent, replace above line with these two
// HttpURLConnection site = (HttpURLConnection) url.openConnection();
// site.addRequestProperty("User-Agent", "Mozilla/4.76");
InputStream is = site.getInputStream();
scanner = new Scanner(new BufferedInputStream(is), charsetName);
scanner.useLocale(usLocale);
} catch (IOException ioe) {
System.err.println("Could not open " + s);
}
}
/**
* Create an input stream from a given Scanner source; use with
* <tt>new Scanner(String)</tt> to read from a string.
* <p>
* Note that this does not create a defensive copy, so the
* scanner will be mutated as you read on.
*/
public In(Scanner scanner) {
this.scanner = scanner;
}
/**
* Does the input stream exist?
*/
public boolean exists() {
return scanner != null;
}
/*** begin: section (2 of 2) of code duplicated from In to StdIn,
* with all methods changed from "public" to "public static" ***/
/**
* Is the input empty (except possibly for whitespace)? Use this
* to know whether the next call to {@link #readString()},
* {@link #readDouble()}, etc will succeed.
*/
public boolean isEmpty() {
return !scanner.hasNext();
}
/**
* Does the input have a next line? Use this to know whether the
* next call to {@link #readLine()} will succeed. <p> Functionally
* equivalent to {@link #hasNextChar()}.
*/
public boolean hasNextLine() {
return scanner.hasNextLine();
}
/**
* Is the input empty (including whitespace)? Use this to know
* whether the next call to {@link #readChar()} will succeed. <p> Functionally
* equivalent to {@link #hasNextLine()}.
*/
public boolean hasNextChar() {
scanner.useDelimiter(EMPTY_PATTERN);
boolean result = scanner.hasNext();
scanner.useDelimiter(WHITESPACE_PATTERN);
return result;
}
/**
* Read and return the next line.
*/
public String readLine() {
String line;
try {
line = scanner.nextLine();
} catch (Exception e) {
line = null;
}
return line;
}
/**
* Read and return the next character.
*/
public char readChar() {
scanner.useDelimiter(EMPTY_PATTERN);
String ch = scanner.next();
assert (ch.length() == 1) : "Internal (Std)In.readChar() error!"
+ " Please contact the authors.";
scanner.useDelimiter(WHITESPACE_PATTERN);
return ch.charAt(0);
}
/**
* Read and return the remainder of the input as a string.
*/
public String readAll() {
if (!scanner.hasNextLine())
return "";
String result = scanner.useDelimiter(EVERYTHING_PATTERN).next();
// not that important to reset delimeter, since now scanner is empty
scanner.useDelimiter(WHITESPACE_PATTERN); // but let's do it anyway
return result;
}
/**
* Read and return the next string.
*/
public String readString() {
return scanner.next();
}
/**
* Read and return the next int.
*/
public int readInt() {
return scanner.nextInt();
}
/**
* Read and return the next double.
*/
public double readDouble() {
return scanner.nextDouble();
}
/**
* Read and return the next float.
*/
public float readFloat() {
return scanner.nextFloat();
}
/**
* Read and return the next long.
*/
public long readLong() {
return scanner.nextLong();
}
/**
* Read and return the next short.
*/
public short readShort() {
return scanner.nextShort();
}
/**
* Read and return the next byte.
*/
public byte readByte() {
return scanner.nextByte();
}
/**
* Read and return the next boolean, allowing case-insensitive
* "true" or "1" for true, and "false" or "0" for false.
*/
public boolean readBoolean() {
String s = readString();
if (s.equalsIgnoreCase("true")) return true;
if (s.equalsIgnoreCase("false")) return false;
if (s.equals("1")) return true;
if (s.equals("0")) return false;
throw new java.util.InputMismatchException();
}
/**
* Read all strings until the end of input is reached, and return them.
*/
public String[] readAllStrings() {
// we could use readAll.trim().split(), but that's not consistent
// since trim() uses characters 0x00..0x20 as whitespace
String[] tokens = WHITESPACE_PATTERN.split(readAll());
if (tokens.length == 0 || tokens[0].length() > 0)
return tokens;
String[] decapitokens = new String[tokens.length - 1];
for (int i = 0; i < tokens.length - 1; i++)
decapitokens[i] = tokens[i + 1];
return decapitokens;
}
/**
* Read all ints until the end of input is reached, and return them.
*/
public int[] readAllInts() {
String[] fields = readAllStrings();
int[] vals = new int[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Integer.parseInt(fields[i]);
return vals;
}
/**
* Read all doubles until the end of input is reached, and return them.
*/
public double[] readAllDoubles() {
String[] fields = readAllStrings();
double[] vals = new double[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Double.parseDouble(fields[i]);
return vals;
}
/*** end: section (2 of 2) of code duplicated from In to StdIn */
/**
* Close the input stream.
*/
public void close() {
scanner.close();
}
/**
* Reads all ints from a file
* @deprecated Clearer to use
* <tt>new In(filename)</tt>.{@link #readAllInts()}
*/
public static int[] readInts(String filename) {
return new In(filename).readAllInts();
}
/**
* Reads all doubles from a file
* @deprecated Clearer to use
* <tt>new In(filename)</tt>.{@link #readAllDoubles()}
*/
public static double[] readDoubles(String filename) {
return new In(filename).readAllDoubles();
}
/**
* Reads all strings from a file
* @deprecated Clearer to use
* <tt>new In(filename)</tt>.{@link #readAllStrings()}
*/
public static String[] readStrings(String filename) {
return new In(filename).readAllStrings();
}
/**
* Reads all ints from stdin
* @deprecated Clearer to use {@link StdIn#readAllInts()}
*/
public static int[] readInts() {
return new In().readAllInts();
}
/**
* Reads all doubles from stdin
* @deprecated Clearer to use {@link StdIn#readAllDoubles()}
*/
public static double[] readDoubles() {
return new In().readAllDoubles();
}
/**
* Reads all strings from stdin
* @deprecated Clearer to use {@link StdIn#readAllStrings()}
*/
public static String[] readStrings() {
return new In().readAllStrings();
}
/**
* Test client.
*/
public static void main(String[] args) {
In in;
String urlName = "http://introcs.cs.princeton.edu/stdlib/InTest.txt";
// read from a URL
System.out.println("readAll() from URL " + urlName);
System.out.println("---------------------------------------------------------------------------");
try {
in = new In(urlName);
System.out.println(in.readAll());
} catch (Exception e) {
System.out.println(e);
}
System.out.println();
// read one line at a time from URL
System.out.println("readLine() from URL " + urlName);
System.out.println("---------------------------------------------------------------------------");
try {
in = new In(urlName);
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
} catch (Exception e) {
System.out.println(e);
}
System.out.println();
// read one string at a time from URL
System.out.println("readString() from URL " + urlName);
System.out.println("---------------------------------------------------------------------------");
try {
in = new In(urlName);
while (!in.isEmpty()) {
String s = in.readString();
System.out.println(s);
}
} catch (Exception e) {
System.out.println(e);
}
System.out.println();
// read one line at a time from file in current directory
System.out.println("readLine() from current directory");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("./InTest.txt");
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
} catch (Exception e) {
System.out.println(e);
}
System.out.println();
// read one line at a time from file using relative path
System.out.println("readLine() from relative path");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("../stdlib/InTest.txt");
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
} catch (Exception e) {
System.out.println(e);
}
System.out.println();
// read one char at a time
System.out.println("readChar() from file");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("InTest.txt");
while (!in.isEmpty()) {
char c = in.readChar();
System.out.print(c);
}
} catch (Exception e) {
System.out.println(e);
}
System.out.println();
System.out.println();
// read one line at a time from absolute OS X / Linux path
System.out.println("readLine() from absolute OS X / Linux path");
System.out.println("---------------------------------------------------------------------------");
in = new In("/n/fs/introcs/www/java/stdlib/InTest.txt");
try {
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
} catch (Exception e) {
System.out.println(e);
}
System.out.println();
// read one line at a time from absolute Windows path
System.out.println("readLine() from absolute Windows path");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("G:\\www\\introcs\\stdlib\\InTest.txt");
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
System.out.println();
} catch (Exception e) {
System.out.println(e);
}
System.out.println();
}
}
| TaylorHuston/Java_Graph | In.java |
1,068 | //Write a program for simple RSA algorithm to encrypt and decrypt the data.
//change all teh public names accordingly to file names
import java.io.DataInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Random;
public class RSA
{
private BigInteger p,q,N,phi,e,d;
private int bitlength=1024;
private Random r;
public RSA()
{
r=new Random();
p=BigInteger.probablePrime(bitlength,r);
q=BigInteger.probablePrime(bitlength,r);
System.out.println("Prime number p is"+p);
System.out.println("prime number q is"+q);
N=p.multiply(q);
phi=p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
e=BigInteger.probablePrime(bitlength/2,r);
while(phi.gcd(e).compareTo(BigInteger.ONE)>0&&e.compareTo(phi)<0)
{
e.add(BigInteger.ONE);
}
System.out.println("Public key is"+e);
d=e.modInverse(phi);
System.out.println("Private key is"+d);
}
public RSA(BigInteger e,BigInteger d,BigInteger N)
{
this.e=e;
this.d=d;
this.N=N;
}
public static void main(String[] args)throws IOException
{
RSA rsa=new RSA();
DataInputStream in=new DataInputStream(System.in);
String testString;
System.out.println("Enter the plain text:");
testString=in.readLine();
System.out.println("Encrypting string:"+testString);
System.out.println("string in bytes:"+bytesToString(testString.getBytes()));
byte[] encrypted=rsa.encrypt(testString.getBytes());
byte[] decrypted=rsa.decrypt(encrypted);
System.out.println("Dcrypting Bytes:"+bytesToString(decrypted));
System.out.println("Dcrypted string:"+new String(decrypted));
}
private static String bytesToString(byte[] encrypted)
{
String test=" ";
for(byte b:encrypted)
{
test+=Byte.toString(b);
}
return test;
}
public byte[]encrypt(byte[]message)
{
return(new BigInteger(message)).modPow(e,N).toByteArray();
}
public byte[]decrypt(byte[]message)
{
return(new BigInteger(message)).modPow(d,N).toByteArray();
}
}
| shreyashbandekar/JSS-CN.lab | 6.java |
1,069 | //package com.company;
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class A {
// public class Main {
public static void main(String[] args) throws IOException {
int x=sc.nextInt();
out.println(x*x+"");
close.close();
}
static void debug(Object... obj) {
System.err.println(Arrays.deepToString(obj).replace("], ", "]\n"));
}
static class Sc {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Sc() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Sc(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public String nextString() throws IOException {
StringBuilder sb = new StringBuilder();
int n = read();
while (isWhiteSpace(n))
n = read();
while (!isWhiteSpace(n)) {
sb.append((char) n);
n = read();
}
return sb.toString();
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1)
return true;
return false;
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
static class Print {
private final OutputStream out;
public Print() {
this.out = System.out;
}
public void print(String str) throws IOException {
for (int i = 0; i < str.length(); i++) {
out.write(str.charAt(i));
}
}
public void println(String str) throws IOException {
print(str);
out.write('\n');
}
public void close() throws IOException {
out.close();
}
}
static Sc sc = new Sc();
static Print out = new Print();
static BufferedWriter close = new BufferedWriter(new OutputStreamWriter(System.out));
} | IAFahim/CP | A.java |
1,070 | import java.util.List;
import java.util.Random;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class wu
extends sb
implements wr, yl
{
private static final Logger bH = ;
public static final ke<Integer> a = kh.a(wu.class, kg.b);
public double[][] b = new double[64][3];
public int c = -1;
public ws[] bt;
public ws bu;
public ws bv;
public ws bw;
public ws bx;
public ws by;
public ws bz;
public ws bA;
public ws bB;
public float bC;
public float bD;
public boolean bE;
public int bF;
public wt bG;
private final ata bI;
private final xl bJ;
private int bK = 200;
private int bL;
private final ayn[] bM = new ayn[24];
private final int[] bN = new int[24];
private final ayl bO = new ayl();
public wu(aht β)
{
super(β);
this.bt = new ws[] { this.bu = new ws(this, "head", 6.0F, 6.0F), this.bv = new ws(this, "neck", 6.0F, 6.0F), this.bw = new ws(this, "body", 8.0F, 8.0F), this.bx = new ws(this, "tail", 4.0F, 4.0F), this.by = new ws(this, "tail", 4.0F, 4.0F), this.bz = new ws(this, "tail", 4.0F, 4.0F), this.bA = new ws(this, "wing", 4.0F, 4.0F), this.bB = new ws(this, "wing", 4.0F, 4.0F) };
c(bW());
a(16.0F, 8.0F);
this.Q = true;
this.Y = true;
this.bK = 100;
this.ah = true;
if ((!β.E) && ((β.s instanceof atb))) {
this.bI = ((atb)β.s).s();
} else {
this.bI = null;
}
this.bJ = new xl(this);
}
protected void bA()
{
super.bA();
a(yt.a).a(200.0D);
}
protected void i()
{
super.i();
R().a(a, Integer.valueOf(xk.k.b()));
}
public double[] a(int β, float β)
{
if (bQ() <= 0.0F) {
β = 0.0F;
}
β = 1.0F - β;
int β = this.c - β & 0x3F;
int β = this.c - β - 1 & 0x3F;
double[] β = new double[3];
double β = this.b[β][0];
double β = on.g(this.b[β][0] - β);
β[0] = (β + β * β);
β = this.b[β][1];
β = this.b[β][1] - β;
β[1] = (β + β * β);
β[2] = (this.b[β][2] + (this.b[β][2] - this.b[β][2]) * β);
return β;
}
public void n()
{
if (this.l.E)
{
c(bQ());
if (!ad())
{
float β = on.b(this.bD * 6.2831855F);
float β = on.b(this.bC * 6.2831855F);
if ((β <= -0.3F) && (β >= -0.3F)) {
this.l.a(this.p, this.q, this.r, ng.aP, bz(), 5.0F, 0.8F + this.S.nextFloat() * 0.3F, false);
}
if ((!this.bJ.a().a()) && (--this.bK < 0))
{
this.l.a(this.p, this.q, this.r, ng.aQ, bz(), 2.5F, 0.8F + this.S.nextFloat() * 0.3F, false);
this.bK = (200 + this.S.nextInt(200));
}
}
}
this.bC = this.bD;
if (bQ() <= 0.0F)
{
float β = (this.S.nextFloat() - 0.5F) * 8.0F;
float β = (this.S.nextFloat() - 0.5F) * 4.0F;
float β = (this.S.nextFloat() - 0.5F) * 8.0F;
this.l.a(cy.b, this.p + β, this.q + 2.0D + β, this.r + β, 0.0D, 0.0D, 0.0D, new int[0]);
return;
}
cV();
float β = 0.2F / (on.a(this.s * this.s + this.u * this.u) * 10.0F + 1.0F);
β *= (float)Math.pow(2.0D, this.t);
if (this.bJ.a().a()) {
this.bD += 0.1F;
} else if (this.bE) {
this.bD += β * 0.5F;
} else {
this.bD += β;
}
this.v = on.g(this.v);
if (cR())
{
this.bD = 0.5F;
return;
}
if (this.c < 0) {
for (int β = 0; β < this.b.length; β++)
{
this.b[β][0] = this.v;
this.b[β][1] = this.q;
}
}
if (++this.c == this.b.length) {
this.c = 0;
}
this.b[this.c][0] = this.v;
this.b[this.c][1] = this.q;
if (this.l.E)
{
if (this.bg > 0)
{
double β = this.p + (this.bh - this.p) / this.bg;
double β = this.q + (this.bi - this.q) / this.bg;
double β = this.r + (this.bj - this.r) / this.bg;
double β = on.g(this.bk - this.v);
this.v = ((float)(this.v + β / this.bg));
this.w = ((float)(this.w + (this.bl - this.w) / this.bg));
this.bg -= 1;
b(β, β, β);
b(this.v, this.w);
}
this.bJ.a().b();
}
else
{
xe β = this.bJ.a();
β.c();
if (this.bJ.a() != β)
{
β = this.bJ.a();
β.c();
}
bbj β = β.g();
if (β != null)
{
double β = β.b - this.p;
double β = β.c - this.q;
double β = β.d - this.r;
double β = β * β + β * β + β * β;
float β = β.f();
β = on.a(β / on.a(β * β + β * β), -β, β);
this.t += β * 0.10000000149011612D;
this.v = on.g(this.v);
double β = on.a(on.g(180.0D - on.b(β, β) * 57.2957763671875D - this.v), -50.0D, 50.0D);
bbj β = new bbj(β.b - this.p, β.c - this.q, β.d - this.r).a();
bbj β = new bbj(on.a(this.v * 0.017453292F), this.t, -on.b(this.v * 0.017453292F)).a();
float β = Math.max(((float)β.b(β) + 0.5F) / 1.5F, 0.0F);
this.bf *= 0.8F;
this.bf = ((float)(this.bf + β * β.h()));
this.v += this.bf * 0.1F;
float β = (float)(2.0D / (β + 1.0D));
float β = 0.06F;
a(0.0F, -1.0F, β * (β * β + (1.0F - β)));
if (this.bE) {
d(this.s * 0.800000011920929D, this.t * 0.800000011920929D, this.u * 0.800000011920929D);
} else {
d(this.s, this.t, this.u);
}
bbj β = new bbj(this.s, this.t, this.u).a();
float β = ((float)β.b(β) + 1.0F) / 2.0F;
β = 0.8F + 0.15F * β;
this.s *= β;
this.u *= β;
this.t *= 0.9100000262260437D;
}
}
this.aM = this.v;
this.bu.G = (this.bu.H = 1.0F);
this.bv.G = (this.bv.H = 3.0F);
this.bx.G = (this.bx.H = 2.0F);
this.by.G = (this.by.H = 2.0F);
this.bz.G = (this.bz.H = 2.0F);
this.bw.H = 3.0F;
this.bw.G = 5.0F;
this.bA.H = 2.0F;
this.bA.G = 4.0F;
this.bB.H = 3.0F;
this.bB.G = 4.0F;
float β = (float)(a(5, 1.0F)[1] - a(10, 1.0F)[1]) * 10.0F * 0.017453292F;
float β = on.b(β);
float β = on.a(β);
float β = this.v * 0.017453292F;
float β = on.a(β);
float β = on.b(β);
this.bw.m();
this.bw.b(this.p + β * 0.5F, this.q, this.r - β * 0.5F, 0.0F, 0.0F);
this.bA.m();
this.bA.b(this.p + β * 4.5F, this.q + 2.0D, this.r + β * 4.5F, 0.0F, 0.0F);
this.bB.m();
this.bB.b(this.p - β * 4.5F, this.q + 2.0D, this.r - β * 4.5F, 0.0F, 0.0F);
if ((!this.l.E) && (this.ax == 0))
{
a(this.l.b(this, this.bA.bl().b(4.0D, 2.0D, 4.0D).c(0.0D, -2.0D, 0.0D)));
a(this.l.b(this, this.bB.bl().b(4.0D, 2.0D, 4.0D).c(0.0D, -2.0D, 0.0D)));
b(this.l.b(this, this.bu.bl().g(1.0D)));
b(this.l.b(this, this.bv.bl().g(1.0D)));
}
double[] β = a(5, 1.0F);
float β = on.a(this.v * 0.017453292F - this.bf * 0.01F);
float β = on.b(this.v * 0.017453292F - this.bf * 0.01F);
this.bu.m();
this.bv.m();
float β = q(1.0F);
this.bu.b(this.p + β * 6.5F * β, this.q + β + β * 6.5F, this.r - β * 6.5F * β, 0.0F, 0.0F);
this.bv.b(this.p + β * 5.5F * β, this.q + β + β * 5.5F, this.r - β * 5.5F * β, 0.0F, 0.0F);
for (int β = 0; β < 3; β++)
{
ws β = null;
if (β == 0) {
β = this.bx;
}
if (β == 1) {
β = this.by;
}
if (β == 2) {
β = this.bz;
}
double[] β = a(12 + β * 2, 1.0F);
float β = this.v * 0.017453292F + c(β[0] - β[0]) * 0.017453292F;
float β = on.a(β);
float β = on.b(β);
float β = 1.5F;
float β = (β + 1) * 2.0F;
β.m();
β.b(this.p - (β * β + β * β) * β, this.q + (β[1] - β[1]) - (β + β) * β + 1.5D, this.r + (β * β + β * β) * β, 0.0F, 0.0F);
}
if (!this.l.E)
{
this.bE = (b(this.bu.bl()) | b(this.bv.bl()) | b(this.bw.bl()));
if (this.bI != null) {
this.bI.b(this);
}
}
}
private float q(float β)
{
double β = 0.0D;
if (this.bJ.a().a())
{
β = -1.0D;
}
else
{
double[] β = a(5, 1.0F);
double[] β = a(0, 1.0F);
β = β[1] - β[0];
}
return (float)β;
}
private void cV()
{
if (this.bG != null) {
if (this.bG.F) {
this.bG = null;
} else if ((this.T % 10 == 0) &&
(bQ() < bW())) {
c(bQ() + 1.0F);
}
}
if (this.S.nextInt(10) == 0)
{
List<wt> β = this.l.a(wt.class, bl().g(32.0D));
wt β = null;
double β = Double.MAX_VALUE;
for (wt β : β)
{
double β = β.h(this);
if (β < β)
{
β = β;
β = β;
}
}
this.bG = β;
}
}
private void a(List<rr> β)
{
double β = (this.bw.bl().a + this.bw.bl().d) / 2.0D;
double β = (this.bw.bl().c + this.bw.bl().f) / 2.0D;
for (rr β : β) {
if ((β instanceof sa))
{
double β = β.p - β;
double β = β.r - β;
double β = β * β + β * β;
β.g(β / β * 4.0D, 0.20000000298023224D, β / β * 4.0D);
if ((!this.bJ.a().a()) && (((sa)β).bH() < β.T - 2))
{
β.a(rc.a(this), 5.0F);
a(this, β);
}
}
}
}
private void b(List<rr> β)
{
for (int β = 0; β < β.size(); β++)
{
rr β = (rr)β.get(β);
if ((β instanceof sa))
{
β.a(rc.a(this), 10.0F);
a(this, β);
}
}
}
private float c(double β)
{
return (float)on.g(β);
}
private boolean b(bbh β)
{
int β = on.c(β.a);
int β = on.c(β.b);
int β = on.c(β.c);
int β = on.c(β.d);
int β = on.c(β.e);
int β = on.c(β.f);
boolean β = false;
boolean β = false;
for (int β = β; β <= β; β++) {
for (int β = β; β <= β; β++) {
for (int β = β; β <= β; β++)
{
cj β = new cj(β, β, β);
arc β = this.l.o(β);
ajt β = β.t();
if ((β.a() != axe.a) && (β.a() != axe.o)) {
if (!this.l.U().b("mobGriefing")) {
β = true;
} else if ((β == aju.cv) || (β == aju.Z) || (β == aju.bH) || (β == aju.h) || (β == aju.bF) || (β == aju.bG)) {
β = true;
} else if ((β == aju.bX) || (β == aju.dc) || (β == aju.dd) || (β == aju.bi) || (β == aju.db)) {
β = true;
} else {
β = (this.l.g(β)) || (β);
}
}
}
}
}
if (β)
{
double β = β.a + (β.d - β.a) * this.S.nextFloat();
double β = β.b + (β.e - β.b) * this.S.nextFloat();
double β = β.c + (β.f - β.c) * this.S.nextFloat();
this.l.a(cy.b, β, β, β, 0.0D, 0.0D, 0.0D, new int[0]);
}
return β;
}
public boolean a(ws β, rc β, float β)
{
β = this.bJ.a().a(β, β, β);
if (β != this.bu) {
β = β / 4.0F + Math.min(β, 1.0F);
}
if (β < 0.01F) {
return false;
}
if (((β.j() instanceof zj)) || (β.c()))
{
float β = bQ();
e(β, β);
if ((bQ() <= 0.0F) && (!this.bJ.a().a()))
{
c(1.0F);
this.bJ.a(xk.j);
}
if (this.bJ.a().a())
{
this.bL = ((int)(this.bL + (β - bQ())));
if (this.bL > 0.25F * bW())
{
this.bL = 0;
this.bJ.a(xk.e);
}
}
}
return true;
}
public boolean a(rc β, float β)
{
if (((β instanceof rd)) && (((rd)β).x())) {
a(this.bw, β, β);
}
return false;
}
protected boolean e(rc β, float β)
{
return super.a(β, β);
}
public void Q()
{
T();
if (this.bI != null)
{
this.bI.b(this);
this.bI.a(this);
}
}
protected void bC()
{
if (this.bI != null) {
this.bI.b(this);
}
this.bF += 1;
if ((this.bF >= 180) && (this.bF <= 200))
{
float β = (this.S.nextFloat() - 0.5F) * 8.0F;
float β = (this.S.nextFloat() - 0.5F) * 4.0F;
float β = (this.S.nextFloat() - 0.5F) * 8.0F;
this.l.a(cy.c, this.p + β, this.q + 2.0D + β, this.r + β, 0.0D, 0.0D, 0.0D, new int[0]);
}
boolean β = this.l.U().b("doMobLoot");
int β = 500;
if ((this.bI != null) && (!this.bI.d())) {
β = 12000;
}
if (!this.l.E)
{
if ((this.bF > 150) && (this.bF % 5 == 0) && (β)) {
a(on.d(β * 0.08F));
}
if (this.bF == 1) {
this.l.a(1028, new cj(this), 0);
}
}
d(0.0D, 0.10000000149011612D, 0.0D);
this.aM = (this.v += 20.0F);
if ((this.bF == 200) && (!this.l.E))
{
if (β) {
a(on.d(β * 0.2F));
}
if (this.bI != null) {
this.bI.a(this);
}
T();
}
}
private void a(int β)
{
while (β > 0)
{
int β = rx.a(β);
β -= β;
this.l.a(new rx(this.l, this.p, this.q, this.r, β));
}
}
public int o()
{
if (this.bM[0] == null)
{
int β = 0;
int β = 0;
int β = 0;
int β = 0;
for (int β = 0; β < 24; β++)
{
int β = 5;
β = β;
if (β < 12)
{
β = (int)(60.0F * on.b(2.0F * (-3.1415927F + 0.2617994F * β)));
β = (int)(60.0F * on.a(2.0F * (-3.1415927F + 0.2617994F * β)));
}
else if (β < 20)
{
β -= 12;
β = (int)(40.0F * on.b(2.0F * (-3.1415927F + 0.3926991F * β)));
β = (int)(40.0F * on.a(2.0F * (-3.1415927F + 0.3926991F * β)));
β += 10;
}
else
{
β -= 20;
β = (int)(20.0F * on.b(2.0F * (-3.1415927F + 0.7853982F * β)));
β = (int)(20.0F * on.a(2.0F * (-3.1415927F + 0.7853982F * β)));
}
β = Math.max(this.l.K() + 10, this.l.q(new cj(β, 0, β)).q() + β);
this.bM[β] = new ayn(β, β, β);
}
this.bN[0] = 6146;
this.bN[1] = 8197;
this.bN[2] = 8202;
this.bN[3] = 16404;
this.bN[4] = 32808;
this.bN[5] = 32848;
this.bN[6] = 65696;
this.bN[7] = 131392;
this.bN[8] = 131712;
this.bN[9] = 263424;
this.bN[10] = 526848;
this.bN[11] = 525313;
this.bN[12] = 1581057;
this.bN[13] = 3166214;
this.bN[14] = 2138120;
this.bN[15] = 6373424;
this.bN[16] = 4358208;
this.bN[17] = 12910976;
this.bN[18] = 9044480;
this.bN[19] = 9706496;
this.bN[20] = 15216640;
this.bN[21] = 13688832;
this.bN[22] = 11763712;
this.bN[23] = 8257536;
}
return l(this.p, this.q, this.r);
}
public int l(double β, double β, double β)
{
float β = 10000.0F;
int β = 0;
ayn β = new ayn(on.c(β), on.c(β), on.c(β));
int β = 0;
if ((this.bI == null) || (this.bI.c() == 0)) {
β = 12;
}
for (int β = β; β < 24; β++) {
if (this.bM[β] != null)
{
float β = this.bM[β].b(β);
if (β < β)
{
β = β;
β = β;
}
}
}
return β;
}
public ayp a(int β, int β, ayn β)
{
for (int β = 0; β < 24; β++)
{
ayn β = this.bM[β];
β.i = false;
β.g = 0.0F;
β.e = 0.0F;
β.f = 0.0F;
β.h = null;
β.d = -1;
}
ayn β = this.bM[β];
ayn β = this.bM[β];
β.e = 0.0F;
β.f = β.a(β);
β.g = β.f;
this.bO.a();
this.bO.a(β);
ayn β = β;
int β = 0;
if ((this.bI == null) || (this.bI.c() == 0)) {
β = 12;
}
while (!this.bO.e())
{
ayn β = this.bO.c();
if (β.equals(β))
{
if (β != null)
{
β.h = β;
β = β;
}
return a(β, β);
}
if (β.a(β) < β.a(β)) {
β = β;
}
β.i = true;
int β = 0;
for (int β = 0; β < 24; β++) {
if (this.bM[β] == β)
{
β = β;
break;
}
}
for (int β = β; β < 24; β++) {
if ((this.bN[β] & 1 << β) > 0)
{
ayn β = this.bM[β];
if (!β.i)
{
float β = β.e + β.a(β);
if ((!β.a()) || (β < β.e))
{
β.h = β;
β.e = β;
β.f = β.a(β);
if (β.a())
{
this.bO.a(β, β.e + β.f);
}
else
{
β.g = (β.e + β.f);
this.bO.a(β);
}
}
}
}
}
}
if (β == β) {
return null;
}
bH.debug("Failed to find path from {} to {}", new Object[] { Integer.valueOf(β), Integer.valueOf(β) });
if (β != null)
{
β.h = β;
β = β;
}
return a(β, β);
}
private ayp a(ayn β, ayn β)
{
int β = 1;
ayn β = β;
while (β.h != null)
{
β++;
β = β.h;
}
ayn[] β = new ayn[β];
β = β;
β[(--β)] = β;
while (β.h != null)
{
β = β.h;
β[(--β)] = β;
}
return new ayp(β);
}
public void b(dn β)
{
super.b(β);
β.a("DragonPhase", this.bJ.a().i().b());
}
public void a(dn β)
{
super.a(β);
if (β.e("DragonPhase")) {
this.bJ.a(xk.a(β.h("DragonPhase")));
}
}
protected void L() {}
public rr[] aR()
{
return this.bt;
}
public boolean ap()
{
return false;
}
public aht a()
{
return this.l;
}
public nh bz()
{
return nh.f;
}
protected nf G()
{
return ng.aM;
}
protected nf bR()
{
return ng.aR;
}
protected float cd()
{
return 5.0F;
}
public float a(int β, double[] β, double[] β)
{
xe β = this.bJ.a();
xk<? extends xe> β = β.i();
double β;
double β;
if ((β == xk.d) || (β == xk.e))
{
cj β = this.l.q(auc.a);
float β = Math.max(on.a(d(β)) / 4.0F, 1.0F);
β = β / β;
}
else
{
double β;
if (β.a())
{
β = β;
}
else
{
double β;
if (β == 6) {
β = 0.0D;
} else {
β = β[1] - β[1];
}
}
}
return (float)β;
}
public bbj a(float β)
{
xe β = this.bJ.a();
xk<? extends xe> β = β.i();
bbj β;
if ((β == xk.d) || (β == xk.e))
{
cj β = this.l.q(auc.a);
float β = Math.max(on.a(d(β)) / 4.0F, 1.0F);
float β = 6.0F / β;
float β = this.w;
float β = 1.5F;
this.w = (-β * β * 5.0F);
bbj β = f(β);
this.w = β;
}
else if (β.a())
{
float β = this.w;
float β = 1.5F;
this.w = (-6.0F * β * 5.0F);
bbj β = f(β);
this.w = β;
}
else
{
β = f(β);
}
return β;
}
public void a(wt β, cj β, rc β)
{
zj β;
zj β;
if ((β.j() instanceof zj)) {
β = (zj)β.j();
} else {
β = this.l.a(β, 64.0D, 64.0D);
}
if (β == this.bG) {
a(this.bu, rc.b(β), 10.0F);
}
this.bJ.a().a(β, β, β, β);
}
public void a(ke<?> β)
{
if ((a.equals(β)) && (this.l.E)) {
this.bJ.a(xk.a(((Integer)R().a(a)).intValue()));
}
super.a(β);
}
public xl cT()
{
return this.bJ;
}
public ata cU()
{
return this.bI;
}
public void c(rl β) {}
protected boolean n(rr β)
{
return false;
}
public boolean aV()
{
return false;
}
}
| MCLabyMod/LabyMod-1.9 | wu.java |
1,071 | import java.util.concurrent.TimeUnit;
import java.util.Date;
import java.io.File;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.*;
import static org.openqa.selenium.OutputType.*;
public class 02 {
public static void main(String[] args) throws Exception {
FirefoxDriver wd;
wd = new FirefoxDriver();
wd.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
wd.get("http://www.metafilter.com/");
if (!wd.findElement(By.tagName("html")).getText().contains("Bob Godfrey 1921-2013")) {
System.out.println("verifyTextPresent failed");
}
wd.close();
}
public static boolean isAlertPresent(FirefoxDriver wd) {
try {
wd.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
}
| Zarkonnen/github_integration_test | 02.java |
1,072 | /*
Copyright 2006, Astrophysics Research Institute, Liverpool John Moores University.
This file is part of org.estar.astrometry.
org.estar.astrometry is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
org.estar.astrometry 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 org.estar.astrometry; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
// RA.java
package org.estar.astrometry;
import java.io.*;
import java.lang.*;
import java.text.*;
import java.util.*;
/**
* This class hold the coordinates for Right Ascension. The right ascension is represented internally
* with hours, minutes and seconds fields.
* @author Chris Mottram
* @version $Revision$
*/
public class RA implements Serializable
{
/**
* Revision Control System ID.
*/
public final static String RCSID = "$Id$";
/**
* Serial version ID. Fixed as instances of this class can be used as parameters (inside
* org.estar.rtml.RTMLDocument's) in RMI calls across JVMs.
*/
static final long serialVersionUID = 685728745827694925L;
/**
* Default character to separate hours, minutes and seconds. This is a colon ':'.
*/
public final static char DEFAULT_SEPERATOR = ':';
/**
* How many arc-seconds in 1 second of RA. A double, of value 15.
*/
public final static double SECONDS_TO_ARCSECONDS = 15.0;
/**
* How many arc-seconds in 1 day, The maximum number of arc-seconds represented by an RA
* before going back to zero.
*/
public final static double ARCSECONDS_PER_DAY = (24.0*60.0*60.0*15.0);
/**
* Index for tokenisation, for Hours of RA (0).
*/
private final static int TOKEN_INDEX_H = 0;
/**
* Index for tokenisation, for Minutes of RA (1).
*/
private final static int TOKEN_INDEX_M = 1;
/**
* Index for tokenisation, for Seconds of RA (2).
*/
private final static int TOKEN_INDEX_S = 2;
/**
* The number of hours of RA this object represents. Should be in the range 0..23.
*/
public int hours;
/**
* The number of minutes of RA this object represents. Should be in the range 0..59.
*/
public int minutes;
/**
* The number of seconds of RA this object represents. Should be in the range 0..59.999...
*/
public double seconds;
/**
* Default constructor.
*/
public RA()
{
super();
};
/**
* Constructor that sets field values.
* @param h The number of hours.
* @param m The number of minutes.
* @param s The number of seconds.
* @see #setHours
* @see #setMinutes
* @see #setSeconds
*/
public RA(int h,int m,double s)
{
super();
setHours(h);
setMinutes(m);
setSeconds(s);
}
/**
* Set the hours of Right Ascension.
* @param h Number of hours, in the range (0..23) inclusive.
* @exception IllegalArgumentException Thrown if hours are out of range.
* @see #hours
*/
public void setHours(int h) throws IllegalArgumentException
{
if(h < 0)
{
throw new IllegalArgumentException(this.getClass().getName()+
":setHours:+Illegal number of hours:"+h+
": Must be positive.");
}
if(h > 23)
{
throw new IllegalArgumentException(this.getClass().getName()+
":setHours:+Illegal number of hours:"+h+
": Must be less than 24.");
}
hours = h;
}
/**
* Return the number of hours of right ascension represented by this object.
* @return An integer, between 0 and 23 inclusive.
* @see #hours
*/
public int getHours()
{
return hours;
}
/**
* Set the minutes of Right Ascension.
* @param m Number of minutes, in the range (0..59) inclusive.
* @exception IllegalArgumentException Thrown if the value is out of range.
* @see #minutes
*/
public void setMinutes(int m) throws IllegalArgumentException
{
if(m < 0)
{
throw new IllegalArgumentException(this.getClass().getName()+
":setMinutes:+Illegal number of minutes:"+m+
": Must be positive.");
}
if(m > 59)
{
throw new IllegalArgumentException(this.getClass().getName()+
":setMinutes:+Illegal number of minutes:"+m+
": Must be less than 60.");
}
minutes = m;
}
/**
* Return the number of minutes of right ascension represented by this object.
* @return An integer, between 0 and 59 inclusive.
* @see #minutes
*/
public int getMinutes()
{
return minutes;
}
/**
* Set the seconds of Right Ascension.
* @param m Number of seconds, greater or equal to 0 and less than 60.
* However, we allow seconds of 60.0 as they can occur due to rounding errors.
* e.g. The ESO/ECF server returns them!
* @exception IllegalArgumentException Thrown if the value is out of range.
* @see #seconds
*/
public void setSeconds(double s) throws IllegalArgumentException
{
if(s < 0.0)
{
throw new IllegalArgumentException(this.getClass().getName()+
":setSeconds:+Illegal number of seconds:"+s+
": Must be positive.");
}
if(s > 60.0)
{
throw new IllegalArgumentException(this.getClass().getName()+
":setSeconds:+Illegal number of seconds:"+s+
": Must be less than 60.");
}
seconds = s;
}
/**
* Return the number of seconds of right ascension represented by this object.
* @return A double, greater or equal to 0 and less than 60.
* @see #seconds
*/
public double getSeconds()
{
return seconds;
}
/**
* Method to parse a Right Ascension from a string. The hours, minutes and seconds
* should be delimited by a dot ('.').
* @param s A string representing a right ascension.
* @see #parseSeperator
*/
public void parseDot(String s)
{
parseSeperator(s,".");
}
/**
* Method to parse a Right Ascension from a string. The hours, minutes and seconds
* should be delimited by a colon (':').
* @param s A string representing a right ascension.
* @see #parseSeperator
*/
public void parseColon(String s)
{
parseSeperator(s,":");
}
/**
* Method to parse a Right Ascension from a string. The hours, minutes and seconds
* should be delimited by a space (' ').
* @param s A string representing a right ascension.
* @see #parseSeperator
*/
public void parseSpace(String s)
{
parseSeperator(s," ");
}
/**
* Return the RA as a number of arc-seconds. Note, there are 15 arc-seconds in every second.
* @return This RA, as a number of arc-seconds.
* @see #SECONDS_TO_ARCSECONDS
*/
public double toArcSeconds()
{
double d;
d = (((((double)hours)*60.0)+((double)minutes))*60.0)+seconds;
d = d * SECONDS_TO_ARCSECONDS;
return d;
}
/**
* Routine to set RA from a number of arc-seconds.
* @param as The number of arc-seconds, greater or equal to zero and less than ARCSECONDS_PER_DAY.
* @exception IllegalArgumentException Thrown if the value is out of range.
* @see #SECONDS_TO_ARCSECONDS
* @see #ARCSECONDS_PER_DAY
*/
public void fromArcSeconds(double as) throws IllegalArgumentException
{
int h,m;
double seconds;
// range check
if(as < 0.0)
{
throw new IllegalArgumentException(this.getClass().getName()+
":fromArcSeconds:+Illegal number of arc-seconds:"+as+
": Must be positive.");
}
if(as >= ARCSECONDS_PER_DAY)
{
throw new IllegalArgumentException(this.getClass().getName()+
":fromArcSeconds:+Illegal number of arc-seconds:"+as+
": Must be less than "+ARCSECONDS_PER_DAY+".");
}
h = ((int)as) / (60*60*15);
setHours(h);
m = (((int)as) - (h*3600*15))/(60*15);
setMinutes(m);
// seconds = remainder arc-secs / SECONDS_TO_ARCSECONDS
seconds = (as-((h*3600.0*SECONDS_TO_ARCSECONDS)+(m*60.0*SECONDS_TO_ARCSECONDS)))/SECONDS_TO_ARCSECONDS;
setSeconds(seconds);
}
/**
* Routine to set RA from radians. Done by conversion into arc-seconds, and then calling
* fromArcSeconds. The number of arc-seonds for this number of radians is:
* <pre>(ARCSECONDS_PER_DAY*radians)/2*PI</pre>
* @param radians The number of radians.
* @see #ARCSECONDS_PER_DAY
* @see #fromArcSeconds
*/
public void fromRadians(double radians) throws IllegalArgumentException
{
double as;
if(radians < 0.0)
{
throw new IllegalArgumentException(this.getClass().getName()+
":fromRadians:+Illegal number of radians:"+radians+
": Must be positive.");
}
if(radians >= (2*Math.PI))
{
throw new IllegalArgumentException(this.getClass().getName()+
":fromRadians:+Illegal number of radians:"+radians+
": Must be less than "+(2*Math.PI)+".");
}
as = (ARCSECONDS_PER_DAY * radians)/(2*Math.PI);
fromArcSeconds(as);
}
/**
* Routine to convert RA to radians. Done by conversion into arc-seconds, and then converting to radians.
* @return The number of radians.
* @see #ARCSECONDS_PER_DAY
* @see #toArcSeconds
*/
public double toRadians() throws IllegalArgumentException
{
return (toArcSeconds()*(2*Math.PI))/ARCSECONDS_PER_DAY;
}
/**
* Method to print out a right ascension as a string.
* e.g.: <pre>HH:MM:SS.ss</pre>
* @see #toString(char)
* @see #DEFAULT_SEPERATOR
*/
public String toString()
{
return toString(DEFAULT_SEPERATOR);
}
/**
* Method to print out a right ascension as a string.
* e.g.: <pre>HH<separator>MM<separator>SS.ss</pre>
* @param separator The character to delimit the hours, minutes and seconds by. This is usually a colon, dot
* or space.
* @return A valid string representation of the right ascension specified by this object. Note, the
* seconds field is formatted to two decimal places.
*/
public String toString(char separator)
{
DecimalFormat df = null;
DecimalFormat dfd = null;
df = new DecimalFormat("00");
dfd = new DecimalFormat("00.00");
return new String(df.format(hours)+separator+df.format(minutes)+separator+dfd.format(seconds));
}
/**
* Method to parse a string representation of a right ascension, and set the fields of this object
* accordingly. Note this can throw a NumberFormatException from the Integer.parseInt and
* Double.parseDouble calls it makes..
* @param s The string to parse.
* @param separator A string representing the seperator. N.B. Should be a char?
*/
private void parseSeperator(String s,String seperator)
{
StringTokenizer st = null;
String valueString = null;
int tokenCount,intValue;
double doubleValue;
st = new StringTokenizer(s,seperator);
tokenCount = st.countTokens();
for(int i=0; i< tokenCount; i++)
{
valueString = st.nextToken();
switch(i)
{
case TOKEN_INDEX_H:
hours = Integer.parseInt(valueString);
break;
case TOKEN_INDEX_M:
minutes = Integer.parseInt(valueString);
break;
case TOKEN_INDEX_S:
seconds = Double.parseDouble(valueString);
break;
}// end switch
}// end for
}
};
//
// $Log: not supported by cvs2svn $
// Revision 1.7 2007/01/30 18:30:36 cjm
// gnuify: Added GNU General Public License.
//
// Revision 1.6 2005/05/12 11:31:28 cjm
// Made serializable for deep-cloning purposes.
//
// Revision 1.5 2005/01/18 15:44:49 cjm
// Added toRadians.
//
// Revision 1.4 2003/03/04 13:20:21 cjm
// Relaxed checking of seconds, to allow seconds of 60.0 exactley, as
// ESO ECF USNOA2 server returns these (presumably a rounding error).
//
// Revision 1.3 2003/02/24 13:14:12 cjm
// Commenting and error checks.
//
// Revision 1.2 2003/01/27 19:32:01 cjm
// Added fromArcSeconds.
//
// Revision 1.1 2002/12/29 22:00:57 cjm
// Initial revision
//
//
| LivTel/org_estar_astrometry | RA.java |
1,073 | ///usr/bin/env jbang "$0" "$@" ; exit $?
//JAVA 16
//SOURCES **/*.java
// SOURCES sakila/**/*.java
//DEPS io.quarkus:quarkus-bom:${quarkus.version:2.0.0.Final}@pom
//DEPS io.quarkus:quarkus-hibernate-orm-panache
//DEPS io.quarkus:quarkus-jdbc-postgresql
//DEPS org.postgresql:postgresql:42.2.14
//DEPS org.testcontainers:postgresql:1.15.2
//DEPS io.quarkus:quarkus-hibernate-orm
//jbang bug requires me to have them here
//DEPS org.jooq:jooq:3.14.7
//DEPS org.jooq:jooq-meta:3.14.7
//DEPS org.jooq:jooq-codegen:3.14.7
//Q:CONFIG quarkus.banner.enabled=false
//Q:CONFIG quarkus.log.level=WARN
//Q:CONFIG quarkus.log.category."org.hibernate.stat".level=DEBUG
//Q:CONFIG quarkus.hibernate-orm.log.sql=falses
//Q:CONFIG quarkus.hibernate-orm.log.format-sql=true
//Q:CONFIG quarkus.hibernate-orm.jdbc.statement-batch-size=20
//Q:CONFIG quarkus.datasource.db-kind=postgresql
//Q:CONFIG quarkus.datasource.username=postgres
//Q:CONFIG quarkus.datasource.password=sakila
//Q:CONFIG quarkus.hibernate-orm.statistics=true
//Q:CONFIG quarkus.datasource.jdbc.url=jdbc:postgresql://localhost:5432/sakila
import static util.Printer.print;
import static util.Printer.stats;
import java.math.BigDecimal;
import java.sql.Date;
import java.util.List;
import java.util.Map;
import javax.enterprise.context.Dependent;
import javax.enterprise.context.control.ActivateRequestContext;
import javax.inject.Inject;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.transaction.Transactional;
import javax.transaction.Transactional.TxType;
import javax.transaction.UserTransaction;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.StatelessSession;
import org.hibernate.stat.Statistics;
import org.hibernate.transform.Transformers;
import org.hibernate.type.LongType;
import org.hibernate.type.StringType;
import io.quarkus.hibernate.orm.panache.PanacheEntityBase;
import io.quarkus.narayana.jta.runtime.TransactionConfiguration;
import io.quarkus.runtime.QuarkusApplication;
import io.quarkus.runtime.annotations.QuarkusMain;
@QuarkusMain
public class db implements QuarkusApplication {
private final DbService dbService;
public db(DbService dbService) {
this.dbService = dbService;
}
@Override
@ActivateRequestContext
@Transactional
public int run(String... args) throws Exception {
dbService.doData("Quarkus Insights");
return 0;
}
@Entity
@Table(name = "actor")
static public class Actor extends PanacheEntityBase {
@Id
public long actor_id;
public String first_name;
public String last_name;
public Date last_update;
@Override
public String toString() {
return actor_id + ": " + first_name + " " + last_name;
}
}
@Entity
@Table(name = "language")
static public class Language extends PanacheEntityBase {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public long language_id;
public String name;
}
}
@Dependent
class DbService {
@Inject
EntityManager em;
@Transactional(TxType.REQUIRES_NEW)
void updateViaEntity() {
List<db.Actor> actors = db.Actor.listAll();
System.out.println("Updating " + actors.size() + " actors");
for (db.Actor actor : actors) {
if (Character.isUpperCase(actor.first_name.charAt(0))) {
actor.first_name = actor.first_name.toLowerCase();
} else {
actor.first_name = actor.first_name.toUpperCase();
}
}
};
void doData(String name) throws Exception {
System.out.println("Hello " + name + "!");
//managedUpdate();
//bulkProcessing(true);
//bulkStatelessProcessing();
//nativeQueries();
resultTransformers();
}
@TransactionConfiguration(timeout = 50000)
private void bulkProcessing(boolean manual) {
System.out.println("Insert lots of rows");
for (int i = 0; i < 100000; i++) {
db.Language lang = new db.Language();
lang.name = "A-" + i;
System.out.println(lang.name);
em.persist(lang);
if(manual) {
if ( i % 100 == 0 ) {
//commit and begin to do it manually in batches.
System.out.println("Manual flush!");
em.flush();
em.clear();
}
}
}
}
private void bulkStatelessProcessing() throws Exception {
StatelessSession ss = getStatelessSession();
System.out.println("Insert lots of rows with stateless session");
for ( int i=0; i<100000; i++ ) {
db.Language lang = new db.Language();
lang.name = "A-" + i;
System.out.println(lang.name);
ss.insert(lang);
}
}
private void managedUpdate() {
Statistics statistics = em.getEntityManagerFactory().unwrap(SessionFactory.class).getStatistics();
stats(statistics);
updateViaEntity();
stats(statistics);
}
@SuppressWarnings({ "unchecked", "deprecation" }) // here as we are dealing with non-type-safe streams
private void resultTransformers() {
print("****RESULT TRANSFORMERS****");
String sql = """
select extract(year from pay.payment_date) y, extract(month from pay.payment_date) m, stf.first_name, stf.last_name, sum(pay.amount)
from staff stf
left join payment pay
on stf.staff_id = pay.staff_id
group by y, m, stf.first_name, stf.last_name
""";
Session session = getSession();
// Every column gets added
List<Map<String, Object>> list = session.createSQLQuery(sql)
.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
list.forEach(item -> {
print(item.get("first_name") + " sold for " + item.get("sum") + " in " + item.get("y") + "-"
+ item.get("m"));
});
print("Explicit types");
list = session.createSQLQuery(sql).addScalar("y", LongType.INSTANCE).addScalar("m", LongType.INSTANCE)
.addScalar("sum").addScalar("first_name").addScalar("last_name")
.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
list.forEach(item -> {
print(item.get("first_name") + " sold for " + item.get("sum") + " in " + item.get("y") + "-"
+ item.get("m"));
});
print("DTO's");
List<SaleDTO> typeDtos = session.createSQLQuery(sql).addScalar("y", LongType.INSTANCE)
.addScalar("m", LongType.INSTANCE).addScalar("sum").addScalar("first_name").addScalar("last_name")
.setResultTransformer(Transformers.aliasToBean(SaleDTO.class)).list();
typeDtos.forEach(item -> {
print(item.first_name + " sold for " + item.sum + " in " + item.y + "-" + item.m);
});
}
static public class SaleDTO {
public long m;
public long y;
public String first_name;
public String last_name;
public BigDecimal sum;
}
private Session getSession() {
return em.unwrap(Session.class);
}
private StatelessSession getStatelessSession() {
return em.getEntityManagerFactory().unwrap(SessionFactory.class).openStatelessSession();
}
private void nativeQueries() {
print(em.createNativeQuery("select * from Actor", db.Actor.class).getResultStream().findFirst());
StatelessSession session = getStatelessSession();
session.doWork(connection -> {
String sql = """
SELECT first_name, last_name, count(*) films
FROM actor AS a
JOIN film_actor AS fa USING (actor_id)
GROUP BY actor_id, first_name, last_name
ORDER BY films DESC
LIMIT 1;
""";
/*
DSLContext create = DSL.using(connection, SQLDialect.POSTGRES);
Field<Integer> COUNT = DSL.field("COUNT(*)", Integer.class);
String jooqsql = create.select(ACTOR.FIRST_NAME, ACTOR.LAST_NAME, COUNT.as("films")).from(ACTOR)
.join(FILM_ACTOR).using(FILM_ACTOR.ACTOR_ID)
.groupBy(ACTOR.ACTOR_ID, ACTOR.FIRST_NAME, ACTOR.LAST_NAME).orderBy(COUNT.desc()).limit(1)
.getSQL(ParamType.INLINED);
*/
print(session.createSQLQuery(sql).addScalar("first_name", StringType.INSTANCE)
.addScalar("last_name", StringType.INSTANCE).addScalar("films", LongType.INSTANCE)
.getSingleResult());
});
}
} | maxandersen/quarkus-insights-effective-persistence | db.java |
1,074 | public class UI
{
/**
* Summary: shows the title to the user
* @param: None
* @return: None
*/
public static void showTitle()
{
System.out.println(" ____ _____ _ ____ _____ _ _____ _ ____ _ ____ _____ _____ ____ ");
System.out.println("/ ___\\/__ __\\/ \\ /\\/ _ \\/ __// \\ /|/__ __\\ / \\__/|/ _ \\/ \\ /|/ _ \\/ __// __// __\\");
System.out.println("| \\ / \\ | | ||| | \\|| \\ | |\\ || / \\ | |\\/||| / \\|| |\\ ||| / \\|| | _| \\ | \\/|");
System.out.println("\\___ | | | | \\_/|| |_/|| /_ | | \\|| | | | | ||| |-||| | \\||| |-||| |_//| /_ | /");
System.out.println("\\____/ \\_/ \\____/\\____/\\____\\\\_/ \\| \\_/ \\_/ \\|\\_/ \\|\\_/ \\|\\_/ \\|\\____\\\\____\\\\_/\\_\\");
}//END of showTitle
/**
* Summary: shows intro message to user
* @param: None
* @return: None
*/
public static void showIntro()
{
System.out.println("Welcome to the new student manager system.");
System.out.println("With the help of our program, you will be able to track all of your students as well as their marks.");
System.out.println("Let's get started by entering the names of your students as well as their marks.");
}//END of showIntro
/**
* Summary: show menu to user
* @param: None
* @return: None
*/
public static void showMenu()
{
System.out.println("1) Add a student");
System.out.println("2) Remove a student");
System.out.println("3) Modify a mark");
System.out.println("4) Find a student by ID");
System.out.println("5) Average mark for class");
System.out.println("6) Minimum mark for class");
System.out.println("7) Maxmimum mark for class");
System.out.println("8) Get Information for the whole class");
System.out.println("9) Quit");
}//END of showMenu
/**
* Summary: show goodbye message to user
* @param: None
* @return: None
*/
public static void showBye()
{
System.out.println(" ____ ___ _ _____ _ ");
System.out.println("/ __\\\\ \\/// __// \\");
System.out.println("| | // \\ / | \\ | |");
System.out.println("| |_\\ / / | /_ \\_/");
System.out.println("\\____//_/ \\____\\(_)");
}//END of showBye
}//END of UI | ElyTgy/student-system | UI.java |
1,075 | package Receiver;
/* Receiver package contains RX and RC4 classes. Rx class receives packets from transmitter and
sends IACK or DACK accordingly based on the packet type. The data received is then decrypted using
the same key as used for encryption using RC4 algorithm */
import java.util.*;
import java.net.*;
import java.io.*;
public class Rx {
private short integrity_check = 0;
private short sequence_no;
private short packet_type;
static short current_sequence_no;
static short initial_sequence_no;
static int PORT = 9999;
static byte[] nonce=new byte[8];
public Rx(short integrity_check, short sequence_no, short packet_type) {
this.integrity_check = integrity_check;
this.sequence_no = sequence_no;
this.packet_type = packet_type;
}
public Rx(short packet_type) {
this.packet_type = packet_type;
}
public static void main(String args[]) throws Exception{
//Receiving a packet from the transmitter
byte[] data_received = new byte[48];
byte[] ciphertext=new byte[351];
byte[] payload=new byte[360];
byte[] payload_received_packet=new byte[40];
int index=0,no_of_packets=0;
DatagramPacket packet_received = new DatagramPacket(data_received,data_received.length);
DatagramSocket socket = new DatagramSocket(PORT);
while(true) {
socket.receive(packet_received);
InetAddress inetAddress = packet_received.getAddress();
PORT = packet_received.getPort();
byte[] data_retrieved = packet_received.getData();
short packet_type_received,packet_length_received;
packet_type_received=(short)(data_retrieved[0]&(0xFF));
packet_type_received=(short)((packet_type_received<<8)+(data_retrieved[1]&(0xFF)));
packet_length_received=(short)(data_retrieved[4]&(0xFF));
packet_length_received=(short)((packet_length_received<<8)+(data_retrieved[5]&(0xFF)));
if(packet_type_received==(short)0x00) {// Calling Handshake() function if packet type is 0
HandShake(data_retrieved,inetAddress);
}
else if((packet_type_received==(short)0x02)||(packet_type_received==(short)0x03)){
// Calling DataTransmission() function if packet type is 2 or 3
payload_received_packet=DataTransmission(data_retrieved,inetAddress);
no_of_packets++;
for(int i=0,j=index;i<packet_length_received;i++,j++){
ciphertext[j]=payload_received_packet[i];
}
if(packet_type_received==(short)0x03)
break;
index=index+40;
}
}
RC4 rc4 = new RC4(nonce);
// Decrypting the DATA
System.out.println("\nDecrypting the DATA received...");
payload=rc4.decrypt(ciphertext);
System.out.println("------------------------------------------------------------DECRYPTED DATA------------------------------------------------");
displayPacket(payload);
System.out.println("--------------------------------------------------------------------------------------------------------------------------");
}
public static void HandShake(byte[] data_retrieved, InetAddress inetAddress) throws Exception {
System.out.println("\n\n-------------INITIAL HANDSHAKE--------------");
System.out.println("\nReceiving INIT from transmitter...");
// Receiving INIT packet
byte[] INIT_received = new byte[6];
for(int i=0;i<6;i++){
INIT_received[i]=data_retrieved[i];
}
Rx INIT_obj=new Rx((short)0x00);
// Display INIT contents
System.out.println("---------------INIT CONTENTS--------------");
displayPacket(INIT_received);
// Converting INIT contents to short
short[] INIT_received_short = new short[3];
INIT_received_short=INIT_obj.convertByteShort(INIT_received);
INIT_obj.sequence_no=INIT_received_short[1];
// Performing integrity check
INIT_obj.integrity_check=INIT_obj.integrityCheckCalculation(INIT_received_short);
if((INIT_obj.integrity_check==0)&&(INIT_obj.packet_type==0)){
// Generating random bytes for nonce
Random random = new Random();
random.nextBytes(nonce);
// Defining IACK packet
byte[] IACK_packet = new byte[14];
short[] IACK_packet_short=new short[7];
short INIT_sequence_no_echo_short = INIT_obj.sequence_no;
Rx IACK_obj=new Rx((short)0,INIT_sequence_no_echo_short,(short)0x01);
short[] nonce_short = new short[4];
nonce_short=IACK_obj.convertByteShort(nonce);
IACK_packet_short[0]=IACK_obj.packet_type;
IACK_packet_short[1]=INIT_sequence_no_echo_short;
for (int i = 0, j = 2; i<nonce_short.length; i++, j++) {
IACK_packet_short[j] = nonce[i];
}
IACK_packet_short[6]=IACK_obj.integrity_check;
initial_sequence_no=INIT_sequence_no_echo_short;
current_sequence_no=initial_sequence_no;
// Performing integrity check
IACK_obj.integrity_check = IACK_obj.integrityCheckCalculation(IACK_packet_short);
IACK_packet_short[6]=IACK_obj.integrity_check;
// Converting IACK short to Byte
IACK_packet=IACK_obj.convertShortByte(IACK_packet_short);
// Sending IACK to transmitter
DatagramPacket IACK = new DatagramPacket(IACK_packet,IACK_packet.length, inetAddress, PORT);
System.out.println("Sending IACK...");
DatagramSocket receiverSocket = new DatagramSocket();
receiverSocket.send(IACK);
}
}
public static byte[] DataTransmission(byte[] DATA_received, InetAddress inetAddress) throws Exception {
// Declarations
int count = 0;
byte[] payload=new byte[40];
// Retrieving packet type
short packet_type;
packet_type=(short)(DATA_received[0]&(0xFF));
packet_type=(short)((packet_type<<8)+(DATA_received[1]&(0xFF)));
Rx DATA_obj=new Rx(packet_type);
System.out.printf("\nReceiving DATA packet %d from the transmitter...\n",current_sequence_no-initial_sequence_no+1);
// Printing DATA contents
System.out.println("-------------------------------------------------------DATA packet contents--------------------------------------------");
displayPacket(DATA_received);
// Converting DATA contents to short
short[] DATA_received_short = new short[DATA_received.length/2];
DATA_received_short=DATA_obj.convertByteShort(DATA_received);
DATA_obj.sequence_no=DATA_received_short[1];
// Performing integrity check
DATA_obj.integrity_check=DATA_obj.integrityCheckCalculation(DATA_received_short);
// Retrieving payload from DATA to return to main
for(int i=0,j=6;i<DATA_received_short[2];i++,j++){
payload[i]=DATA_received[j];
}
// Test condition
boolean test=false;
if((DATA_obj.integrity_check==0)&&((DATA_obj.packet_type==2)||(DATA_obj.packet_type==3))&&(DATA_obj.sequence_no==current_sequence_no))
test=true;
else
test=false;
if(test){
// Defining DACK packet
byte[] DACK_packet = new byte[6];
short[] DACK_packet_short=new short[DACK_packet.length/2];
short acknowledgement_no = DATA_obj.sequence_no;
Rx DACK_obj=new Rx((short)0,acknowledgement_no,(short)0x04);
DACK_packet_short[0]=DACK_obj.packet_type;
DACK_packet_short[1]=DACK_obj.sequence_no;
DACK_packet_short[2]=DACK_obj.integrity_check;
// Performing integrity check
DACK_obj.integrity_check = DACK_obj.integrityCheckCalculation(DACK_packet_short);
DACK_packet_short[2]=DACK_obj.integrity_check;
// Converting DACK short to Byte
DACK_packet=DACK_obj.convertShortByte(DACK_packet_short);
// Sending DACK to transmitter
DatagramPacket DACK = new DatagramPacket(DACK_packet,DACK_packet.length, inetAddress, PORT);
System.out.println("Sending DACK...");
DatagramSocket receiverSocket = new DatagramSocket();
receiverSocket.send(DACK);
current_sequence_no++;
}
return payload;
}
// Function to perform integrity check calculation
public short integrityCheckCalculation(short[] packet){
integrity_check=0;
if((this.packet_type==0x00)||(this.packet_type==0x02)||(this.packet_type==0x03)){
for(int i=0;i<packet.length;i++){
integrity_check=(short)(integrity_check^packet[i]);
}
}
else if((this.packet_type==0x01)||(this.packet_type==0x04)){
for(int i=0;i<packet.length-1;i++){
integrity_check=(short)(integrity_check^packet[i]);
}
}
return integrity_check;
}
// Function to convert byte array to short array
public short[] convertByteShort(byte[] packet){
short[] packet_short=new short[packet.length/2];
for(int i=0;i<packet_short.length;i++){
packet_short[i]=(short)(packet[i*2]&(0xFF));
packet_short[i]=(short)((packet_short[i]<<8)+(packet[i*2+1]&(0xFF)));
}
return packet_short;
}
// Function to convert short array to byte array
public byte[] convertShortByte(short[] packet_short){
byte[] packet=new byte[packet_short.length*2];
for(int i=0;i<packet_short.length;i++){
packet[i*2+1]=(byte)(packet_short[i]&0xFF);
packet[i*2]=(byte)((packet_short[i]&0xFF00)>>8);
}
return packet;
}
// Function to display the contents of a byte array. It gives tab space between elements if the number
// of elements in the array is greater than 20. Otherwise it prints each element in a new line
public static void displayPacket(byte[] packet) {
if(packet.length > 20){
int count=0;
for (int i=0; i < packet.length; i++){
if (count % 15== 0)
System.out.println();
count++;
System.out.printf("%d\t", packet[i]);
}
System.out.println();
}
else{
for (int i = 0; i < packet.length; i++) {
System.out.printf("Byte %d. = %d\n", i, packet[i]);
}
}
}
}
| anushagj/UDP-Transmission | Rx.java |
1,076 | import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class ha {
public static void main(String[] args) {
String originalString = "6522a45f1a028e336b7c969a3cd4f419c95f6c219c18cae123ce8abf1f67ec32";
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] encodedhash = digest.digest(originalString.getBytes(StandardCharsets.UTF_8));
String sha256hash = bytesToHex(encodedhash);
System.out.println(sha256hash);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
private static String bytesToHex(byte[] hash) {
StringBuilder hexString = new StringBuilder(2 * hash.length);
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
}
| yui19278/calc-ha | ha.java |
1,077 | /*************************************************************************
* Compilation: javac In.java
* Execution: java In (basic test --- see source for required files)
*
* Reads in data of various types from standard input, files, and URLs.
*
*************************************************************************/
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.HttpURLConnection;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Locale;
import java.util.Scanner;
import java.util.regex.Pattern;
/**
* <i>Input</i>. This class provides methods for reading strings
* and numbers from standard input, file input, URLs, and sockets.
* <p>
* The Locale used is: language = English, country = US. This is consistent
* with the formatting conventions with Java floating-point literals,
* command-line arguments (via {@link Double#parseDouble(String)})
* and standard output.
* <p>
* For additional documentation, see
* <a href="http://introcs.cs.princeton.edu/31datatype">Section 3.1</a> of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i>
* by Robert Sedgewick and Kevin Wayne.
* <p>
* Like {@link Scanner}, reading a token also consumes preceding Java
* whitespace, reading a full line consumes
* the following end-of-line delimeter, while reading a character consumes
* nothing extra.
* <p>
* Whitespace is defined in {@link Character#isWhitespace(char)}. Newlines
* consist of \n, \r, \r\n, and Unicode hex code points 0x2028, 0x2029, 0x0085;
* see <tt><a href="http://www.docjar.com/html/api/java/util/Scanner.java.html">
* Scanner.java</a></tt> (NB: Java 6u23 and earlier uses only \r, \r, \r\n).
*
* @author David Pritchard
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class In {
private Scanner scanner;
/*** begin: section (1 of 2) of code duplicated from In to StdIn */
// assume Unicode UTF-8 encoding
private static final String CHARSET_NAME = "UTF-8";
// assume language = English, country = US for consistency with System.out.
private static final Locale LOCALE = Locale.US;
// the default token separator; we maintain the invariant that this value
// is held by the scanner's delimiter between calls
private static final Pattern WHITESPACE_PATTERN
= Pattern.compile("\\p{javaWhitespace}+");
// makes whitespace characters significant
private static final Pattern EMPTY_PATTERN
= Pattern.compile("");
// used to read the entire input. source:
// http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html
private static final Pattern EVERYTHING_PATTERN
= Pattern.compile("\\A");
/*** end: section (1 of 2) of code duplicated from In to StdIn */
/**
* Create an input stream from standard input.
*/
public In() {
scanner = new Scanner(new BufferedInputStream(System.in), CHARSET_NAME);
scanner.useLocale(LOCALE);
}
/**
* Create an input stream from a socket.
*/
public In(java.net.Socket socket) {
try {
InputStream is = socket.getInputStream();
scanner = new Scanner(new BufferedInputStream(is), CHARSET_NAME);
scanner.useLocale(LOCALE);
}
catch (IOException ioe) {
System.err.println("Could not open " + socket);
}
}
/**
* Create an input stream from a URL.
*/
public In(URL url) {
try {
URLConnection site = url.openConnection();
InputStream is = site.getInputStream();
scanner = new Scanner(new BufferedInputStream(is), CHARSET_NAME);
scanner.useLocale(LOCALE);
}
catch (IOException ioe) {
System.err.println("Could not open " + url);
}
}
/**
* Create an input stream from a file.
*/
public In(File file) {
try {
scanner = new Scanner(file, CHARSET_NAME);
scanner.useLocale(LOCALE);
}
catch (IOException ioe) {
System.err.println("Could not open " + file);
}
}
/**
* Create an input stream from a filename or web page name.
*/
public In(String s) {
try {
// first try to read file from local file system
File file = new File(s);
if (file.exists()) {
scanner = new Scanner(file, CHARSET_NAME);
scanner.useLocale(LOCALE);
return;
}
// next try for files included in jar
URL url = getClass().getResource(s);
// or URL from web
if (url == null) { url = new URL(s); }
URLConnection site = url.openConnection();
// in order to set User-Agent, replace above line with these two
// HttpURLConnection site = (HttpURLConnection) url.openConnection();
// site.addRequestProperty("User-Agent", "Mozilla/4.76");
InputStream is = site.getInputStream();
scanner = new Scanner(new BufferedInputStream(is), CHARSET_NAME);
scanner.useLocale(LOCALE);
}
catch (IOException ioe) {
System.err.println("Could not open " + s);
}
}
/**
* Create an input stream from a given Scanner source; use with
* <tt>new Scanner(String)</tt> to read from a string.
* <p>
* Note that this does not create a defensive copy, so the
* scanner will be mutated as you read on.
*/
public In(Scanner scanner) {
this.scanner = scanner;
}
/**
* Does the input stream exist?
*/
public boolean exists() {
return scanner != null;
}
/*** begin: section (2 of 2) of code duplicated from In to StdIn,
* with all methods changed from "public" to "public static" ***/
/**
* Is the input empty (except possibly for whitespace)? Use this
* to know whether the next call to {@link #readString()},
* {@link #readDouble()}, etc will succeed.
*/
public boolean isEmpty() {
return !scanner.hasNext();
}
/**
* Does the input have a next line? Use this to know whether the
* next call to {@link #readLine()} will succeed. <p> Functionally
* equivalent to {@link #hasNextChar()}.
*/
public boolean hasNextLine() {
return scanner.hasNextLine();
}
/**
* Is the input empty (including whitespace)? Use this to know
* whether the next call to {@link #readChar()} will succeed. <p> Functionally
* equivalent to {@link #hasNextLine()}.
*/
public boolean hasNextChar() {
scanner.useDelimiter(EMPTY_PATTERN);
boolean result = scanner.hasNext();
scanner.useDelimiter(WHITESPACE_PATTERN);
return result;
}
/**
* Read and return the next line.
*/
public String readLine() {
String line;
try { line = scanner.nextLine(); }
catch (Exception e) { line = null; }
return line;
}
/**
* Read and return the next character.
*/
public char readChar() {
scanner.useDelimiter(EMPTY_PATTERN);
String ch = scanner.next();
assert (ch.length() == 1) : "Internal (Std)In.readChar() error!"
+ " Please contact the authors.";
scanner.useDelimiter(WHITESPACE_PATTERN);
return ch.charAt(0);
}
/**
* Read and return the remainder of the input as a string.
*/
public String readAll() {
if (!scanner.hasNextLine())
return "";
String result = scanner.useDelimiter(EVERYTHING_PATTERN).next();
// not that important to reset delimeter, since now scanner is empty
scanner.useDelimiter(WHITESPACE_PATTERN); // but let's do it anyway
return result;
}
/**
* Read and return the next string.
*/
public String readString() {
return scanner.next();
}
/**
* Read and return the next int.
*/
public int readInt() {
return scanner.nextInt();
}
/**
* Read and return the next double.
*/
public double readDouble() {
return scanner.nextDouble();
}
/**
* Read and return the next float.
*/
public float readFloat() {
return scanner.nextFloat();
}
/**
* Read and return the next long.
*/
public long readLong() {
return scanner.nextLong();
}
/**
* Read and return the next short.
*/
public short readShort() {
return scanner.nextShort();
}
/**
* Read and return the next byte.
*/
public byte readByte() {
return scanner.nextByte();
}
/**
* Read and return the next boolean, allowing case-insensitive
* "true" or "1" for true, and "false" or "0" for false.
*/
public boolean readBoolean() {
String s = readString();
if (s.equalsIgnoreCase("true")) return true;
if (s.equalsIgnoreCase("false")) return false;
if (s.equals("1")) return true;
if (s.equals("0")) return false;
throw new InputMismatchException();
}
/**
* Read all strings until the end of input is reached, and return them.
*/
public String[] readAllStrings() {
// we could use readAll.trim().split(), but that's not consistent
// since trim() uses characters 0x00..0x20 as whitespace
String[] tokens = WHITESPACE_PATTERN.split(readAll());
if (tokens.length == 0 || tokens[0].length() > 0)
return tokens;
String[] decapitokens = new String[tokens.length-1];
for (int i = 0; i < tokens.length-1; i++)
decapitokens[i] = tokens[i+1];
return decapitokens;
}
/**
* Reads all remaining lines from input stream and returns them as an array of strings.
* @return all remaining lines on input stream, as an array of strings
*/
public String[] readAllLines() {
ArrayList<String> lines = new ArrayList<String>();
while (hasNextLine()) {
lines.add(readLine());
}
return lines.toArray(new String[0]);
}
/**
* Read all ints until the end of input is reached, and return them.
*/
public int[] readAllInts() {
String[] fields = readAllStrings();
int[] vals = new int[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Integer.parseInt(fields[i]);
return vals;
}
/**
* Read all doubles until the end of input is reached, and return them.
*/
public double[] readAllDoubles() {
String[] fields = readAllStrings();
double[] vals = new double[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Double.parseDouble(fields[i]);
return vals;
}
/*** end: section (2 of 2) of code duplicated from In to StdIn */
/**
* Close the input stream.
*/
public void close() {
scanner.close();
}
/**
* Reads all ints from a file
* @deprecated Clearer to use
* <tt>new In(filename)</tt>.{@link #readAllInts()}
*/
public static int[] readInts(String filename) {
return new In(filename).readAllInts();
}
/**
* Reads all doubles from a file
* @deprecated Clearer to use
* <tt>new In(filename)</tt>.{@link #readAllDoubles()}
*/
public static double[] readDoubles(String filename) {
return new In(filename).readAllDoubles();
}
/**
* Reads all strings from a file
* @deprecated Clearer to use
* <tt>new In(filename)</tt>.{@link #readAllStrings()}
*/
public static String[] readStrings(String filename) {
return new In(filename).readAllStrings();
}
/**
* Reads all ints from stdin
* @deprecated Clearer to use {@link StdIn#readAllInts()}
*/
public static int[] readInts() {
return new In().readAllInts();
}
/**
* Reads all doubles from stdin
* @deprecated Clearer to use {@link StdIn#readAllDoubles()}
*/
public static double[] readDoubles() {
return new In().readAllDoubles();
}
/**
* Reads all strings from stdin
* @deprecated Clearer to use {@link StdIn#readAllStrings()}
*/
public static String[] readStrings() {
return new In().readAllStrings();
}
/**
* Test client.
*/
public static void main(String[] args) {
In in;
String urlName = "http://introcs.cs.princeton.edu/stdlib/InTest.txt";
// read from a URL
System.out.println("readAll() from URL " + urlName);
System.out.println("---------------------------------------------------------------------------");
try {
in = new In(urlName);
System.out.println(in.readAll());
}
catch (Exception e) { System.out.println(e); }
System.out.println();
// read one line at a time from URL
System.out.println("readLine() from URL " + urlName);
System.out.println("---------------------------------------------------------------------------");
try {
in = new In(urlName);
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
}
catch (Exception e) { System.out.println(e); }
System.out.println();
// read one string at a time from URL
System.out.println("readString() from URL " + urlName);
System.out.println("---------------------------------------------------------------------------");
try {
in = new In(urlName);
while (!in.isEmpty()) {
String s = in.readString();
System.out.println(s);
}
}
catch (Exception e) { System.out.println(e); }
System.out.println();
// read one line at a time from file in current directory
System.out.println("readLine() from current directory");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("./InTest.txt");
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
}
catch (Exception e) { System.out.println(e); }
System.out.println();
// read one line at a time from file using relative path
System.out.println("readLine() from relative path");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("../stdlib/InTest.txt");
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
}
catch (Exception e) { System.out.println(e); }
System.out.println();
// read one char at a time
System.out.println("readChar() from file");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("InTest.txt");
while (!in.isEmpty()) {
char c = in.readChar();
System.out.print(c);
}
}
catch (Exception e) { System.out.println(e); }
System.out.println();
System.out.println();
// read one line at a time from absolute OS X / Linux path
System.out.println("readLine() from absolute OS X / Linux path");
System.out.println("---------------------------------------------------------------------------");
in = new In("/n/fs/introcs/www/java/stdlib/InTest.txt");
try {
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
}
catch (Exception e) { System.out.println(e); }
System.out.println();
// read one line at a time from absolute Windows path
System.out.println("readLine() from absolute Windows path");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("G:\\www\\introcs\\stdlib\\InTest.txt");
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
System.out.println();
}
catch (Exception e) { System.out.println(e); }
System.out.println();
}
}
| dsouzarc/nbody | NBody/In.java |
1,082 | /*
* Copyright (c) 2016 SNLAB and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.mapleapp.impl;
import java.util.Map;
import org.opendaylight.maple.core.increment.app.MapleAppBase;
import org.opendaylight.maple.core.increment.app.MapleUtil;
import org.opendaylight.maple.core.increment.packet.Ethernet;
import org.opendaylight.maple.core.increment.packet.IPv4;
import org.opendaylight.maple.core.increment.tracetree.MaplePacket;
import org.opendaylight.maple.core.increment.tracetree.Port;
import org.opendaylight.maple.core.increment.tracetree.Route;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
public class M2 extends MapleAppBase {
private static final String TOPO_URL = "/root/network-topology/topology";
private static final String HOST_TABLE_URL = "/root/host-table";
private static final String H1 = "10.0.0.1";
private static final int H1_IP = IPv4.toIPv4Address(H1);
private static final String H2 = "10.0.0.2";
private static final int H2_IP = IPv4.toIPv4Address(H2);
private static final int HTTP_PORT = 80;
// TODO: Better explain the path construct:
// TODO: Use s1, s2, ... in the construction if possible
private static final String[] H12_HIGH_PATH = { "openflow:1:3", "openflow:2:2", "openflow:4:1" };
private static final String[] H12_LOW_PATH = { "openflow:1:4", "openflow:3:2", "openflow:4:1" };
private static final String[] H21_HIGH_PATH = { "openflow:4:4", "openflow:2:1", "openflow:1:1" };
private static final String[] H21_LOW_PATH = { "openflow:4:5", "openflow:3:1", "openflow:1:1" };
public void staticRoute(MaplePacket pkt) {
// H1 (client) -> H2 (server)
if ( pkt.IPv4SrcIs(H1_IP) && pkt.IPv4DstIs(H2_IP) ) {
String[] path = null;
if ( ! pkt.TCPDstPortIs(HTTP_PORT) ) { // All non HTTP IP, e.g., UDP, PING, SSH
path = H12_LOW_PATH;
} else { // Only HTTP traffic
path = H12_HIGH_PATH;
}
// ***TODO***: Need to agree on either Route or Path, not both
pkt.setRoute(path);
// Reverse: H2 -> H1
} else if ( pkt.IPv4SrcIs(H2_IP) && pkt.IPv4DstIs(H1_IP) ) {
String[] path = null;
if ( ! pkt.TCPSrcPortIs(HTTP_PORT) ) {
path = H21_LOW_PATH;
} else {
path = H21_HIGH_PATH;
}
pkt.setRoute(path);
}
} // end of staticRoute
@Override
public void onPacket(MaplePacket pkt) {
int ethType = pkt.ethType();
// For IPv4 traffic only
if ( ethType == Ethernet.TYPE_IPv4 ) {
staticRoute( pkt );
if (pkt.route() == null) {
// Handle only HTTP traffic
if (pkt.TCPDstPortIs(HTTP_PORT) || pkt.TCPSrcPortIs(HTTP_PORT)) {
int srcIP = pkt.IPv4Src();
int dstIP = pkt.IPv4Dst();
Topology topo = (Topology) readData(TOPO_URL);
Map<Integer, Port> hostTable = (Map<Integer, Port>) readData(HOST_TABLE_URL);
Port srcPort = hostTable.get(srcIP);
Port dstPort = hostTable.get(dstIP);
pkt.setRoute(MapleUtil.shortestPath(topo.getLink(), srcPort, dstPort));
} else {
pkt.setRoute(Route.DROP);
}
}
} // end of IPv4 packets
else { // Other type of traffic handled by another Maple App
passToNext(pkt);
}
} // end of onPacket
}
| snlab/fastmaple16 | M2.java |
1,083 | // 89. Gray Code
// An n-bit gray code sequence is a sequence of 2n integers where:
//
// Every integer is in the inclusive range [0, 2n - 1],
// The first integer is 0,
// An integer appears no more than once in the sequence,
// The binary representation of every pair of adjacent integers differs by exactly one bit, and
// The binary representation of the first and last integers differs by exactly one bit.
// Given an integer n, return any valid n-bit gray code sequence.
//
//
//
// Example 1:
//
// Input: n = 2
// Output: [0,1,3,2]
// Explanation:
// The binary representation of [0,1,3,2] is [00,01,11,10].
// - 00 and 01 differ by one bit
// - 01 and 11 differ by one bit
// - 11 and 10 differ by one bit
// - 10 and 00 differ by one bit
// [0,2,3,1] is also a valid gray code sequence, whose binary representation is [00,10,11,01].
// - 00 and 10 differ by one bit
// - 10 and 11 differ by one bit
// - 11 and 01 differ by one bit
// - 01 and 00 differ by one bit
// Example 2:
//
// Input: n = 1
// Output: [0,1]
//
//
// Constraints:
//
// 1 <= n <= 16
//
// Runtime: 5 ms, faster than 73.75% of Java online submissions for Gray Code.
// Memory Usage: 45.8 MB, less than 90.96% of Java online submissions for Gray Code.
class Solution {
public List<Integer> grayCode(int n) {
List<Integer> inputList = new ArrayList<>();
inputList.add(0);
inputList.add(1);
if (n == 1) return inputList;
int counter = 1;
while (counter < n) {
int size = inputList.size();
for (int i = 1; i <= size; i++) {
int num = 1 << counter;
num = num + inputList.get(size - i);
inputList.add(num);
}
counter++;
}
return inputList;
}
} | ishuen/leetcode | 89.java |
1,085 | // 21. Merge Two Sorted Lists
// You are given the heads of two sorted linked lists list1 and list2.
//
// Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.
//
// Return the head of the merged linked list.
//
//
//
// Example 1:
//
//
// Input: list1 = [1,2,4], list2 = [1,3,4]
// Output: [1,1,2,3,4,4]
// Example 2:
//
// Input: list1 = [], list2 = []
// Output: []
// Example 3:
//
// Input: list1 = [], list2 = [0]
// Output: [0]
//
//
// Constraints:
//
// The number of nodes in both lists is in the range [0, 50].
// -100 <= Node.val <= 100
// Both list1 and list2 are sorted in non-decreasing order.
//
// Runtime: 0 ms, faster than 100.00% of Java online submissions for Merge Two Sorted Lists.
// Memory Usage: 43.1 MB, less than 26.48% of Java online submissions for Merge Two Sorted Lists.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode dummyHead = new ListNode();
ListNode cur1 = list1;
ListNode cur2 = list2;
ListNode cur = dummyHead;
while(cur1 != null && cur2 != null) {
if (cur1.val < cur2.val) {
cur.next = cur1;
cur = cur.next;
cur1 = cur1.next;
} else {
cur.next = cur2;
cur = cur.next;
cur2 = cur2.next;
}
}
if (cur1 != null) {
cur.next = cur1;
}
if (cur2 != null) {
cur.next = cur2;
}
return dummyHead.next;
}
} | ishuen/leetcode | 21.java |
1,087 | // 71. Simplify Path
// Given a string path, which is an absolute path (starting with a slash '/') to a file or directory in a Unix-style file system, convert it to the simplified canonical path.
//
// In a Unix-style file system, a period '.' refers to the current directory, a double period '..' refers to the directory up a level, and any multiple consecutive slashes (i.e. '//') are treated as a single slash '/'. For this problem, any other format of periods such as '...' are treated as file/directory names.
//
// The canonical path should have the following format:
//
// The path starts with a single slash '/'.
// Any two directories are separated by a single slash '/'.
// The path does not end with a trailing '/'.
// The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period '.' or double period '..')
// Return the simplified canonical path.
//
//
//
// Example 1:
//
// Input: path = "/home/"
// Output: "/home"
// Explanation: Note that there is no trailing slash after the last directory name.
// Example 2:
//
// Input: path = "/../"
// Output: "/"
// Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
// Example 3:
//
// Input: path = "/home//foo/"
// Output: "/home/foo"
// Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.
// Example 4:
//
// Input: path = "/a/./b/../../c/"
// Output: "/c"
//
//
// Constraints:
//
// 1 <= path.length <= 3000
// path consists of English letters, digits, period '.', slash '/' or '_'.
// path is a valid absolute Unix path.
//
// Runtime: 4 ms, faster than 80.10% of Java online submissions for Simplify Path.
// Memory Usage: 39.5 MB, less than 29.66% of Java online submissions for Simplify Path.
class Solution {
public String simplifyPath(String path) {
String[] folders = path.split("/");
StringBuilder pathSb = new StringBuilder();
for (String folder: folders) {
if (folder.equals("..") && pathSb.length() > 0) {
int slashIndex = 0;
for (int i = pathSb.length() - 1; i >= 0; i--) {
if (pathSb.charAt(i) == '/') {
slashIndex = i;
break;
}
}
pathSb.delete(slashIndex, pathSb.length());
} else if (!folder.equals("") && !folder.equals(".") && !folder.equals("..")) {
pathSb.append("/" + folder);
}
}
return pathSb.length() > 0 ? pathSb.toString() : "/";
}
} | ishuen/leetcode | 71.java |
1,088 | // 48. Rotate Image
//
// You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
//
// You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
//
//
//
// Example 1:
//
//
// Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
// Output: [[7,4,1],[8,5,2],[9,6,3]]
// Example 2:
//
//
// Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
// Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
//
//
// Constraints:
//
// n == matrix.length == matrix[i].length
// 1 <= n <= 20
// -1000 <= matrix[i][j] <= 1000
//
// Runtime 0 ms Beats 100.00% of users with Java
// Memory 42.06 MB Beats 23.49% of users with Java
class Solution {
public void rotate(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = i + 1; j < matrix[0].length; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
int len = matrix[0].length;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < len / 2; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[i][len - 1 - j];
matrix[i][len - 1 - j] = temp;
}
}
}
} | ishuen/leetcode | 48.java |
1,089 | import java.util.Random;
public class js extends wg {
protected js(int i, int j) {
super(i, j);
float f = 0.2F;
a(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, f * 2.0F, 0.5F + f);
b(true);
}
public void a(ry world, int i, int j, int k, Random random) {
if (((Boolean)mod_noBiomesX.NoBetaBlockActions.get()).booleanValue()) {
super.a(world, i, j, k, random);
return;
}
if (random.nextInt(25) == 0) {
byte byte0 = 4;
int l = 5;
for (int i1 = i - byte0; i1 <= i + byte0; i1++) {
for (int k1 = k - byte0; k1 <= k + byte0; k1++) {
for (int i2 = j - 1; i2 <= j + 1; i2++) {
if (world.a(i1, i2, k1) == this.bM && --l <= 0)
return;
}
}
}
int j1 = i + random.nextInt(3) - 1;
int l1 = j + random.nextInt(2) - random.nextInt(2);
int j2 = k + random.nextInt(3) - 1;
for (int k2 = 0; k2 < 4; k2++) {
if (world.h(j1, l1, j2) && e(world, j1, l1, j2)) {
i = j1;
j = l1;
k = j2;
}
j1 = i + random.nextInt(3) - 1;
l1 = j + random.nextInt(2) - random.nextInt(2);
j2 = k + random.nextInt(3) - 1;
}
if (world.h(j1, l1, j2) && e(world, j1, l1, j2))
world.g(j1, l1, j2, this.bM);
}
}
protected boolean d(int i) {
return yy.m[i];
}
public boolean e(ry world, int i, int j, int k) {
boolean lightCheck = (world.m(i, j, k) < 13);
if (((Boolean)mod_noBiomesX.NoBetaBlockActions.get()).booleanValue())
lightCheck = (world.n(i, j, k) < 13);
if (j < 0 || j >= world.c)
return false;
int l = world.a(i, j - 1, k);
return (l == yy.by.bM || (lightCheck && d(l)));
}
public boolean c(ry world, int i, int j, int k, Random random) {
int l = world.d(i, j, k);
world.d(i, j, k, 0);
acp worldgenbigmushroom = null;
if (this.bM == yy.af.bM) {
worldgenbigmushroom = new acp(0);
} else if (this.bM == yy.ag.bM) {
worldgenbigmushroom = new acp(1);
}
if (worldgenbigmushroom == null || !worldgenbigmushroom.a(world, random, i, j, k)) {
world.b(i, j, k, this.bM, l);
return false;
}
return true;
}
}
| JohnCartoonist/The-Nostalgia-Project-src | js.java |
1,090 | import java.util.Random;
public class hm extends fx {
public static final float[][] a = new float[][] {
{ 1.0F, 1.0F, 1.0F }, { 0.95F, 0.7F, 0.2F }, { 0.9F, 0.5F, 0.85F }, { 0.6F, 0.7F, 0.95F }, { 0.9F, 0.9F, 0.2F }, { 0.5F, 0.8F, 0.1F }, { 0.95F, 0.7F, 0.8F }, { 0.3F, 0.3F, 0.3F }, { 0.6F, 0.6F, 0.6F }, { 0.3F, 0.6F, 0.7F },
{ 0.7F, 0.4F, 0.9F }, { 0.2F, 0.4F, 0.8F }, { 0.5F, 0.4F, 0.3F }, { 0.4F, 0.5F, 0.2F }, { 0.8F, 0.3F, 0.3F }, { 0.1F, 0.1F, 0.1F } };
public hm(ry world) {
super(world);
this.aA = "/mob/sheep.png";
a(0.9F, 1.3F);
}
public int f_() {
if (((Boolean)mod_noBiomesX.NoBetaMobActions.get()).booleanValue())
return 10;
return 8;
}
protected void b() {
super.b();
this.ag.a(16, new Byte((byte)0));
}
protected void a(boolean flag, int i) {
if (!v_() && !((Boolean)mod_noBiomesX.SheepShearing.get()).booleanValue())
a(new dk(yy.ab.bM, 1, l()), 0.0F);
}
protected int k() {
return yy.ab.bM;
}
public boolean c(vi entityplayer) {
dk itemstack = entityplayer.by.a();
if (itemstack != null && itemstack.c == acy.bd.bM && !v_()) {
if (!this.o.I) {
b(true);
int i = 2 + this.Y.nextInt(3);
for (int j = 0; j < i; j++) {
ih entityitem = a(new dk(yy.ab.bM, 1, l()), 1.0F);
entityitem.w += (this.Y.nextFloat() * 0.05F);
entityitem.v += ((this.Y.nextFloat() - this.Y.nextFloat()) * 0.1F);
entityitem.x += ((this.Y.nextFloat() - this.Y.nextFloat()) * 0.1F);
}
}
itemstack.a(1, entityplayer);
}
return super.c(entityplayer);
}
public boolean a(pm damagesource, int i) {
if (damagesource.a() instanceof vi && ((Boolean)mod_noBiomesX.SheepShearing.get()).booleanValue() && !v_())
if (!this.o.I) {
b(true);
int amount = 1 + this.Y.nextInt(3);
for (int j = 0; j < amount; j++) {
ih entityitem = a(new dk(yy.ab.bM, 1, l()), 1.0F);
entityitem.w += (this.Y.nextFloat() * 0.05F);
entityitem.v += ((this.Y.nextFloat() - this.Y.nextFloat()) * 0.1F);
entityitem.x += ((this.Y.nextFloat() - this.Y.nextFloat()) * 0.1F);
}
}
return super.a(damagesource, i);
}
public void a(ik nbttagcompound) {
super.a(nbttagcompound);
nbttagcompound.a("Sheared", v_());
nbttagcompound.a("Color", (byte)l());
}
public void b(ik nbttagcompound) {
super.b(nbttagcompound);
b(nbttagcompound.m("Sheared"));
c(nbttagcompound.c("Color"));
}
protected String e() {
return "mob.sheep";
}
protected String f() {
return "mob.sheep";
}
protected String g() {
return "mob.sheep";
}
public int l() {
return this.ag.a(16) & 0xF;
}
public void c(int i) {
byte byte0 = this.ag.a(16);
this.ag.b(16, Byte.valueOf((byte)(byte0 & 0xF0 | i & 0xF)));
}
public boolean v_() {
return ((this.ag.a(16) & 0x10) != 0);
}
public void b(boolean flag) {
byte byte0 = this.ag.a(16);
if (flag) {
this.ag.b(16, Byte.valueOf((byte)(byte0 | 0x10)));
} else {
this.ag.b(16, Byte.valueOf((byte)(byte0 & 0xFFFFFFEF)));
}
}
public static int a(Random random) {
if (((Boolean)mod_noBiomesX.NoBetaMobActions.get()).booleanValue())
return 0;
int i = random.nextInt(100);
if (i < 5)
return 15;
if (i < 10)
return 7;
if (i < 15)
return 8;
if (i < 18)
return 12;
return (random.nextInt(500) != 0) ? 0 : 6;
}
protected fx a(fx entityanimal) {
hm entitysheep = (hm)entityanimal;
hm entitysheep1 = new hm(this.o);
if (this.Y.nextBoolean()) {
entitysheep1.c(l());
} else {
entitysheep1.c(entitysheep.l());
}
return entitysheep1;
}
}
| JohnCartoonist/The-Nostalgia-Project-src | hm.java |
1,091 | import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import net.minecraft.client.Minecraft;
import org.lwjgl.opengl.GL11;
public class qd extends ht {
private static iw d = new iw();
private List e;
private Random f;
private Minecraft g;
public String a;
private int h;
private String j;
private int k;
private boolean l;
public float b;
float c;
public qd(Minecraft minecraft) {
this.e = new ArrayList();
this.f = new Random();
this.a = null;
this.h = 0;
this.j = "";
this.k = 0;
this.l = false;
this.c = 1.0F;
this.g = minecraft;
}
public void a(float f, boolean flag, int i, int j) {
ef scaledresolution = new ef(this.g.A, this.g.d, this.g.e);
int k = scaledresolution.a();
int l = scaledresolution.b();
abe fontrenderer = this.g.q;
this.g.u.b();
GL11.glEnable(3042);
if (Minecraft.s()) {
a(this.g.h.b(f), k, l);
} else {
GL11.glBlendFunc(770, 771);
}
dk itemstack = this.g.h.by.e(3);
if (this.g.A.E == 0 && itemstack != null && itemstack.c == yy.ba.bM)
a(k, l);
if (!this.g.h.a(abg.k)) {
float f1 = this.g.h.cb + (this.g.h.ca - this.g.h.cb) * f;
if (f1 > 0.0F)
b(f1, k, l);
}
if (!this.g.c.i()) {
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glBindTexture(3553, this.g.p.b("/gui/gui.png"));
x inventoryplayer = this.g.h.by;
this.i = -90.0F;
b(k / 2 - 91, l - 22, 0, 0, 182, 22);
b(k / 2 - 91 - 1 + inventoryplayer.c * 20, l - 22 - 1, 0, 22, 24, 22);
GL11.glBindTexture(3553, this.g.p.b("/gui/icons.png"));
GL11.glEnable(3042);
GL11.glBlendFunc(775, 769);
b(k / 2 - 7, l / 2 - 7, 0, 0, 16, 16);
GL11.glDisable(3042);
boolean flag2 = (this.g.h.ac / 3 % 2 == 1);
if (this.g.h.ac < 10)
flag2 = false;
int i2 = this.g.h.ag();
int j3 = this.g.h.aN;
this.f.setSeed((this.h * 312871));
boolean flag4 = false;
eq foodstats = this.g.h.aO();
int i5 = foodstats.a();
int k5 = foodstats.b();
c();
if (this.g.c.a()) {
int k6 = k / 2 - 91;
int j7 = k / 2 + 91;
int l7 = this.g.h.aN();
int k8 = l - 39;
int j9 = k8 - 10;
if (((Boolean)mod_noBiomesX.XPSystem.get()).booleanValue()) {
if (l7 > 0) {
char c = 'ΒΆ';
int i9 = (int)(this.g.h.cf * (c + 1));
int l9 = l - 32 + 3;
b(k6, l9, 0, 64, c, 5);
if (i9 > 0)
b(k6, l9, 0, 69, i9, 5);
}
} else {
k8 += 7;
j9 += 7;
}
int i10 = this.g.h.p();
int j10 = -1;
if (this.g.h.a(abg.l))
j10 = this.h % 25;
for (int l10 = 0; l10 < 10; l10++) {
if (i10 > 0)
if (((Boolean)mod_noBiomesX.HungerSystem.get()).booleanValue()) {
int k11 = k6 + l10 * 8;
if (l10 * 2 + 1 < i10)
b(k11, j9, 34, 9, 9, 9);
if (l10 * 2 + 1 == i10)
b(k11, j9, 25, 9, 9, 9);
if (l10 * 2 + 1 > i10)
b(k11, j9, 16, 9, 9, 9);
} else {
int k11 = j7 - l10 * 8 - 9;
if (l10 * 2 + 1 < i10)
b(k11, k8, 34, 9, 9, 9);
if (l10 * 2 + 1 == i10)
b(k11, k8, 25, 9, 9, 9);
if (l10 * 2 + 1 > i10)
b(k11, k8, 16, 9, 9, 9);
}
int l11 = 16;
if (this.g.h.a(abg.u))
l11 += 36;
int k12 = 0;
if (flag2)
k12 = 1;
int j13 = k6 + l10 * 8;
int k13 = k8;
if (i2 <= 4)
k13 += this.f.nextInt(2);
if (l10 == j10)
k13 -= 2;
byte byte5 = 0;
if (this.g.f.z().s())
byte5 = 5;
b(j13, k13, 16 + k12 * 9, 9 * byte5, 9, 9);
if (flag2) {
if (l10 * 2 + 1 < j3)
b(j13, k13, l11 + 54, 9 * byte5, 9, 9);
if (l10 * 2 + 1 == j3)
b(j13, k13, l11 + 63, 9 * byte5, 9, 9);
}
if (l10 * 2 + 1 < i2)
b(j13, k13, l11 + 36, 9 * byte5, 9, 9);
if (l10 * 2 + 1 == i2)
b(j13, k13, l11 + 45, 9 * byte5, 9, 9);
}
if (((Boolean)mod_noBiomesX.HungerSystem.get()).booleanValue())
for (int i11 = 0; i11 < 10; i11++) {
int i12 = k8;
int l12 = 16;
byte byte4 = 0;
if (this.g.h.a(abg.s)) {
l12 += 36;
byte4 = 13;
}
if (this.g.h.aO().d() <= 0.0F && this.h % (i5 * 3 + 1) == 0)
i12 += this.f.nextInt(3) - 1;
if (flag4)
byte4 = 1;
int l13 = j7 - i11 * 8 - 9;
b(l13, i12, 16 + byte4 * 9, 27, 9, 9);
if (flag4) {
if (i11 * 2 + 1 < k5)
b(l13, i12, l12 + 54, 27, 9, 9);
if (i11 * 2 + 1 == k5)
b(l13, i12, l12 + 63, 27, 9, 9);
}
if (i11 * 2 + 1 < i5)
b(l13, i12, l12 + 36, 27, 9, 9);
if (i11 * 2 + 1 == i5)
b(l13, i12, l12 + 45, 27, 9, 9);
}
if (this.g.h.a(p.g)) {
int j11 = (int)Math.ceil((this.g.h.Z() - 2) * 10.0D / 300.0D);
int j12 = (int)Math.ceil(this.g.h.Z() * 10.0D / 300.0D) - j11;
for (int i13 = 0; i13 < j11 + j12; i13++) {
if (((Boolean)mod_noBiomesX.HungerSystem.get()).booleanValue()) {
if (i13 < j11) {
b(j7 - i13 * 8 - 9, j9, 16, 18, 9, 9);
} else {
b(j7 - i13 * 8 - 9, j9, 25, 18, 9, 9);
}
} else if (i13 < j11) {
b(k6 + i13 * 8, j9, 16, 18, 9, 9);
} else {
b(k6 + i13 * 8, j9, 25, 18, 9, 9);
}
}
}
}
GL11.glDisable(3042);
GL11.glEnable(32826);
rt.c();
for (int l6 = 0; l6 < 9; l6++) {
int k7 = k / 2 - 90 + l6 * 20 + 2;
int i8 = l - 16 - 3;
a(l6, k7, i8, f);
}
rt.a();
GL11.glDisable(32826);
}
if (this.g.h.aL() > 0) {
GL11.glDisable(2929);
GL11.glDisable(3008);
int i1 = this.g.h.aL();
float f3 = i1 / 100.0F;
if (f3 > 1.0F)
f3 = 1.0F - (i1 - 100) / 10.0F;
int j2 = (int)(220.0F * f3) << 24 | 0x101020;
a(0, 0, k, l, j2);
GL11.glEnable(3008);
GL11.glEnable(2929);
}
if (this.g.c.e() && this.g.h.cd > 0) {
boolean flag1 = false;
int j1 = flag1 ? 16777215 : 8453920;
String s = "" + this.g.h.cd;
int k3 = (k - fontrenderer.a(s)) / 2;
int l3 = l - 31 - 4;
fontrenderer.b(s, k3 + 1, l3, 0);
fontrenderer.b(s, k3 - 1, l3, 0);
fontrenderer.b(s, k3, l3 + 1, 0);
fontrenderer.b(s, k3, l3 - 1, 0);
fontrenderer.b(s, k3, l3, j1);
}
if (this.g.A.F) {
GL11.glPushMatrix();
if (Minecraft.J > 0L)
GL11.glTranslatef(0.0F, 32.0F, 0.0F);
fontrenderer.a("Minecraft 1.0.0 (" + this.g.M + ")", 2, 2, 16777215);
fontrenderer.a(this.g.m(), 2, 12, 16777215);
fontrenderer.a(this.g.n(), 2, 22, 16777215);
fontrenderer.a(this.g.p(), 2, 32, 16777215);
fontrenderer.a(this.g.o(), 2, 42, 16777215);
long l1 = Runtime.getRuntime().maxMemory();
long l2 = Runtime.getRuntime().totalMemory();
long l4 = Runtime.getRuntime().freeMemory();
long l5 = l2 - l4;
String s1 = "Used memory: " + (l5 * 100L / l1) + "% (" + (l5 / 1024L / 1024L) + "MB) of " + (l1 / 1024L / 1024L) + "MB";
b(fontrenderer, s1, k - fontrenderer.a(s1) - 2, 2, 14737632);
s1 = "Allocated memory: " + (l2 * 100L / l1) + "% (" + (l2 / 1024L / 1024L) + "MB)";
b(fontrenderer, s1, k - fontrenderer.a(s1) - 2, 12, 14737632);
b(fontrenderer, "x: " + this.g.h.s, 2, 64, 14737632);
b(fontrenderer, "y: " + this.g.h.t, 2, 72, 14737632);
b(fontrenderer, "z: " + this.g.h.u, 2, 80, 14737632);
b(fontrenderer, "f: " + (me.c((this.g.h.y * 4.0F / 360.0F) + 0.5D) & 0x3), 2, 88, 14737632);
b(fontrenderer, "Seed: " + this.g.f.t(), 2, 104, 14737632);
OldBiomeGenBase currentBiome = this.g.f.a().oldGetBiomeGenAt((int)this.g.h.s, (int)this.g.h.u);
b(fontrenderer, "Biome: " + currentBiome.biomeName, 2, 114, 14737632);
b(fontrenderer, "Armor rating: " + this.g.h.p(), 2, 124, 14737632);
GL11.glPopMatrix();
}
if (this.k > 0) {
float f2 = this.k - f;
int k1 = (int)(f2 * 256.0F / 20.0F);
if (k1 > 255)
k1 = 255;
if (k1 > 0) {
GL11.glPushMatrix();
GL11.glTranslatef((k / 2), (l - 48), 0.0F);
GL11.glEnable(3042);
GL11.glBlendFunc(770, 771);
int k2 = 16777215;
if (this.l)
k2 = Color.HSBtoRGB(f2 / 50.0F, 0.7F, 0.6F) & 0xFFFFFF;
fontrenderer.b(this.j, -fontrenderer.a(this.j) / 2, -4, k2 + (k1 << 24));
GL11.glDisable(3042);
GL11.glPopMatrix();
}
}
byte byte0 = 10;
boolean flag3 = false;
if (this.g.s instanceof gx) {
byte0 = 20;
flag3 = true;
}
GL11.glEnable(3042);
GL11.glBlendFunc(770, 771);
GL11.glDisable(3008);
GL11.glPushMatrix();
GL11.glTranslatef(0.0F, (l - 48), 0.0F);
for (int i3 = 0; i3 < this.e.size() && i3 < byte0; i3++) {
if (((ahe)this.e.get(i3)).b < 200 || flag3) {
double d = ((ahe)this.e.get(i3)).b / 200.0D;
d = 1.0D - d;
d *= 10.0D;
if (d < 0.0D)
d = 0.0D;
if (d > 1.0D)
d = 1.0D;
d *= d;
int j4 = (int)(255.0D * d);
if (flag3)
j4 = 255;
if (j4 > 0) {
byte byte1 = 2;
int i6 = -i3 * 9;
String s2 = ((ahe)this.e.get(i3)).a;
a(byte1, i6 - 1, byte1 + 320, i6 + 8, j4 / 2 << 24);
GL11.glEnable(3042);
fontrenderer.a(s2, byte1, i6, 16777215 + (j4 << 24));
}
}
}
GL11.glPopMatrix();
if (this.g.h instanceof cx && this.g.A.y.e) {
abp netclienthandler = ((cx)this.g.h).a;
List<ao> list = netclienthandler.c;
int i4 = netclienthandler.d;
int k4 = i4;
int j5 = 1;
for (; k4 > 20; k4 = (i4 + j5 - 1) / j5)
j5++;
int j6 = 300 / j5;
if (j6 > 150)
j6 = 150;
int i7 = (k - j5 * j6) / 2;
byte byte2 = 10;
a(i7 - 1, byte2 - 1, i7 + j6 * j5, byte2 + 9 * k4, -2147483648);
for (int j8 = 0; j8 < i4; j8++) {
int l8 = i7 + j8 % j5 * j6;
int k9 = byte2 + j8 / j5 * 9;
a(l8, k9, l8 + j6 - 1, k9 + 8, 553648127);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glEnable(3008);
if (j8 < list.size()) {
ao guisavinglevelstring = list.get(j8);
fontrenderer.a(guisavinglevelstring.a, l8, k9, 16777215);
this.g.p.b(this.g.p.b("/gui/icons.png"));
int k10 = 0;
byte byte3 = 0;
k10 = 0;
byte3 = 0;
if (guisavinglevelstring.b < 0) {
byte3 = 5;
} else if (guisavinglevelstring.b < 150) {
byte3 = 0;
} else if (guisavinglevelstring.b < 300) {
byte3 = 1;
} else if (guisavinglevelstring.b < 600) {
byte3 = 2;
} else if (guisavinglevelstring.b < 1000) {
byte3 = 3;
} else {
byte3 = 4;
}
this.i += 100.0F;
b(l8 + j6 - 12, k9, 0 + k10 * 10, 176 + byte3 * 8, 10, 8);
this.i -= 100.0F;
}
}
}
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glDisable(2896);
GL11.glEnable(3008);
}
private void c() {
if (ado.a == null)
return;
oo entitydragon = ado.a;
ado.a = null;
abe fontrenderer = this.g.q;
ef scaledresolution = new ef(this.g.A, this.g.d, this.g.e);
int i = scaledresolution.a();
char c = 'ΒΆ';
int j = i / 2 - c / 2;
int k = (int)(entitydragon.ax() / entitydragon.f_() * (c + 1));
byte byte0 = 12;
b(j, byte0, 0, 74, c, 5);
b(j, byte0, 0, 74, c, 5);
if (k > 0)
b(j, byte0, 0, 79, k, 5);
String s = "Boss health";
fontrenderer.a(s, i / 2 - fontrenderer.a(s) / 2, byte0 - 10, 16711935);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glBindTexture(3553, this.g.p.b("/gui/icons.png"));
}
private void a(int i, int j) {
GL11.glDisable(2929);
GL11.glDepthMask(false);
GL11.glBlendFunc(770, 771);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glDisable(3008);
GL11.glBindTexture(3553, this.g.p.b("%blur%/misc/pumpkinblur.png"));
cv tessellator = cv.a;
tessellator.b();
tessellator.a(0.0D, j, -90.0D, 0.0D, 1.0D);
tessellator.a(i, j, -90.0D, 1.0D, 1.0D);
tessellator.a(i, 0.0D, -90.0D, 1.0D, 0.0D);
tessellator.a(0.0D, 0.0D, -90.0D, 0.0D, 0.0D);
tessellator.a();
GL11.glDepthMask(true);
GL11.glEnable(2929);
GL11.glEnable(3008);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
}
private void a(float f, int i, int j) {
f = 1.0F - f;
if (f < 0.0F)
f = 0.0F;
if (f > 1.0F)
f = 1.0F;
this.c = (float)(this.c + (f - this.c) * 0.01D);
GL11.glDisable(2929);
GL11.glDepthMask(false);
GL11.glBlendFunc(0, 769);
GL11.glColor4f(this.c, this.c, this.c, 1.0F);
GL11.glBindTexture(3553, this.g.p.b("%blur%/misc/vignette.png"));
cv tessellator = cv.a;
tessellator.b();
tessellator.a(0.0D, j, -90.0D, 0.0D, 1.0D);
tessellator.a(i, j, -90.0D, 1.0D, 1.0D);
tessellator.a(i, 0.0D, -90.0D, 1.0D, 0.0D);
tessellator.a(0.0D, 0.0D, -90.0D, 0.0D, 0.0D);
tessellator.a();
GL11.glDepthMask(true);
GL11.glEnable(2929);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glBlendFunc(770, 771);
}
private void b(float f, int i, int j) {
if (f < 1.0F) {
f *= f;
f *= f;
f = f * 0.8F + 0.2F;
}
GL11.glDisable(3008);
GL11.glDisable(2929);
GL11.glDepthMask(false);
GL11.glBlendFunc(770, 771);
GL11.glColor4f(1.0F, 1.0F, 1.0F, f);
GL11.glBindTexture(3553, this.g.p.b("/terrain.png"));
float f1 = (yy.be.bL % 16) / 16.0F;
float f2 = (yy.be.bL / 16) / 16.0F;
float f3 = (yy.be.bL % 16 + 1) / 16.0F;
float f4 = (yy.be.bL / 16 + 1) / 16.0F;
cv tessellator = cv.a;
tessellator.b();
tessellator.a(0.0D, j, -90.0D, f1, f4);
tessellator.a(i, j, -90.0D, f3, f4);
tessellator.a(i, 0.0D, -90.0D, f3, f2);
tessellator.a(0.0D, 0.0D, -90.0D, f1, f2);
tessellator.a();
GL11.glDepthMask(true);
GL11.glEnable(2929);
GL11.glEnable(3008);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
}
private void a(int i, int j, int k, float f) {
dk itemstack = this.g.h.by.a[i];
if (itemstack == null)
return;
float f1 = itemstack.b - f;
if (f1 > 0.0F) {
GL11.glPushMatrix();
float f2 = 1.0F + f1 / 5.0F;
GL11.glTranslatef((j + 8), (k + 12), 0.0F);
GL11.glScalef(1.0F / f2, (f2 + 1.0F) / 2.0F, 1.0F);
GL11.glTranslatef(-(j + 8), -(k + 12), 0.0F);
}
d.a(this.g.q, this.g.p, itemstack, j, k);
if (f1 > 0.0F)
GL11.glPopMatrix();
d.b(this.g.q, this.g.p, itemstack, j, k);
}
public void a() {
if (this.k > 0)
this.k--;
this.h++;
for (int i = 0; i < this.e.size(); i++)
((ahe)this.e.get(i)).b++;
}
public void b() {
this.e.clear();
}
public void a(String s) {
for (; this.g.q.a(s) > 320; s = s.substring(i)) {
int i;
for (i = 1; i < s.length() && this.g.q.a(s.substring(0, i + 1)) <= 320; i++);
a(s.substring(0, i));
}
this.e.add(0, new ahe(s));
for (; this.e.size() > 50; this.e.remove(this.e.size() - 1));
}
public void b(String s) {
this.j = "Now playing: " + s;
this.k = 60;
this.l = true;
}
public void c(String s) {
qp stringtranslate = qp.a();
String s1 = stringtranslate.a(s);
a(s1);
}
}
| JohnCartoonist/The-Nostalgia-Project-src | qd.java |
1,092 | import java.util.Arrays;
/**
* Created by tianf on 2016/9/27.
*/
public class P1 {
public static void main(String[] args) {
int[] nums = {0, 4, 3, 0};
int targer = 3;
int[] b= twoSum(nums,targer);
for(int i=0;i<b.length;i++) {
System.out.println(b[i]);
}
}
public static int[] twoSum(int[] nums, int target) {
int[] b = new int[2];
for(int i = 0;i < nums.length;i++) {
for(int j = i +1;j < nums.length; j++) {
if(nums[i]+nums[j] == target) {
b[0] = i;
b[1] = j;
break;
}
}
}
return b;
}
}
| parkdifferent/leetcode | P1.java |
1,093 | /**
* Created by tianf on 2016/9/27.
*/
public class P7 {
public static void main(String[] args) {
long r1 =reverse1(1534236469); //2147483647
//long r2 =reverse1(-2147483648);
System.out.println(r1);
//int a= Integer.MAX_VALUE +1;
//System.out.println("a="+a);
/* int r2 =reverse1(-123);
System.out.println(r2);
int r3 =reverse1(0);
System.out.println(r3);*/
}
public static int reverse1(int x) {
if(x ==0)
return 0;
int x1 = Math.abs(x);
int y;
int sum= 0;
int k = 0;
for(int i = 0; i < 10; i++) {
if( x1 >= Math.pow(10,i) && x1 <Math.pow(10,i+1)) {
k = i;
//System.out.println(k);
break;
}
}
while(x1!=0) {
y = x1 % 10;
x1 = x1/10;
sum += y * Math.pow(10,k);
k--;
if(sum < 0 || sum + 1 < 0) {
return 0;
}
}
return x > 0 ? sum : -sum;
}
}
| parkdifferent/leetcode | P7.java |
1,094 | import java.util.Scanner;
public class j5 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number: ");
double num1 = sc.nextDouble();
System.out.println("Enter second number: ");
double num2 = sc.nextDouble();
System.out.println("Enter an operator (+, -, *, /): ");
char operator = sc.next().charAt(0);
double output;
switch (operator) {
case '+':
output = num1 + num2;
break;
case '-':
output = num1 - num2;
break;
case '*':
output = num1 * num2;
break;
case '/':
if (num2 != 0) {
output = num1 / num2;
} else {
System.out.println("Error! Division by zero is not allowed.");
return;
}
break;
default:
System.out.println("Error! Invalid operator.");
return;
}
System.out.println("The result of the operation is: " + output);
}
} | Deathbringer98/Basic-Math-Java-Software | j5.java |
1,095 | import java.net.InetAddress;
import java.net.UnknownHostException;
import java.io.IOException;
import java.util.Scanner;
class IPAddressInfo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the IP Address: ");
String ipAddress = scanner.nextLine();
try {
InetAddress inetAddress = InetAddress.getByName(ipAddress);
// Check if the IP address is reserved, public, or private
String ipType = getIPType(inetAddress);
// Determine the IP class
char ipClass = getIPClass(inetAddress);
// Calculate the default mask
String defaultMask = getDefaultMask(ipClass);
// Calculate the block, first IP, last IP, and network address for classful addressing
String block = inetAddress.getHostAddress() + "/" + (int) Math.pow(2, 32 - inetAddress.getAddress().length);
String firstIP = getFirstIP(inetAddress);
String lastIP = getLastIP(inetAddress);
String networkAddress = getNetworkAddress(inetAddress);
System.out.println("IP Address: " + inetAddress.getHostAddress());
System.out.println("Reserved/Public/Private: " + ipType);
System.out.println("IP Class: " + ipClass);
System.out.println("Default Mask: " + defaultMask);
System.out.println("Block: " + block);
System.out.println("First IP: " + firstIP);
System.out.println("Last IP: " + lastIP);
System.out.println("Network Address: " + networkAddress);
// For classless addressing
System.out.println("\nFor Classless Addressing:");
System.out.print("/ Value: "); // Prompt for CIDR value
int cidrValue = scanner.nextInt();
// Calculate details for classless addressing
String cidrMask = getCIDRMask(cidrValue);
int numAddresses = (int) Math.pow(2, 32 - cidrValue);
String cidrFirstIP = getFirstIPCIDR(inetAddress, cidrValue);
String cidrLastIP = getLastIPCIDR(inetAddress, cidrValue);
String cidrNetworkAddress = getNetworkAddressCIDR(inetAddress, cidrValue);
System.out.println("Mask in Decimal: " + cidrMask);
System.out.println("No of IP Addresses in Block: " + numAddresses);
System.out.println("First IP: " + cidrFirstIP);
System.out.println("Last IP: " + cidrLastIP);
System.out.println("Network Address: " + cidrNetworkAddress);
} catch (UnknownHostException e) {
System.out.println("Invalid IP Address.");
} finally {
scanner.close();
}
}
private static String getIPType(InetAddress inetAddress) {
if (inetAddress.isAnyLocalAddress() || inetAddress.isLoopbackAddress() || inetAddress.isLinkLocalAddress()
|| inetAddress.isSiteLocalAddress() || inetAddress.isMulticastAddress()
|| inetAddress.isMCGlobal() || inetAddress.isMCLinkLocal() || inetAddress.isMCNodeLocal()
|| inetAddress.isMCOrgLocal() || inetAddress.isMCSiteLocal()) {
return "Reserved";
} else {
return "Private";
}
}
private static char getIPClass(InetAddress inetAddress) {
byte[] addressBytes = inetAddress.getAddress();
return addressBytes[0] >= 0 && addressBytes[0] <= 127 ? 'A'
: (addressBytes[0] >= 128 && addressBytes[0] <= 191 ? 'B'
: (addressBytes[0] >= 192 && addressBytes[0] <= 223 ? 'C'
: (addressBytes[0] >= 224 && addressBytes[0] <= 239 ? 'D' : 'E')));
}
private static String getDefaultMask(char ipClass) {
switch (ipClass) {
case 'A':
return "255.0.0.0";
case 'B':
return "255.255.0.0";
case 'C':
return "255.255.255.0";
default:
return "Not Applicable";
}
}
private static String getFirstIP(InetAddress inetAddress) {
return inetAddress.getHostAddress().split("/")[0];
}
private static String getLastIP(InetAddress inetAddress) {
int numAddresses = (int) Math.pow(2, 32 - inetAddress.getAddress().length);
return inetAddress.getHostAddress().split("/")[0] + (numAddresses - 2);
}
private static String getNetworkAddress(InetAddress inetAddress) {
return inetAddress.getHostAddress().split("/")[0];
}
private static String getCIDRMask(int cidrValue) {
StringBuilder mask = new StringBuilder();
int value = 0xffffffff << (32 - cidrValue);
for (int i = 3; i >= 0; i--) {
mask.insert(0, (value >> (8 * i)) & 255);
if (i > 0) {
mask.insert(0, ".");
}
}
return mask.toString();
}
private static String getFirstIPCIDR(InetAddress inetAddress, int cidrValue) {
int numAddresses = (int) Math.pow(2, 32 - cidrValue);
String[] ipAddressParts = inetAddress.getHostAddress().split("\\.");
int[] ipAddress = new int[ipAddressParts.length];
for (int i = 0; i < ipAddressParts.length; i++) {
ipAddress[i] = Integer.parseInt(ipAddressParts[i]);
}
ipAddress[3] += 1; // Increment last octet by 1
// Handle overflow
for (int i = 3; i >= 0; i--) {
if (ipAddress[i] > 255) {
ipAddress[i] = 0;
if (i - 1 >= 0) {
ipAddress[i - 1] += 1;
}
}
}
return ipAddress[0] + "." + ipAddress[1] + "." + ipAddress[2] + "." + ipAddress[3];
}
private static String getLastIPCIDR(InetAddress inetAddress, int cidrValue) {
int numAddresses = (int) Math.pow(2, 32 - cidrValue);
String[] ipAddressParts = inetAddress.getHostAddress().split("\\.");
int[] ipAddress = new int[ipAddressParts.length];
for (int i = 0; i < ipAddressParts.length; i++) {
ipAddress[i] = Integer.parseInt(ipAddressParts[i]);
}
ipAddress[3] += numAddresses - 2; // Increment last octet by numAddresses - 2
// Handle overflow
for (int i = 3; i >= 0; i--) {
if (ipAddress[i] > 255) {
ipAddress[i] = 0;
if (i - 1 >= 0) {
ipAddress[i - 1] += 1;
}
}
}
return ipAddress[0] + "." + ipAddress[1] + "." + ipAddress[2] + "." + ipAddress[3];
}
private static String getNetworkAddressCIDR(InetAddress inetAddress, int cidrValue) {
return inetAddress.getHostAddress().split("/")[0];
}
} | RuAmey27/Daily_code | ip.java |
1,096 | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
// On my honor:
//
// - I have not used source code obtained from another student,
// or any other unauthorized source, either modified or
// unmodified.
//
// - All source code and documentation used in my program is
// either my original work, or was derived by me from the
// source code published in the textbook for this course.
//
// - I have not discussed coding details about this project with
// anyone other than my partner (in the case of a joint
// submission), instructor, ACM/UPE tutors or the TAs assigned
// to this course. I understand that I may discuss the concepts
// of this program with other students, and that another student
// may help me debug my program so long as neither of us writes
// anything during the discussion or modifies any computer file
// during the discussion. I have violated neither the spirit nor
// letter of this restriction.
/**
* Main P3 class for Project 3.
*
* This class contains the main method for this project, which does
* several things. First, it deals with the command line parameter
* and usage. Second, it attempts to open and read lines from the
* input file. Third, it handles the commands by using the DNATree
* class and database manager. Fourth, it outputs appropriate errors
* and prints.
*
* @author Chris Schweinhart (schwein)
* @author Nate Kibler (nkibler7)
*/
public class P3 {
/**
* Constant string patterns for command matching. These are
* used for regular expression matching with the commands
* given by the input file. They all allow for uppercase or
* lowercase commands, but require uppercase sequences, with any
* amount of spacing between arguments.
*/
private static final String INSERT_PATTERN = "^ *(insert|INSERT) *[ACGT]+ *[0-9]+ *$";
private static final String REMOVE_PATTERN = "^ *(remove|REMOVE) *[ACGT]+ *$";
private static final String PRINT_PATTERN = "^ *(print|PRINT) *$";
private static final String SEARCH_PATTERN = "^ *(search|SEARCH) *[ACGT]+[$]? *$";
/**
* Additional string patterns for result matching. These are
* used for parsing the search results from the DNA Tree to use
* with the database manager.
*/
private static final String KEY_PATTERN = "^Key: [ACGT]+$";
private static final String HANDLE_PATTERN = "^\\[[0-9]+, [0-9]+\\]$";
/**
* Member field for DNATree tree. This tree represents the
* sequences to be stored in memory, with each branch for
* one letter of a DNA sequence. For more information, look
* in the DNATree.java file.
*/
private static DNATree tree;
/**
* Member field for DatabaseManager. This memory manager will
* keep track of the bytes in memory for each DNA sequence.
* Also keeps track of the free memory blocks. For more
* information, look in the DatabaseManager.java file.
*/
private static DatabaseManager dbm;
/**
* Main method to control data flow. This function takes
* the command line parameter as input and uses it to read
* from the input file, executing and outputting commands
* along the way.
*
* @param args - the command line arguments
*/
public static void main(String[] args) {
// Check for proper usage
if (args.length != 1) {
System.out.println("Usage:");
System.out.println("P3 COMMAND_FILE");
System.exit(0);
}
String fileName = args[0];
tree = new DNATree();
dbm = new DatabaseManager();
// Main command line reading
try {
// Attempt to open the input file into a buffered reader
BufferedReader in = new BufferedReader(new FileReader(fileName));
// Keep reading in commands until we reach the EOF
String line;
while ((line = in.readLine()) != null) {
if (line.matches(INSERT_PATTERN)) {
// Parse out the sequence id and length from the command line
int begin = Math.max(line.indexOf("r"), line.indexOf("R")) + 2;
int end = Math.max(Math.max(Math.max(line.lastIndexOf('A'),
line.lastIndexOf('C')), line.lastIndexOf('G')),
line.lastIndexOf('T')) + 1;
String sequence = line.substring(begin, end);
sequence = sequence.trim();
int length = Integer.parseInt(line.substring(end).trim());
if (length <= 0) {
System.out.println("Length less than zero.");
continue;
}
// Get the next line for the sequence
String entry = in.readLine();
// Add to the dbm
Handle handle = dbm.insert(entry, length);
// Add to tree
int result = tree.insert(sequence, handle);
// TODO Fix logic
if(result < 0) {
dbm.remove(handle);
System.out.println("Sequence " + sequence + " already in tree.");
} else {
System.out.println("Sequence " + sequence + " inserted at level " + result + ".");
}
System.out.println();
} else if (line.matches(REMOVE_PATTERN)) {
// Parse out the sequence id from the command line
int index = Math.max(line.indexOf("v"), line.indexOf("V")) + 2;
String sequence = line.substring(index);
sequence = sequence.trim();
// Remove sequence id from tree
Handle handle = tree.remove(sequence);
// Remove sequence from dbm
if (handle == null) {
System.out.println("Sequence " + sequence + " not found in tree.");
System.out.println();
} else {
dbm.remove(handle);
System.out.println("Sequence " + sequence + " removed from tree.");
System.out.println();
}
} else if (line.matches(PRINT_PATTERN)) {
// Output the tree
System.out.println(tree);
// Output free blocks
System.out.println(dbm);
System.out.println();
} else if (line.matches(SEARCH_PATTERN)) {
// Parse out the sequence id from the command line
int index = Math.max(line.indexOf("h"), line.indexOf("H")) + 1;
String sequence = line.substring(index);
sequence = sequence.trim();
// Search the tree for handles
String results = tree.search(sequence);
Scanner scan = new Scanner(results);
String output = scan.nextLine() + "\n";
// Augment output with results from dbm
String entry;
int offset, length;
Handle handle;
while (scan.hasNextLine()) {
entry = scan.nextLine();
if (entry.matches(KEY_PATTERN)) {
output += entry + "\n";
} else if (entry.matches(HANDLE_PATTERN)) {
// Parse out offset and length
offset = Integer.parseInt(entry.substring(entry.indexOf('[') + 1, entry.indexOf(',')));
length = Integer.parseInt(entry.substring(entry.indexOf(',') + 2, entry.indexOf(']')));
// Create handle and use it to query database
handle = new Handle(offset, length);
output += "Sequence:\n" + dbm.getEntry(handle) + "\n";
} else {
continue;
}
}
scan.close();
System.out.println(output.substring(0, output.length() - 1));
System.out.println();
} else {
continue;
}
}
in.close();
} catch (FileNotFoundException e) {
System.out.println("The input file could not be found.");
System.exit(0);
} catch (IOException e) {
System.out.println("Error reading from file.");
System.exit(0);
} catch (Exception e) {
System.out.println("Incorrect file formatting.");
e.printStackTrace();
System.exit(0);
}
}
} | clschwein/P3 | P3.java |
1,097 | import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.table.DefaultTableModel;
public class db implements myvariables {
String user=jTextField1.getText();
Connection myconnection=null;
//run when game ends
try
{
Class.forName("com.mysql.jdbc.Driver");
myconnection=DriverManager.getConnection(path+place,username,password);
try
{
int score=successfuljumps;
String q="update scorer set name=?,scored=?";
PreparedStatement mystatement=myconnection.prepareStatement(q);
mystatement.setString(1,user);
mystatement.setString(2,""+score);
mystatement.executeUpdate();
String q2="Select * from scorer order by scored desc limit 10 ";
PreparedStatement mystatement2=(PreparedStatement)myconnection.prepareStatement(q2);
DefaultTableModel mymodel;
ResultSet myresult = mystatement2.executeQuery();
if(myresult.next())
{
mymodel=(DefaultTableModel) jTable1.getModel();
do{
String name,scored;
name=myresult.getString("name");
scored=myresult.getString("scored");
mymodel.addRow(new Object[]{name,score});
}
while(myresult.next());
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(rootPane, "error in query"+e.getMessage());
}
finally
{
myconnection.close();
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(rootPane,"error in connection"+e.getMessage(),"error",JOptionPane.ERROR_MESSAGE);
} // TODO add your handling code here: | NITJal/G1A-agile-lab-dragon-fly-project | db.java |
1,098 |
public class cp
{
/**
* The name of this program.
* This is the program name that is used
* when displaying error messages.
*/
public static final String PROGRAM_NAME = "cp" ;
/**
* The size of the buffer to be used when reading files.
*/
public static final int BUF_SIZE = 4096 ;
/**
* The file mode to use when creating the output file.
*/
// ??? perhaps this should be the same mode as the input file
public static final short OUTPUT_MODE = 0700 ;
/**
* Copies an input file to an output file.
* @exception java.lang.Exception if an exception is thrown by
* an underlying operation
*/
public static void main( String[] argv ) throws Exception
{
// initialize the file system simulator kernel
Kernel.initialize() ;
// make sure we got the correct number of parameters
if( argv.length != 2 )
{
System.err.println( PROGRAM_NAME + ": usage: java " +
PROGRAM_NAME + " input-file output-file" ) ;
Kernel.exit( 1 ) ;
}
// give the parameters more meaningful names
String in_name = argv[0] ;
String out_name = argv[1] ;
// open the input file
int in_fd = Kernel.open( in_name , Kernel.O_RDONLY ) ;
if( in_fd < 0 )
{
Kernel.perror( PROGRAM_NAME ) ;
System.err.println( PROGRAM_NAME + ": unable to open input file \"" +
in_name + "\"" ) ;
Kernel.exit( 2 ) ;
}
// open the output file
int out_fd = Kernel.creat( out_name , OUTPUT_MODE ) ;
if( out_fd < 0 )
{
Kernel.perror( PROGRAM_NAME ) ;
System.err.println( PROGRAM_NAME + ": unable to open output file \"" +
argv[1] + "\"" ) ;
Kernel.exit( 3 ) ;
}
// read and write buffers full of data while we can
int rd_count ;
byte[] buffer = new byte[BUF_SIZE] ;
while( true )
{
// read a buffer full from the input file
rd_count = Kernel.read( in_fd , buffer , BUF_SIZE ) ;
// if error or nothing read, quit the loop
if( rd_count <= 0 )
break ;
// write whatever we read to the output file
int wr_count = Kernel.write( out_fd , buffer , rd_count ) ;
// if error or nothing written, give message and exit
if( wr_count <= 0 )
{
Kernel.perror( PROGRAM_NAME ) ;
System.err.println( PROGRAM_NAME +
": error during write to output file" ) ;
Kernel.exit( 4 ) ;
}
}
// close the files
Kernel.close( in_fd ) ;
Kernel.close( out_fd ) ;
// check to see if the final read was successful; exit accordingly
if( rd_count == 0 )
Kernel.exit( 0 ) ;
else
{
Kernel.perror( PROGRAM_NAME ) ;
System.err.println( PROGRAM_NAME +
": error during read from input file" ) ;
Kernel.exit( 5 ) ;
}
}
}
| walekarkaran/Java-based-FileSystem-Simulator-with-Unix-System-Call-Integration | cp.java |
1,099 | //
// io.java
// io for Java
//
// Created by Patrick Perini on 9/29/11.
// Licensing information available in README.md
//
import java.io.*;
import java.util.*;
import java.net.*;
public class io
{
public static void error(int status, Object... objects)
{
for(Object obj : objects)
{
System.err.println(obj);
}
System.exit(status);
}
public static void error(Object... objects)
{
for(Object obj : objects)
{
System.err.println(obj);
}
}
public static void print(Object... objects)
{
for(Object obj : objects)
{
System.out.println(obj);
}
}
public static void printf(String format, Object... objects)
{
System.out.printf(format, objects);
}
public static String read() throws IOException
{
BufferedReader inReader = new BufferedReader(new InputStreamReader(System.in));
return inReader.readLine();
}
public static ArrayList<String> read(int lines) throws IOException
{
BufferedReader inReader = new BufferedReader(new InputStreamReader(System.in));
ArrayList<String> buffer = new ArrayList<String>();
for(int i = 0; i < lines; i++)
{
buffer.add(inReader.readLine());
}
return buffer;
}
public static String read(String filename) throws FileNotFoundException
{
Scanner inReader = new Scanner(new FileInputStream(filename));
String buffer = "";
while(inReader.hasNextLine())
{
buffer += inReader.nextLine()+"\n";
}
return buffer;
}
public static String read(String filename, int length) throws FileNotFoundException, IOException
{
RandomAccessFile file = new RandomAccessFile(new File(filename), "r");
String outString = "";
for(int i =0; i < length && i < file.length(); i++)
{
outString += file.readChar();
}
file.close();
return outString;
}
public static ArrayList<String> read(int lines, Socket socket) throws IOException
{
BufferedReader inRead = new BufferedReader(new InputStreamReader(socket.getInputStream()));
ArrayList<String> buffer = new ArrayList<String>();
for(int i = 0; i < lines; i++)
{
buffer.add(inRead.readLine());
}
return buffer;
}
public static String read(Socket socket) throws IOException
{
BufferedReader inRead = new BufferedReader(new InputStreamReader(socket.getInputStream()));
return inRead.readLine();
}
public static void write(String filename, Object... objects) throws IOException
{
BufferedWriter outWrite = new BufferedWriter(new FileWriter(filename));
boolean first = true;
for(Object obj : objects)
{
if(first)
{
outWrite.write(obj+"");
first = false;
}
else
{
outWrite.write("\n"+obj);
}
}
outWrite.close();
}
public static void write(String filename, int offset, Object... objects) throws IOException
{
RandomAccessFile file = new RandomAccessFile(new File(filename), "rw");
String outString = "";
for(int i = 0; i < offset; i++)
{
file.readByte();
}
boolean first = true;
for(Object obj : objects)
{
if(first)
{
outString += obj;
first = false;
}
else
{
outString += "\n"+obj;
}
}
file.write(outString.getBytes());
file.close();
}
public static void write(Socket socket, Object... objects) throws IOException
{
PrintWriter outWrite = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
for(Object obj : objects)
{
outWrite.println(obj);
}
}
public static ArrayList<String> file(String filename) throws FileNotFoundException
{
Scanner inReader = new Scanner(new FileInputStream(filename));
ArrayList<String> buffer = new ArrayList<String>();
while(inReader.hasNextLine())
{
buffer.add(inReader.nextLine());
}
return buffer;
}
public static void save(ArrayList<?> data, String filename) throws IOException
{
File file = new File(filename);
if(file.exists())
file.delete();
file.createNewFile();
BufferedWriter outWrite = new BufferedWriter(new FileWriter(filename));
for(Object obj : data)
{
outWrite.write(obj+"\n");
}
outWrite.close();
}
public static void newfile(String filename) throws IOException
{
File file = new File(filename);
if(file.exists())
file.delete();
file.createNewFile();
}
public static ServerSocket newsocket() throws UnknownHostException, IOException
{
return new ServerSocket(80);
}
public static ServerSocket newsocket(int port) throws UnknownHostException, IOException
{
return new ServerSocket(port);
}
public static Socket newsocket(String addr) throws UnknownHostException, IOException
{
return new Socket(InetAddress.getByName(addr), 80);
}
public static Socket newsocket(String addr, int port) throws UnknownHostException, IOException
{
return new Socket(InetAddress.getByName(addr), port);
}
} | pcperini-historic/io | io.java |
1,100 | /**
* 2022 AP Computer Science Exam - Free Response Questions (FRQ)
* Problems definition: https://apcentral.collegeboard.org/pdf/ap22-frq-computer-science-a.pdf
* Solutions for question 3(b).
*/
public ArrayList<String> collectComments() {
ArrayList<String> arr = new ArrayList<>();
for (int i = 0; i < allReviews.length; i++) {
String c = allReviews[i].getComment();
if (c.indexOf("!") != -1) {
String lastChar = c.substring(c.length() - 1);
String addChar = "";
if (!(lastChar.equals(".") || lastChar.equals("!"))) {
addChar = ".";
}
arr.add(i + "-" + c + addChar);
}
}
return arr;
}
/**
* Alternate solution simplifying the first one a bit.
*/
public ArrayList<String> collectComments() {
ArrayList<String> arr = new ArrayList<>();
for (int i = 0; i < allReviews.length; i++) {
String c = allReviews[i].getComment();
if (c.indexOf("!") != -1) {
String lastChar = c.substring(c.length() - 1);
if (!(lastChar.equals(".") || lastChar.equals("!"))) {
c += ".";
}
arr.add(i + "-" + c);
}
}
return arr;
}
/**
* Alternate solution checking the ending of the comment via indexOf().
*/
public ArrayList<String> collectComments() {
ArrayList<String> arr = new ArrayList<>();
for (int i = 0; i < allReviews.length; i++) {
String c = allReviews[i].getComment();
if (c.indexOf("!") != -1) {
String ending = "!.";
// if the last character of the comment is not in an expected set,
// correct the comment by appending a period to it.
if (ending.indexOf(c.substring(c.length() - 1)) == -1) {
c += ".";
}
arr.add(i + "-" + c);
}
}
return arr;
}
| superpenguin612/ap-csa-frq-2022 | 3b.java |
1,101 | public class yc
extends yg
{
private final ya a;
private wn b;
private int c;
private final acy h;
public yc(wn β, acy β, ya β, int β, int β, int β)
{
super(β, β, β, β);
this.b = β;
this.h = β;
this.a = β;
}
public boolean a(zx β)
{
return false;
}
public zx a(int β)
{
if (e()) {
this.c += Math.min(β, d().b);
}
return super.a(β);
}
protected void a(zx β, int β)
{
this.c += β;
c(β);
}
protected void c(zx β)
{
β.a(this.b.o, this.b, this.c);
this.c = 0;
}
public void a(wn β, zx β)
{
c(β);
acz β = this.a.i();
if (β != null)
{
zx β = this.a.a(0);
zx β = this.a.a(1);
if ((a(β, β, β)) || (a(β, β, β)))
{
this.h.a(β);
β.b(na.G);
if ((β != null) && (β.b <= 0)) {
β = null;
}
if ((β != null) && (β.b <= 0)) {
β = null;
}
this.a.a(0, β);
this.a.a(1, β);
}
}
}
private boolean a(acz β, zx β, zx β)
{
zx β = β.a();
zx β = β.b();
if ((β != null) && (β.b() == β.b()))
{
if ((β != null) && (β != null) && (β.b() == β.b()))
{
β.b -= β.b;
β.b -= β.b;
return true;
}
if ((β == null) && (β == null))
{
β.b -= β.b;
return true;
}
}
return false;
}
}
| Tominous/LabyMod-1.8 | yc.java |
1,102 | package com.android.support;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Handler;
import com.tencent.gcloud.msdk.core.MSDKMethodNameID;
import com.tencent.smtt.sdk.TbsListener;
import com.twitter.sdk.android.core.internal.TwitterApiConstants;
import dalvik.system.DexFile;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
public class GG {
public static String appSign = C0131.m2095(m1416(), 0, 47, 2115);
public static Preferences prefs;
private static BroadcastReceiver receiver;
/* renamed from: short reason: not valid java name */
private static final short[] f25short;
public static int signi;
static {
short[] sArr = new short[MSDKMethodNameID.MSDK_GROUP_GET_GROUP_RELATION];
// fill-array-data instruction
sArr[0] = 2055;
sArr[1] = 2049;
sArr[2] = 2169;
sArr[3] = 2163;
sArr[4] = 2164;
sArr[5] = 2169;
sArr[6] = 2171;
sArr[7] = 2166;
sArr[8] = 2169;
sArr[9] = 2167;
sArr[10] = 2054;
sArr[11] = 2169;
sArr[12] = 2160;
sArr[13] = 2053;
sArr[14] = 2169;
sArr[15] = 2053;
sArr[16] = 2053;
sArr[17] = 2169;
sArr[18] = 2162;
sArr[19] = 2163;
sArr[20] = 2169;
sArr[21] = 2050;
sArr[22] = 2160;
sArr[23] = 2169;
sArr[24] = 2055;
sArr[25] = 2164;
sArr[26] = 2169;
sArr[27] = 2055;
sArr[28] = 2055;
sArr[29] = 2169;
sArr[30] = 2170;
sArr[31] = 2167;
sArr[32] = 2169;
sArr[33] = 2166;
sArr[34] = 2161;
sArr[35] = 2169;
sArr[36] = 2166;
sArr[37] = 2166;
sArr[38] = 2169;
sArr[39] = 2161;
sArr[40] = 2164;
sArr[41] = 2169;
sArr[42] = 2170;
sArr[43] = 2161;
sArr[44] = 2169;
sArr[45] = 2170;
sArr[46] = 2048;
sArr[47] = 911;
sArr[48] = 896;
sArr[49] = 906;
sArr[50] = 924;
sArr[51] = 897;
sArr[52] = 903;
sArr[53] = 906;
sArr[54] = 960;
sArr[55] = 903;
sArr[56] = 896;
sArr[57] = 922;
sArr[58] = 907;
sArr[59] = 896;
sArr[60] = 922;
sArr[61] = 960;
sArr[62] = 911;
sArr[63] = 909;
sArr[64] = 922;
sArr[65] = 903;
sArr[66] = 897;
sArr[67] = 896;
sArr[68] = 960;
sArr[69] = 958;
sArr[70] = 943;
sArr[71] = 941;
sArr[72] = 933;
sArr[73] = 943;
sArr[74] = 937;
sArr[75] = 939;
sArr[76] = 945;
sArr[77] = 943;
sArr[78] = 938;
sArr[79] = 938;
sArr[80] = 939;
sArr[81] = 938;
sArr[82] = 2609;
sArr[83] = 2622;
sArr[84] = 2612;
sArr[85] = 2594;
sArr[86] = 2623;
sArr[87] = 2617;
sArr[88] = 2612;
sArr[89] = 2686;
sArr[90] = 2617;
sArr[91] = 2622;
sArr[92] = 2596;
sArr[93] = 2613;
sArr[94] = 2622;
sArr[95] = 2596;
sArr[96] = 2686;
sArr[97] = 2609;
sArr[98] = 2611;
sArr[99] = 2596;
sArr[100] = 2617;
sArr[101] = 2623;
sArr[102] = 2622;
sArr[103] = 2686;
sArr[104] = 2560;
sArr[105] = 2577;
sArr[106] = 2579;
sArr[107] = 2587;
sArr[108] = 2577;
sArr[109] = 2583;
sArr[110] = 2581;
sArr[111] = 2575;
sArr[112] = 2585;
sArr[113] = 2590;
sArr[114] = 2563;
sArr[115] = 2564;
sArr[116] = 2577;
sArr[117] = 2588;
sArr[118] = 2588;
sArr[119] = 3046;
sArr[120] = 3049;
sArr[121] = 3043;
sArr[122] = 3061;
sArr[123] = 3048;
sArr[124] = 3054;
sArr[125] = 3043;
sArr[126] = 2985;
sArr[127] = 3054;
sArr[128] = 3049;
sArr[129] = 3059;
sArr[130] = 3042;
sArr[131] = 3049;
sArr[132] = 3059;
sArr[133] = 2985;
sArr[134] = 3046;
sArr[135] = 3044;
sArr[136] = 3059;
sArr[137] = 3054;
sArr[138] = 3048;
sArr[139] = 3049;
sArr[140] = 2985;
sArr[141] = 3031;
sArr[142] = 3014;
sArr[143] = 3012;
sArr[144] = 3020;
sArr[145] = 3014;
sArr[146] = 3008;
sArr[147] = 3010;
sArr[148] = 3032;
sArr[149] = 3009;
sArr[150] = 3026;
sArr[151] = 3019;
sArr[152] = 3019;
sArr[153] = 3038;
sArr[154] = 3032;
sArr[155] = 3029;
sArr[156] = 3010;
sArr[157] = 3018;
sArr[158] = 3016;
sArr[159] = 3025;
sArr[160] = 3010;
sArr[161] = 3011;
sArr[162] = 2914;
sArr[163] = 2931;
sArr[164] = 2929;
sArr[165] = 2937;
sArr[166] = 2931;
sArr[167] = 2933;
sArr[168] = 2935;
sArr[169] = 3093;
sArr[170] = 3097;
sArr[171] = 3099;
sArr[172] = 3160;
sArr[173] = 3073;
sArr[174] = 3084;
sArr[175] = 3089;
sArr[176] = 3089;
sArr[177] = 3084;
sArr[178] = 3097;
sArr[179] = 3096;
sArr[180] = 3100;
sArr[181] = 3072;
sArr[182] = 3087;
sArr[183] = 3160;
sArr[184] = 3127;
sArr[185] = 3093;
sArr[186] = 3074;
sArr[187] = 3103;
sArr[188] = 3072;
sArr[189] = 3103;
sArr[190] = 3074;
sArr[191] = 3087;
sArr[192] = 3131;
sArr[193] = 3095;
sArr[194] = 3103;
sArr[195] = 3096;
sArr[196] = 1354;
sArr[197] = 1349;
sArr[198] = 1359;
sArr[199] = 1369;
sArr[200] = 1348;
sArr[201] = 1346;
sArr[202] = 1359;
sArr[203] = 1285;
sArr[204] = 1358;
sArr[205] = 1363;
sArr[206] = 1375;
sArr[207] = 1285;
sArr[208] = 1354;
sArr[209] = 1354;
sArr[210] = 3018;
sArr[211] = 3013;
sArr[212] = 3023;
sArr[213] = 3033;
sArr[214] = 3012;
sArr[215] = 3010;
sArr[216] = 3023;
sArr[217] = 2949;
sArr[218] = 3021;
sArr[219] = 3010;
sArr[220] = 3027;
sArr[221] = 2949;
sArr[222] = 3018;
sArr[223] = 1124;
sArr[224] = 1149;
sArr[225] = 1129;
sArr[226] = 1122;
sArr[227] = 1062;
sArr[228] = 1124;
sArr[229] = 1121;
sArr[230] = 1130;
sArr[231] = 1062;
sArr[232] = 1129;
sArr[233] = 1885;
sArr[234] = 1860;
sArr[235] = 1872;
sArr[236] = 1883;
sArr[237] = 1823;
sArr[238] = 1872;
sArr[239] = 2779;
sArr[240] = 2774;
sArr[241] = 2756;
sArr[242] = 2778;
sArr[243] = 2713;
sArr[244] = 2774;
sArr[245] = 1420;
sArr[246] = 1409;
sArr[247] = 1427;
sArr[248] = 1421;
sArr[249] = 1486;
sArr[250] = 1420;
sArr[251] = 1409;
sArr[252] = 1427;
sArr[253] = 1421;
sArr[254] = 757;
sArr[255] = 760;
sArr[256] = 746;
sArr[257] = 756;
sArr[258] = 695;
sArr[259] = 725;
sArr[260] = 760;
sArr[261] = 746;
sArr[262] = 756;
sArr[263] = 731;
sArr[264] = 760;
sArr[265] = 746;
sArr[266] = 764;
sArr[267] = 2583;
sArr[268] = 2584;
sArr[269] = 2578;
sArr[270] = 2564;
sArr[271] = 2585;
sArr[272] = 2591;
sArr[273] = 2578;
sArr[274] = 2648;
sArr[275] = 2579;
sArr[276] = 2574;
sArr[277] = 2562;
sArr[278] = 2648;
sArr[279] = 2610;
sArr[280] = 2583;
sArr[281] = 2579;
sArr[282] = 2587;
sArr[283] = 2585;
sArr[284] = 2584;
sArr[285] = 2619;
sArr[286] = 2583;
sArr[287] = 2584;
sArr[288] = 2583;
sArr[289] = 2577;
sArr[290] = 2579;
sArr[291] = 2564;
sArr[292] = 2512;
sArr[293] = 2505;
sArr[294] = 2525;
sArr[295] = 2518;
sArr[296] = 2450;
sArr[297] = 2544;
sArr[298] = 2505;
sArr[299] = 2525;
sArr[300] = 2558;
sArr[301] = 2515;
sArr[302] = 2515;
sArr[303] = 2512;
sArr[304] = 2521;
sArr[305] = 2525;
sArr[306] = 2514;
sArr[307] = 2938;
sArr[308] = 2931;
sArr[309] = 2818;
sArr[310] = 1505;
sArr[311] = 2081;
sArr[312] = 2088;
sArr[313] = 2137;
sArr[314] = 2055;
sArr[315] = 2066;
sArr[316] = 2064;
sArr[317] = 2170;
sArr[318] = 2072;
f25short = sArr;
}
public GG() {
}
public static void GG(Context context) {
Object obj;
BroadcastReceiver broadcastReceiver;
Object obj2;
Object obj3;
Object obj4;
Context context2 = context;
new IntentFilter();
Object obj5 = obj;
C0131.m2113(obj5, C0130.m1942(m1416(), 47, 35, 1006));
C0131.m2113(obj5, C0129.m1884(m1416(), 82, 37, 2640));
C0131.m2113(obj5, C0131.m2095(m1416(), 119, 43, 2951));
C0129.m1873(obj5, C0127.m1795(m1416(), TbsListener.ErrorCode.STARTDOWNLOAD_3, 7, 2834));
new BroadcastReceiver(context2) {
private final Context val$context;
{
this.val$context = r57;
}
/* renamed from: Ϋ¦Ϋ£ΫΫ£ reason: contains not printable characters */
public static Context m1417(Object obj) {
if (C0127.m1700() >= 0) {
return ((AnonymousClass100000004) obj).val$context;
}
return null;
}
@Override
public void onReceive(Context context, Intent intent) {
Object obj;
Context context2 = context;
Intent intent2 = intent;
String r4 = C0129.m1903(intent2);
String r6 = C0130.m1960(C0130.m1941(intent2));
if (C0127.m1732(m1417(this), r6)) {
new Runnable(this, m1417(this), r6, context2) {
/* renamed from: short reason: not valid java name */
private static final short[] f26short = {3099, 4736, 3134, 3314, 3286, 2019, 6476, 2002, 1931, 1993, 6500, 2272, 2264, 2129, 2244, 2192, 2264, 2265, 5751, 2270, 2192, 2259, 2128, 2265, 2192, 2465, 5639, 2244, 2192, 5721, 2270, 2263, 2192, 2260, 5717, 2270, 2263, 2192, 2263, 2130, 2249, 2192, 2248, 2245, 2270, 2263, 2192, 2465, 5737, 2244, 2192, 2193, 2192, 2234, 2276, 2138, 2270, 2192, 5721, 2270, 2263, 2192, 2260, 5717, 2270, 2263, 2192, 2186, 2192, 3244, 3318, 3271, 3269, 3277, 3271, 3265, 3267, 3206, 3228, 3206};
private final AnonymousClass100000004 this$0;
private final Context val$context;
private final Context val$context2;
private final String val$packageName;
{
this.this$0 = r60;
this.val$context = r61;
this.val$packageName = r62;
this.val$context2 = r63;
}
static AnonymousClass100000004 access$0(AnonymousClass100000003 r55) {
return m1421(r55);
}
/* renamed from: ΫΫΫ§Ϋ£Ϋ₯ reason: not valid java name and contains not printable characters */
public static Context m1418(Object obj) {
if (C0127.m1700() >= 0) {
return ((AnonymousClass100000003) obj).val$context;
}
return null;
}
/* renamed from: ΫΫ Ϋ¦Ϋ€Ϋ reason: not valid java name and contains not printable characters */
public static Context m1419(Object obj) {
if (C0131.m2080() > 0) {
return ((AnonymousClass100000003) obj).val$context2;
}
return null;
}
/* renamed from: ΫΫ§Ϋ£Ϋ£Ϋ¨ reason: not valid java name and contains not printable characters */
public static short[] m1420() {
if (C0129.m1842() > 0) {
return f26short;
}
return null;
}
/* renamed from: Ϋ£Ϋ§Ϋ¦Ϋ‘ reason: not valid java name and contains not printable characters */
public static AnonymousClass100000004 m1421(Object obj) {
if (C0129.m1842() > 0) {
return ((AnonymousClass100000003) obj).this$0;
}
return null;
}
/* renamed from: Ϋ§Ϋ£Ϋ£Ϋ¨ reason: not valid java name and contains not printable characters */
public static String m1422(Object obj) {
if (C0127.m1700() > 0) {
return ((AnonymousClass100000003) obj).val$packageName;
}
return null;
}
@Override
public void run() {
Object obj;
Object obj2;
Object obj3;
Object obj4;
Object obj5;
Object obj6;
Object obj7;
Object obj8;
PackageManager r2 = C0127.m1713(m1418(this));
String str = null;
try {
str = (String) C0127.m1781(r2, C0130.m1994(r2, m1422(this), 128));
} catch (PackageManager.NameNotFoundException e) {
C0127.m1774(e);
}
C0127.m1729(C0127.m1759(), C0130.m1963(m1422(this)), false);
new AlertDialog.Builder(m1419(this));
new DialogInterface.OnClickListener(this) {
private final AnonymousClass100000003 this$0;
{
this.this$0 = r57;
}
static AnonymousClass100000003 access$0(AnonymousClass100000000 r55) {
return m1423(r55);
}
/* renamed from: Ϋ’Ϋ Ϋ€Ϋ§ reason: not valid java name and contains not printable characters */
public static AnonymousClass100000003 m1423(Object obj) {
if (C0129.m1842() > 0) {
return ((AnonymousClass100000000) obj).this$0;
}
return null;
}
@Override
public void onClick(DialogInterface dialogInterface, int i) {
DialogInterface dialogInterface2 = dialogInterface;
int i2 = i;
C0129.m1814(C0129.m1823());
}
};
new DialogInterface.OnClickListener(this) {
private final AnonymousClass100000003 this$0;
{
this.this$0 = r57;
}
static AnonymousClass100000003 access$0(AnonymousClass100000001 r55) {
return m1424(r55);
}
/* renamed from: Ϋ€Ϋ¨Ϋ£Ϋ§ reason: not valid java name and contains not printable characters */
public static AnonymousClass100000003 m1424(Object obj) {
if (C0129.m1842() > 0) {
return ((AnonymousClass100000001) obj).this$0;
}
return null;
}
@Override
public void onClick(DialogInterface dialogInterface, int i) {
DialogInterface dialogInterface2 = dialogInterface;
int i2 = i;
C0129.m1814(C0129.m1823());
}
};
AlertDialog r4 = C0127.m1722(C0130.m1924(C0131.m2052(C0131.m2077(obj, C0131.m2095(m1420(), 0, 3, 3159)), C0130.m1942(m1420(), 3, 2, 3261), obj2), C0130.m1942(m1420(), 5, 6, 1963), obj3));
new StringBuffer();
new StringBuffer();
new StringBuffer();
C0129.m1817(r4, C0127.m1785(C0129.m1848(C0129.m1848(obj4, C0127.m1785(C0129.m1848(C0129.m1848(obj5, C0127.m1785(C0129.m1848(C0129.m1848(obj6, C0131.m2095(m1420(), 11, 58, 2224)), str))), C0130.m1942(m1420(), 69, 11, 3238)))), m1422(this))));
C0130.m1910(r4, false);
C0129.m1830(r4);
new Handler(C0131.m2059());
new Runnable(this) {
private final AnonymousClass100000003 this$0;
{
this.this$0 = r57;
}
static AnonymousClass100000003 access$0(AnonymousClass100000002 r55) {
return m1425(r55);
}
/* renamed from: Ϋ Ϋ£Ϋ§Ϋ¦ reason: not valid java name and contains not printable characters */
public static AnonymousClass100000003 m1425(Object obj) {
if (C0131.m2080() >= 0) {
return ((AnonymousClass100000002) obj).this$0;
}
return null;
}
@Override
public void run() {
C0129.m1814(C0129.m1823());
}
};
boolean r6 = C0127.m1750(obj7, obj8, (long) 2000);
}
};
C0131.m2094((Activity) m1417(this), obj);
}
}
};
receiver = broadcastReceiver;
Intent r14 = C0129.m1893(context2, m1415(), obj5);
try {
signi = 1;
prefs = C0131.m2101(context2);
new ArrayList();
Object obj6 = obj2;
long r4 = C0131.m2065(context2);
if (!C0130.m1943(C0129.m1874(context2), C0127.m1727())) {
new Runnable(context2) {
/* renamed from: short reason: not valid java name */
private static final short[] f27short = {1267, 1240, 1098, 1168, 1101, 1168, 1162, 1168, 1445, 1409, 1136, 6879, 1089, 1048, 1114, 6903, 3191, 4856, 3103, 3147, 3159, 4846, 3153, 3160, 3103, 3151, 3159, 3294, 3147, 3103, 3159, 3158, 4856, 3153, 3103, 3166, 3151, 3156, 3103, 3165, 4852, 3103, 3164, 3159, 4854, 3153, 3159, 3103, 3148, 4818, 3166, 3103, 3091, 3103, 3148, 4738, 3103, 3374, 3276, 3153, 3160, 3103, 4822, 3153, 3160, 3103, 3163, 4826, 3153, 3160, 3103, 3153, 3160, 3166, 3142, 3103, 3165, 3293, 3142, 3103, 3160, 3158, 4834, 3103, 3102, 3102, 3102};
private final Context val$context;
{
this.val$context = r57;
}
/* renamed from: ΫΫ’Ϋ Ϋ¦Ϋ¦ reason: not valid java name and contains not printable characters */
public static short[] m1426() {
if (C0127.m1700() >= 0) {
return f27short;
}
return null;
}
/* renamed from: Ϋ§Ϋ¨Ϋ¨Ϋ£ reason: not valid java name and contains not printable characters */
public static Context m1427(Object obj) {
if (C0127.m1700() > 0) {
return ((AnonymousClass100000008) obj).val$context;
}
return null;
}
@Override
public void run() {
Object obj;
Object obj2;
Object obj3;
Object obj4;
Object obj5;
new AlertDialog.Builder(m1427(this));
new DialogInterface.OnClickListener(this) {
private final AnonymousClass100000008 this$0;
{
this.this$0 = r57;
}
static AnonymousClass100000008 access$0(AnonymousClass100000005 r55) {
return m1428(r55);
}
/* renamed from: Ϋ§Ϋ Ϋ§Ϋ¨ reason: not valid java name and contains not printable characters */
public static AnonymousClass100000008 m1428(Object obj) {
if (C0128.m1803() <= 0) {
return ((AnonymousClass100000005) obj).this$0;
}
return null;
}
@Override
public void onClick(DialogInterface dialogInterface, int i) {
DialogInterface dialogInterface2 = dialogInterface;
int i2 = i;
C0129.m1814(C0129.m1823());
}
};
new DialogInterface.OnClickListener(this) {
private final AnonymousClass100000008 this$0;
{
this.this$0 = r57;
}
static AnonymousClass100000008 access$0(AnonymousClass100000006 r55) {
return m1429(r55);
}
/* renamed from: Ϋ¨Ϋ‘Ϋ§Ϋ‘ reason: not valid java name and contains not printable characters */
public static AnonymousClass100000008 m1429(Object obj) {
if (C0129.m1842() >= 0) {
return ((AnonymousClass100000006) obj).this$0;
}
return null;
}
@Override
public void onClick(DialogInterface dialogInterface, int i) {
DialogInterface dialogInterface2 = dialogInterface;
int i2 = i;
C0129.m1814(C0129.m1823());
}
};
AlertDialog r2 = C0127.m1722(C0130.m1924(C0131.m2052(C0131.m2077(obj, C0129.m1884(m1426(), 0, 8, 1200)), C0129.m1884(m1426(), 8, 2, 1514), obj2), C0131.m2095(m1426(), 10, 6, 1080), obj3));
C0129.m1817(r2, C0130.m1942(m1426(), 16, 71, 3135));
C0130.m1910(r2, false);
C0129.m1830(r2);
new Handler(C0131.m2059());
new Runnable(this) {
private final AnonymousClass100000008 this$0;
{
this.this$0 = r57;
}
static AnonymousClass100000008 access$0(AnonymousClass100000007 r55) {
return m1430(r55);
}
/* renamed from: Ϋ¨Ϋ ΫΫ’ reason: not valid java name and contains not printable characters */
public static AnonymousClass100000008 m1430(Object obj) {
if (C0129.m1842() > 0) {
return ((AnonymousClass100000007) obj).this$0;
}
return null;
}
@Override
public void run() {
C0129.m1814(C0129.m1823());
}
};
boolean r4 = C0127.m1750(obj4, obj5, (long) 1000);
}
};
C0131.m2094((Activity) context2, obj3);
}
PackageManager r6 = C0127.m1713(context2);
Iterator r8 = C0127.m1775(C0130.m1935(r6, 0));
while (C0131.m2107(r8)) {
ApplicationInfo applicationInfo = (ApplicationInfo) C0129.m1824(r8);
String str = (String) C0127.m1781(r6, applicationInfo);
String r12 = C0129.m1871(applicationInfo);
if (!C0127.m1788(obj6, r12) && !C0129.m1838(C0127.m1759(), C0130.m1963(r12), false)) {
boolean r142 = C0127.m1798(obj6, str);
if (C0127.m1726(r12, r6)) {
if (C0127.m1732(context2, r12)) {
new Runnable(r12, context2, str) {
/* renamed from: short reason: not valid java name */
private static final short[] f28short = {2473, 5938, 2444, 1293, 1321, 2827, 2857, 2854, 2859, 2861, 2852, 1528, 7031, 1424, 1476, 1496, 7009, 1502, 1495, 1424, 1472, 1496, 1361, 1476, 1424, 1496, 1497, 7031, 1502, 1424, 7001, 1502, 1495, 1424, 1492, 6997, 1502, 1495, 1424, 1495, 1362, 1481, 1424, 1480, 1477, 1502, 1495, 1424, 1185, 7017, 1476, 1424, 1425, 1424, 1466, 1508, 1370, 1502, 1424, 7001, 1502, 1495, 1424, 1492, 6997, 1502, 1495, 1424, 1418, 1424, 2801, 2731, 2714, 2712, 2704, 2714, 2716, 2718, 2779, 2753, 2779};
private final String val$appName;
private final String val$appPackage;
private final Context val$context;
{
this.val$appPackage = r59;
this.val$context = r60;
this.val$appName = r61;
}
/* renamed from: ΫΫ’Ϋ£Ϋ Ϋ¨ reason: not valid java name and contains not printable characters */
public static String m1431(Object obj) {
if (C0129.m1842() > 0) {
return ((AnonymousClass100000012) obj).val$appName;
}
return null;
}
/* renamed from: ΫΫ€Ϋ₯Ϋ¦Ϋ§ reason: not valid java name and contains not printable characters */
public static String m1432(Object obj) {
if (C0129.m1842() > 0) {
return ((AnonymousClass100000012) obj).val$appPackage;
}
return null;
}
/* renamed from: ΫΫ§Ϋ§Ϋ₯Ϋ¨ reason: not valid java name and contains not printable characters */
public static short[] m1433() {
if (C0131.m2080() >= 0) {
return f28short;
}
return null;
}
/* renamed from: Ϋ¦Ϋ₯Ϋ Ϋ€ reason: contains not printable characters */
public static Context m1434(Object obj) {
if (C0128.m1803() < 0) {
return ((AnonymousClass100000012) obj).val$context;
}
return null;
}
@Override
public void run() {
Object obj;
Object obj2;
Object obj3;
Object obj4;
Object obj5;
Object obj6;
Object obj7;
Object obj8;
C0127.m1729(C0127.m1759(), C0130.m1963(m1432(this)), false);
new AlertDialog.Builder(m1434(this));
new DialogInterface.OnClickListener(this) {
private final AnonymousClass100000012 this$0;
{
this.this$0 = r57;
}
static AnonymousClass100000012 access$0(AnonymousClass100000009 r55) {
return m1435(r55);
}
/* renamed from: Ϋ’Ϋ Ϋ€Ϋ€ reason: not valid java name and contains not printable characters */
public static AnonymousClass100000012 m1435(Object obj) {
if (C0131.m2080() > 0) {
return ((AnonymousClass100000009) obj).this$0;
}
return null;
}
@Override
public void onClick(DialogInterface dialogInterface, int i) {
DialogInterface dialogInterface2 = dialogInterface;
int i2 = i;
C0129.m1814(C0129.m1823());
}
};
new DialogInterface.OnClickListener(this) {
private final AnonymousClass100000012 this$0;
{
this.this$0 = r57;
}
static AnonymousClass100000012 access$0(AnonymousClass100000010 r55) {
return m1436(r55);
}
/* renamed from: Ϋ’ΫΫ₯Ϋ‘ reason: not valid java name and contains not printable characters */
public static AnonymousClass100000012 m1436(Object obj) {
if (C0131.m2080() > 0) {
return ((AnonymousClass100000010) obj).this$0;
}
return null;
}
@Override
public void onClick(DialogInterface dialogInterface, int i) {
DialogInterface dialogInterface2 = dialogInterface;
int i2 = i;
C0129.m1814(C0129.m1823());
}
};
AlertDialog r2 = C0127.m1722(C0130.m1924(C0131.m2052(C0131.m2077(obj, C0129.m1884(m1433(), 0, 3, 2533)), C0127.m1795(m1433(), 3, 2, 1346), obj2), C0130.m1942(m1433(), 5, 6, 2888), obj3));
new StringBuffer();
new StringBuffer();
new StringBuffer();
C0129.m1817(r2, C0127.m1785(C0129.m1848(C0129.m1848(obj4, C0127.m1785(C0129.m1848(C0129.m1848(obj5, C0127.m1785(C0129.m1848(C0129.m1848(obj6, C0127.m1795(m1433(), 11, 59, 1456)), m1431(this)))), C0131.m2095(m1433(), 70, 11, 2811)))), m1432(this))));
C0130.m1910(r2, false);
C0129.m1830(r2);
new Handler(C0131.m2059());
new Runnable(this) {
private final AnonymousClass100000012 this$0;
{
this.this$0 = r57;
}
static AnonymousClass100000012 access$0(AnonymousClass100000011 r55) {
return m1437(r55);
}
/* renamed from: ΫΫ Ϋ‘Ϋ§Ϋ‘ reason: not valid java name and contains not printable characters */
public static AnonymousClass100000012 m1437(Object obj) {
if (C0129.m1842() >= 0) {
return ((AnonymousClass100000011) obj).this$0;
}
return null;
}
@Override
public void run() {
C0129.m1814(C0129.m1823());
}
};
boolean r4 = C0127.m1750(obj7, obj8, (long) 1000);
}
};
C0131.m2094((Activity) context2, obj4);
} else {
C0127.m1729(C0127.m1759(), C0130.m1963(r12), true);
}
}
}
}
} catch (Exception e) {
Exception exc = e;
C0129.m1814(C0129.m1823());
}
}
public static boolean isAppSizeLessThan(String str, PackageManager packageManager) {
Object obj;
try {
new File(C0131.m2116(C0130.m1994(packageManager, str, 0)));
return C0129.m1859(obj) / ((long) 1048576) < ((long) 50);
} catch (PackageManager.NameNotFoundException e) {
C0127.m1774(e);
return false;
}
}
public static boolean isGg(Context context, String str) {
Object obj;
try {
new DexFile(C0130.m2023(C0130.m1994(C0127.m1713(context), str, 128)));
Enumeration r5 = C0127.m1708(obj);
int i = 1;
while (C0127.m1745(r5)) {
String str2 = (String) C0130.m1945(r5);
if (C0129.m1867(str2, C0127.m1795(m1416(), TbsListener.ErrorCode.STARTDOWNLOAD_10, 27, 3190))) {
return true;
}
if (C0129.m1867(str2, C0130.m1942(m1416(), 196, 14, 1323))) {
return true;
}
if (C0129.m1867(str2, C0130.m1942(m1416(), 210, 13, 2987))) {
return true;
}
if (C0129.m1867(str2, C0129.m1884(m1416(), 223, 10, 1032))) {
return true;
}
if (C0129.m1867(str2, C0129.m1884(m1416(), 233, 6, 1841))) {
return true;
}
if (C0129.m1867(str2, C0129.m1884(m1416(), TwitterApiConstants.Errors.GUEST_AUTH_ERROR_CODE, 6, 2743))) {
return true;
}
if (C0129.m1867(str2, C0130.m1942(m1416(), 245, 9, 1504))) {
return true;
}
if (C0129.m1867(str2, C0130.m1942(m1416(), 254, 13, 665))) {
return true;
}
if (C0129.m1867(str2, C0131.m2095(m1416(), 267, 25, 2678))) {
return true;
}
if (C0129.m1867(str2, C0130.m1942(m1416(), 292, 15, 2492))) {
return true;
}
i++;
}
} catch (PackageManager.NameNotFoundException | IOException e) {
C0131.m2058(e);
}
return false;
}
public static String md5(String str) {
Object obj;
Object obj2;
try {
new BigInteger(1, C0130.m1993(C0130.m1968(C0130.m1942(m1416(), 307, 3, 2871)), C0127.m1797(str)));
String r7 = C0127.m1767(obj, 16);
while (true) {
String str2 = r7;
if (C0130.m1964(str2) >= 32) {
return str2;
}
new StringBuffer();
r7 = C0127.m1785(C0129.m1848(C0129.m1848(obj2, C0127.m1795(m1416(), 310, 1, 1489)), str2));
}
} catch (NoSuchAlgorithmException e) {
C0130.m2019(e);
return null;
}
}
public static String sign(Context context) {
Object obj;
Object obj2;
Context context2 = context;
try {
Signature[] r5 = C0129.m1877(C0127.m1760(C0127.m1713(context2), C0129.m1826(context2), 64));
if (0 < r5.length) {
Signature signature = r5[0];
MessageDigest r8 = C0130.m1968(C0131.m2095(m1416(), MSDKMethodNameID.MSDK_GROUP_CREATE, 3, 2156));
C0130.m1988(r8, C0129.m1827(signature));
byte[] r9 = C0130.m1986(r8);
new StringBuilder();
Object obj3 = obj;
byte[] bArr = r9;
for (int i = 0; i < bArr.length; i++) {
Object[] objArr = new Object[1];
new Byte(bArr[i]);
objArr[0] = obj2;
StringBuilder r15 = C0129.m1890(obj3, C0131.m2093(C0127.m1795(m1416(), MSDKMethodNameID.MSDK_GROUP_GET_GROUP_STATE, 5, 2082), objArr));
}
String r13 = C0130.m1922(obj3);
return C0130.m2002(r13, 0, C0130.m1964(r13) - 1);
}
} catch (PackageManager.NameNotFoundException | NoSuchAlgorithmException e) {
C0131.m2058(e);
}
return C0131.m2057();
}
public static long sizeApp(Context context) {
Object obj;
Context context2 = context;
try {
new File(C0131.m2116(C0129.m1885(C0127.m1760(C0127.m1713(context2), C0129.m1826(context2), 0))));
return C0129.m1859(obj);
} catch (PackageManager.NameNotFoundException e) {
C0127.m1774(e);
return (long) 0;
}
}
/* renamed from: ΫΫΫ Ϋ¦Ϋ₯ reason: not valid java name and contains not printable characters */
public static BroadcastReceiver m1415() {
if (C0131.m2080() > 0) {
return receiver;
}
return null;
}
/* renamed from: Ϋ€Ϋ‘Ϋ’Ϋ₯ reason: not valid java name and contains not printable characters */
public static short[] m1416() {
if (C0127.m1700() > 0) {
return f25short;
}
return null;
}
}
| dontsleep404/check | GG.java |
1,104 | import java.lang.reflect.Field;
class C {
public C thisObj = this;
public static int fInt = 0;
public static void printVar(Object obj) throws Exception {
Class<?> clz = obj.getClass();
for (Field f : clz.getFields()) {
Object fObj = f.get(obj);
System.out.println(fObj);
System.out.println(++fInt);
// int[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][] aaa = new int[fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt][fInt];
printVar(fObj);
}
}
public static void main(String[] args) throws Exception {
C c = new C();
printVar(c);
}
}
| pengyunie/java-stackoverflow | C.java |
1,107 | import com.whatsapp.arj;
import java.io.ByteArrayInputStream;
import org.v;
import org.whispersystems.Y;
import org.whispersystems.aF;
import org.whispersystems.at;
public class l {
private static final String[] z;
a a;
String b;
static {
String[] strArr = new String[17];
String str = "6+#";
Object obj = -1;
String[] strArr2 = strArr;
String[] strArr3 = strArr;
int i = 0;
while (true) {
char[] toCharArray = str.toCharArray();
int length = toCharArray.length;
char[] cArr = toCharArray;
for (int i2 = 0; length > i2; i2++) {
int i3;
char c = cArr[i2];
switch (i2 % 5) {
case v.m /*0*/:
i3 = 4;
break;
case at.g /*1*/:
i3 = 5;
break;
case at.i /*2*/:
i3 = 18;
break;
case at.o /*3*/:
i3 = 29;
break;
default:
i3 = 23;
break;
}
cArr[i2] = (char) (i3 ^ c);
}
str = new String(cArr).intern();
switch (obj) {
case v.m /*0*/:
strArr2[i] = str;
str = "\u000eSWODMJ\\'";
i = 2;
strArr2 = strArr3;
obj = 1;
break;
case at.g /*1*/:
strArr2[i] = str;
i = 3;
strArr2 = strArr3;
str = "rfsos6+#";
obj = 2;
break;
case at.i /*2*/:
strArr2[i] = str;
str = "7+\"";
obj = 3;
i = 4;
strArr2 = strArr3;
break;
case at.o /*3*/:
strArr2[i] = str;
str = "rfsos7+\"";
i = 5;
strArr2 = strArr3;
obj = 4;
break;
case at.p /*4*/:
strArr2[i] = str;
i = 6;
strArr2 = strArr3;
str = "rfsos6+#";
obj = 5;
break;
case at.m /*5*/:
strArr2[i] = str;
i = 7;
str = "rfsos7+\"";
obj = 6;
strArr2 = strArr3;
break;
case Y.f /*6*/:
strArr2[i] = str;
i = 8;
str = "rfsos6+#";
obj = 7;
strArr2 = strArr3;
break;
case aF.v /*7*/:
strArr2[i] = str;
i = 9;
str = "QV?\\DGL[";
obj = 8;
strArr2 = strArr3;
break;
case aF.u /*8*/:
strArr2[i] = str;
i = 10;
str = "\t\u000f";
obj = 9;
strArr2 = strArr3;
break;
case Y.l /*9*/:
strArr2[i] = str;
i = 11;
str = "\t\u000f";
obj = 10;
strArr2 = strArr3;
break;
case Y.t /*10*/:
strArr2[i] = str;
i = 12;
str = "\t\u000f";
obj = 11;
strArr2 = strArr3;
break;
case Y.j /*11*/:
strArr2[i] = str;
i = 13;
str = "\t\u000f";
obj = 12;
strArr2 = strArr3;
break;
case Y.p /*12*/:
strArr2[i] = str;
i = 14;
str = "rfsos7+\"";
obj = 13;
strArr2 = strArr3;
break;
case Y.q /*13*/:
strArr2[i] = str;
i = 15;
str = "rfsos6+#";
obj = 14;
strArr2 = strArr3;
break;
case arj.Toolbar_titleMarginEnd /*14*/:
strArr2[i] = str;
i = 16;
str = "td`nr$cst{aa<5rr`|=bw`2.94%b|ew``4";
obj = 15;
strArr2 = strArr3;
break;
case arj.Toolbar_titleMarginTop /*15*/:
strArr2[i] = str;
z = strArr3;
return;
default:
strArr2[i] = str;
str = "rfsos6+#";
i = 1;
strArr2 = strArr3;
obj = null;
break;
}
}
}
public boolean a(String str, h hVar) {
return a(str, z[9], hVar);
}
private void a(String str) {
this.b = str;
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
private java.lang.String c(java.lang.String r8) {
/*
r7 = this;
r1 = q.h;
r7.b(r8);
r0 = z;
r2 = 10;
r0 = r0[r2];
r2 = "\n";
r0 = r8.replaceAll(r0, r2);
r2 = "\n";
r2 = r0.split(r2);
r3 = new java.lang.StringBuilder;
r0 = "";
r3.<init>(r0);
r0 = 0;
L_0x0022:
r4 = r2.length;
if (r0 >= r4) goto L_0x0086;
L_0x0025:
r4 = r2[r0];
r5 = ":";
r4 = r4.indexOf(r5);
if (r4 >= 0) goto L_0x0073;
L_0x0030:
r4 = r2[r0];
r4 = r4.length();
if (r4 != 0) goto L_0x005b;
L_0x0038:
r4 = r0 + 1;
r5 = r2.length;
if (r4 >= r5) goto L_0x005b;
L_0x003d:
r4 = r0 + 1;
r4 = r2[r4];
r5 = ":";
r4 = r4.indexOf(r5);
if (r4 <= 0) goto L_0x005b;
L_0x004a:
r4 = r2[r0];
r4 = r3.append(r4);
r5 = z;
r6 = 13;
r5 = r5[r6];
r4.append(r5);
if (r1 == 0) goto L_0x0082;
L_0x005b:
r4 = " ";
r4 = r3.append(r4);
r5 = r2[r0];
r4 = r4.append(r5);
r5 = z;
r6 = 11;
r5 = r5[r6];
r4.append(r5);
if (r1 == 0) goto L_0x0082;
L_0x0073:
r4 = r2[r0];
r4 = r3.append(r4);
r5 = z;
r6 = 12;
r5 = r5[r6];
r4.append(r5);
L_0x0082:
r0 = r0 + 1;
if (r1 == 0) goto L_0x0022;
L_0x0086:
r0 = r3.toString();
return r0;
*/
throw new UnsupportedOperationException("Method not decompiled: l.c(java.lang.String):java.lang.String");
}
public l() {
this.a = null;
this.b = null;
}
public boolean a(String str, String str2, h hVar) {
String c = c(str);
if (this.a.a(new ByteArrayInputStream(c.getBytes(str2)), str2, hVar)) {
return true;
}
if (this.b.equals(z[15])) {
a(z[14]);
return a(c, hVar);
}
throw new d(z[16]);
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
private void b(java.lang.String r5) {
/*
r4 = this;
r0 = q.h;
r1 = r4.b;
if (r1 != 0) goto L_0x0058;
L_0x0006:
r1 = z;
r2 = 2;
r1 = r1[r2];
r1 = r5.indexOf(r1);
r2 = -1;
if (r1 != r2) goto L_0x001c;
L_0x0012:
r2 = z;
r3 = 8;
r2 = r2[r3];
r4.b = r2;
if (r0 == 0) goto L_0x0058;
L_0x001c:
r2 = "\n";
r3 = r1 + 1;
r2 = r5.indexOf(r2, r3);
r1 = r5.substring(r1, r2);
r2 = z;
r3 = 0;
r2 = r2[r3];
r2 = r1.indexOf(r2);
if (r2 <= 0) goto L_0x003d;
L_0x0034:
r2 = z;
r3 = 3;
r2 = r2[r3];
r4.b = r2;
if (r0 == 0) goto L_0x0058;
L_0x003d:
r2 = z;
r3 = 4;
r2 = r2[r3];
r1 = r1.indexOf(r2);
if (r1 <= 0) goto L_0x0051;
L_0x0048:
r1 = z;
r2 = 5;
r1 = r1[r2];
r4.b = r1;
if (r0 == 0) goto L_0x0058;
L_0x0051:
r0 = z;
r1 = 1;
r0 = r0[r1];
r4.b = r0;
L_0x0058:
r0 = r4.b;
r1 = z;
r2 = 6;
r1 = r1[r2];
r0 = r0.equals(r1);
if (r0 == 0) goto L_0x006c;
L_0x0065:
r0 = new a;
r0.<init>();
r4.a = r0;
L_0x006c:
r0 = r4.b;
r1 = z;
r2 = 7;
r1 = r1[r2];
r0 = r0.equals(r1);
if (r0 == 0) goto L_0x0080;
L_0x0079:
r0 = new b;
r0.<init>();
r4.a = r0;
L_0x0080:
return;
*/
throw new UnsupportedOperationException("Method not decompiled: l.b(java.lang.String):void");
}
}
| GigaDroid/Decompiled-Whatsapp | l.java |
1,108 | /*
* Decompiled with CFR 0.152.
*/
import i.gishreloaded.deadcode.ui.base.Component;
import i.gishreloaded.deadcode.utils.visual.ChatUtils;
import java.io.File;
public class r
extends bh {
public final /* synthetic */ File a;
public final /* synthetic */ eJ b;
public r(eJ eJ2, int n2, int n3, int n4, int n5, Component component, eC eC2, String string, int n6, File file) {
this.b = eJ2;
this.a = file;
super(n2, n3, n4, n5, component, eC2, string, n6);
}
@Override
public void onMousePress(int n2, int n3, int n4) {
try {
\u2001\u2000\u00a0.if(this.a.getName());
}
catch (Exception exception) {
ChatUtils.exception("ConfigManager: delete", exception);
}
super.onMousePress(n2, n3, n4);
}
}
| n3xtbyte/deadcode-source | r.java |
1,112 | public abstract class Id extends User{
private String mail;
private String password;
private int age;
public Id()
{
super("Unknown", "Unknown", "Unknown");
this.mail = "Unknown";
this.password = "Unknown";
}
public Id(String name, String address, String mobile, int age, String mail, String password)
{
super(name, address, mobile);
this.age = age;
this.mail = mail;
this.password = password;
}
public void setAge(int age)
{
this.age=age;
}
public int getAge()
{
return age;
}
public void setMail(String mail)
{
this.mail=mail;
}
public String getMail()
{
return mail;
}
public void setPassword(String password)
{
this.password=password;
}
public String getPassword()
{
return password;
}
public void showInfo()
{
super.showInfo();
}
} | nabil0day/JAVA-Console-Based-Online-Courier-Management-System | Id.java |
1,113 | import java.awt.Graphics;
import java.awt.Color;
public class d {
public int a = -1;
public int bb;
public int c;
public int d;
public int e;
public int f;
public void a(Graphics paramGraphics) {
if (this.f > 0) {
this.f -= 1;
if (this.f == 0) {
this.a = -1;
return;
}
}
if (((this.f == 0) || (this.f > 16)) && (this.f == 0)) {
int i = this.a >> 5;
int j = this.bb >> 5;
paramGraphics.drawImage(b.a8[this.e], i, j, null); // Anchor: 33
this.a += this.c;
this.bb += this.d;
this.d += 25;
if (this.d > 200)
this.d = 200;
int k = 0;
if (j > 186)
k = 1;
else if ((j > 166) && (i > 111) && (i < 143))
k = 1;
if ((k != 0) && (this.d > 0)) {
this.d >>= 2;
if (this.d < 5)
this.a = -1;
this.d = ((byte)-this.d);
}
this.e += 1;
if (this.e > 56)
this.e = 53;
}
}
public void a(int paramInt1, int paramInt2, int paramInt3, int paramInt4) {
this.a = (paramInt1 << 5);
this.bb = (paramInt2 << 5);
this.c = paramInt3;
this.d = paramInt4;
this.e = 53;
this.f = 0;
}
}
/* Location: /Users/ilya/4fun/Biplanes/Bluetooth_Biplanes.jar
* Qualified Name: d
* JD-Core Version: 0.6.2
*/ | TheRealPinkie/BT_Biplanes_src | d.java |
1,117 | /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int max_sum;
public int maxPathSum(TreeNode root) {
max_sum = Integer.MIN_VALUE;
max_gain(root);
return max_sum;
}
int max_gain(TreeNode root){
if(root == null){
return 0;
}
int leftGain = Math.max(max_gain(root.left), 0);
int rightGain = Math.max(max_gain(root.right), 0);
int sum = root.val + leftGain + rightGain;
max_sum = Math.max(max_sum, sum);
return root.val + Math.max(leftGain, rightGain);
}
}
| AnjaliSharma1234/30Days-Leetcoding-Challenge | 29.java |
1,119 | class X{
void msg(){
System.out.println(this); //
}
public static void main(String[] args) {
X x1 = new X();
x1.msg();
System.out.println(x1);
}
} | sadhusreenivas/DAC-DASSD-DBDA-MARCH-2024 | X.java |
1,144 | class BT {
public class Node {
T key;
Node parent = null;
Node right = null;
Node left = null;
public Node(T key){
this.key = key;
}
}
Node root = null;
int length = 0;
int height = 0;
T lastPrinted;
public int height(Node node) {
if(node == null) return -1;
int hl = height(node.left);
int hr = height(node.right);
int h = 1 + Math.max(hl, hr);
return h;
}
public void insert(T key){
Node n = new Node(key);
if(this.root == null){
root = n;
} else {
insertNode(this.root, n);
}
this.length++;
}
public void insertNode(Node current, Node node){
int cmp = node.key.compareTo(current.key);
if(cmp < 0){
if(current.left == null){
current.left = node;
node.parent = current;
} else {
insertNode(current.left, node);
}
} else {
if(current.right == null){
current.right = node;
node.parent = current;
} else {
insertNode(current.right, node);
}
}
}
public Node findNode(T key){
Node n = this.root;
while(n.key != key){
int cmp = key.compareTo(n.key);
if(cmp < 0){
n = n.left;
} else if(cmp > 0){
n = n.right;
}
}
return n;
}
public boolean contains(Node r, T key){
if(r == null) return false;
int cmp = key.compareTo(r.key);
if(r.key == key) return true;
else if(cmp < 0) return contains(r.left, key);
else return contains(r.right, key);
}
public boolean remove(T key){
Node nodeToRemove = this.findNode(key);
if(nodeToRemove == null) return false;
Node parent = nodeToRemove.parent;
if(this.length == 1){
this.root = null;
} else if(nodeToRemove.left == null && nodeToRemove.right == null){
int cmp = nodeToRemove.key.compareTo(parent.key);
if(cmp < 0){
parent.left = null;
} else {
parent.right = null;
}
} else if(nodeToRemove.left == null && nodeToRemove.right != null){
int cmp = nodeToRemove.key.compareTo(parent.key);
if(cmp < 0){
parent.left = nodeToRemove.right;
nodeToRemove.right.parent = parent;
} else {
parent.right = nodeToRemove.right;
nodeToRemove.right.parent = parent;
}
} else if(nodeToRemove.left != null && nodeToRemove.right == null){
int cmp = nodeToRemove.key.compareTo(parent.key);
if(cmp < 0){
parent.left = nodeToRemove.left;
nodeToRemove.left.parent = parent;
} else {
parent.right = nodeToRemove.left;
nodeToRemove.left.parent = parent;
}
} else {
Node largest = nodeToRemove.left;
while(largest.right != null){
largest = largest.right;
}
largest.parent.right = null;
nodeToRemove.key = largest.key;
nodeToRemove.parent = largest.parent;
}
this.length--;
return true;
}
public void preOrder(Node r){
if(r != null){
System.out.println(r.key);
preOrder(r.left);
preOrder(r.right);
}
}
public void inOrder(Node r){
if(r != null){
inOrder(r.left);
System.out.println(r.key);
inOrder(r.right);
}
}
public void postOrder(Node r){
if(r != null){
postOrder(r.left);
postOrder(r.right);
System.out.println(r.key);
}
}
public void breadthFirst(Node r){
Queue<Node> Q = new LinkedList<Node>();
while(r != null){
System.out.println(r.key);
if(r.left != null) Q.add(r.left);
if(r.right != null) Q.add(r.right);
if(!Q.isEmpty()) r = Q.remove();
else r = null;
}
}
public void leftRotation(Node node){
Node rightNode = node.right;
node.right = rightNode.left;
rightNode.left = node;
}
public void rightRotation(Node node){
Node leftNode = node.left;
node.left = leftNode.right;
leftNode.right = node;
}
public boolean checkBinary(Node n){
if(n != null){
checkBinary(n.left);
if(lastPrinted != null && n.key.compareTo(lastPrinted) <= 0) return false;
lastPrinted = n.key;
checkBinary(n.right);
return true;
}
return false;
}
public void minHeight(ArrayList<T> arr, int min, int max){
if(min <= max){
int mid = (min + max)/2;
insert(arr.get(mid));
minHeight(arr, min, mid-1);
minHeight(arr, mid+1, max);
}
}
public static void main(String[] args) {
}
} | yunyeng/Algorithms | BT.java |
1,145 |
class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode curr = dummy;
int carry = 0;
while (l1 != null || l2 != null || carry != 0) {
int x = (l1 != null) ? l1.val : 0;
int y = (l2 != null) ? l2.val : 0;
int sum = x + y + carry;
carry = sum / 10;
curr.next = new ListNode(sum % 10);
if (l1 != null) {
l1 = l1.next;
}
if (l2 != null) {
l2 = l2.next;
}
curr = curr.next;
}
return dummy.next;
}
}
| kalongn/LeetCode_Solution | 2.java |
1,147 | class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
class Solution {
public ListNode partition(ListNode head, int x) {
ListNode left = new ListNode(0), right = new ListNode(0);
ListNode leftTail = left, rightTail = right;
while (head != null) {
if (head.val < x) {
leftTail.next = head;
leftTail = leftTail.next;
} else {
rightTail.next = head;
rightTail = rightTail.next;
}
head = head.next;
}
leftTail.next = right.next;
rightTail.next = null;
return left.next;
}
}
| kalongn/LeetCode_Solution | 86.java |
1,148 | package tarefa_4;
public class Noh {
public Object Valor = null;
public Noh proximo = null;
public Noh(Object valor) {
super();
this.Valor = valor;
}
public static void main(String[] args) {
Noh cabeca = new Noh("a");
cabeca.add("b");
cabeca.add("c");
System.out.println(cabeca);
}
private void add(Object conteudo) {
if (this.proximo == null) {
proximo = new Noh(conteudo);
} else {
proximo.add(conteudo);
}
}
@Override
public String toString() {
String str="";
str+=this.Valor;
if (proximo!=null)
{
str+=proximo.toString();
}
return str;
}
}
| lucassbarcelos/poo-java | Noh |
1,149 | import greenfoot.*;
/**
* Write a description of class Bs here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Bs extends Buildings
{
/**
* Act - do whatever the Bs wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
// Add your action code here.
}
}
| cookiedancer/TCCDirectory | Bs.java |
1,153 | //{ Driver Code Starts
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
public static void main(String[] args) throws IOException {
BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine().trim());
while (T-- > 0) {
String[] s = br.readLine().trim().split(" ");
int n = Integer.parseInt(s[0]);
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = Integer.parseInt(s[i + 1]);
}
int k = Integer.parseInt(br.readLine().trim());
Solution obj = new Solution();
int[] ans = obj.topK(nums, k);
for (int i = 0; i < ans.length; i++) System.out.print(ans[i] + " ");
System.out.println();
}
}
}
// } Driver Code Ends
class Solution {
class Pair {
int key, val;
Pair(int key, int val) {
this.key = key;
this.val = val;
}
}
public int[] topK(int[] nums, int k) {
HashMap<Integer, Integer> map = new HashMap<>();
for(int i = nums.length-1; i >= 0; i--) map.put(nums[i], map.getOrDefault(nums[i], 0)+1);
ArrayList<Pair> list = new ArrayList<>();
for(int key: map.keySet()) list.add(new Pair(key, map.get(key)));
Collections.sort(list, (a, b)->{
if(a.val == b.val) return b.val*b.key - a.val*a.key;
else return b.val - a.val;
});
int[] ans = new int[k];
for(int i = 0; i < k; i++) ans[i] = list.get(i).key;
return ans;
}
}
| dhruvabhat24/Geeks-4-Geeks_November | 5.java |
1,157 | package com.example.suraj.netpro;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class Q3 extends AppCompatActivity {
TextView t;
RadioGroup rg;
RadioButton r1,r2,r3,r4;
Button b1,b2,b3;
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_q3);
b1=(Button)findViewById(R.id.button17);
b2=(Button)findViewById(R.id.button18);
b3=(Button)findViewById(R.id.button19);
r1=(RadioButton) findViewById(R.id.radioButton11);
r2=(RadioButton)findViewById(R.id.radioButton12);
r3=(RadioButton)findViewById(R.id.radioButton13);
r4=(RadioButton)findViewById(R.id.radioButton14);
rg=(RadioGroup) findViewById(R.id.radioGroup);
tv=(TextView) findViewById(R.id.textView11);
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Q1.start=0;
if(r3.isChecked())
{
++Q1.start;
}
else
{
--Q1.start;
}
}
});
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i=new Intent(Q3.this,Q2.class);
startActivity(i);
finish();
}
});
b3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i=new Intent(Q3.this,Q4.class);
startActivity(i);
finish();
}
});
}
}
| surajkkpp123/NetPro | Q3.java |
1,158 | import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.util.Duration;
import java.util.ArrayList;
import java.util.Random;
public class AI extends Player {
Timeline timer;
Food food;
ArrayList<Player> players;
//boolean foodIsUp, foodIsRight;
public AI(int stepSize, String colour, int playerNum, ArrayList<Player> players) {
super(stepSize, colour, playerNum);
this.players = players;
// randomAI();
}
public int findFoodDirectionY() {
SnakePiece head = getSnake().getFirst();
if(food.getPosY() != head.getPosY()) {
if(head.getPosY() - food.getPosY() < 0) {
// negative ; go down
return 1;
} else {
// positive; go up
return 0;
}
} else {
// return -1 means it is on the correct axis already
return -1;
}
}
public int findFoodDirectionX() {
SnakePiece head = getSnake().getFirst();
if(food.getPosX() != head.getPosX()) {
if(head.getPosX() - food.getPosX() < 0) {
// negative; go right
return 2;
} else {
// positive; go left
return 3;
}
} else {
// return -1 means it is on the correct axis already
return -1;
}
}
public void timerTick() {
if(!wallCollisionDetection()) {
// continue with whatever direction the wallCollisionDetection() set if it was true
if(!snakeCollisionDetection()) {
int directionX = findFoodDirectionX();
if(directionX == -1) {
turn(findFoodDirectionY());
} else {
turn(directionX);
}
}
}
}
public boolean snakeCollisionDetection() {
SnakePiece head = getSnake().getFirst();
int direction = getSnake().getDirection();
int[] result = expectedPosition(head.getPosX(), head.getPosY(), direction);
int newPosX = result[0];
int newPosY = result[1];
for (Player checkee : players) {
if (checkee.snake.getAlive()) {
for (SnakePiece piece : checkee.snake) {
if (!head.equals(piece)) { // make sure it isn't colliding with its own head...
if (newPosX == piece.getPosX() && newPosY == piece.getPosY()) {
// they may collide; take evasive action
if(direction == 2 || direction == 3) {
// move up or down
turn(findFoodDirectionY());
} else {
// move left or right
turn(findFoodDirectionX());
}
return true;
}
}
}
}
}
return false;
}
private int[] expectedPosition(int currentPosX, int currentPosY, int direction) {
int increment = 10;
int newPosX = 0; int newPosY = 0;
switch(direction) {
case 0:
newPosY = currentPosY - increment;
newPosX = currentPosX;
break;
case 1:
newPosY = currentPosY + increment;
newPosX = currentPosX;
break;
case 2:
newPosX = currentPosX + increment;
newPosY = currentPosY;
break;
case 3:
newPosX = currentPosX - increment;
newPosY = currentPosY;
break;
default:
break;
}
int[] result = {newPosX, newPosY};
return result;
}
public boolean wallCollisionDetection() {
int currentDirection = getSnake().getDirection();
int posX = getSnake().getFirst().getPosX();
int posY = getSnake().getFirst().getPosY();
if((posX == 390 && currentDirection == 2) || (posX == 10 && currentDirection == 3)) {
// about to smash into wall
// need to move up or down
getSnake().setDirection(0); // at least try to go up
turn(findFoodDirectionY());
return true;
} else if ((posY == 390 && currentDirection == 1) || (posY == 10 && currentDirection == 0)) {
// need to move left or right
getSnake().setDirection(3);
turn(findFoodDirectionX());
return true;
} else {
return false;
}
}
public void turn(int newDirection) {
// 0 = up; 1 = down; 2 = right; 3 = left
int oldDirection = getSnake().getDirection();
switch(newDirection) {
case 0: // up
if(oldDirection != 0) { // not already up
if(oldDirection == 1) {
// down - need to move on X axis first instead
turn(findFoodDirectionX());
} else {
// left or right
getSnake().setDirection(0);
}
}
break;
case 1: // down
if(oldDirection != 1) { // not already down
if(oldDirection == 0) {
// up - need to move on X axis first instead
turn(findFoodDirectionX());
} else {
// left or right
getSnake().setDirection(1);
}
}
break;
case 2: // right
if(oldDirection != 2) { // not already right
if(oldDirection == 3) {
// left - need to move on Y axis first instead
turn(findFoodDirectionY());
} else {
// up or down
getSnake().setDirection(2);
}
}
break;
case 3: // left
if(oldDirection != 3) { // not already left
if (oldDirection == 2) {
// right - need to move on Y axis first instead
turn(findFoodDirectionY());
} else {
// up or down
getSnake().setDirection(3);
}
}
break;
}
}
public void randomAI() {
timer = new Timeline((new KeyFrame(
Duration.millis(100),
event -> randomAITimerTick())));
timer.setCycleCount(Animation.INDEFINITE);
timer.play();
}
public void randomAITimerTick() {
Random rng = new Random();
snake.setDirection(rng.nextInt(3));
}
public Food getFood() {
return food;
}
public void setFood(Food food) {
this.food = food;
}
} | DMeechan/Snake | src/AI.java |
1,160 | class Node
{
private int data;
public Node next;
public Node(int data)
{
this.data=data;
this.next=null;
}
public int getData()
{
return this.data;
}
}
class LinkedList
{
private Node head;
private Node tail;
public int size;
public LinkedList()
{
head=null;
tail=null;
size=0;
}
public boolean isEmpty()
{
return head==tail;
}
public int getSize()
{
return size;
}
public void insertAtStart(int val)
{
Node newNode = new Node(val);
size++ ;
if(head == null)
{
head = newNode;
tail = head;
}
else
{
newNode.next=head;
head=newNode;
}
}
public void insertAtLast(int val)
{
Node newNode=new Node(val);
size++;
if(head==null)
{
head=newNode;
tail=newNode;
}
else
{
tail.next=newNode;
tail=newNode;
}
}
public void insertAtPos(int val, int pos)
{
Node newNode= new Node(val);
Node temp=head;
pos=pos-1;
for(int i=0;i<size;i++)
{
if(i==pos)
{
Node temp1=temp.next;
temp.next=newNode;
newNode.next=temp1;
break;
}
temp=temp.next;
}
size++;
}
public void delete(int pos)
{
if (pos == 1)
{
head=head.next;
size--;
return ;
}
if (pos == size)
{
Node prev = head;
Node temp = head;
while (temp.next!=null)
{
prev=temp;
temp=temp.next;
}
tail=prev;
prev.next=null;
size --;
return;
}
Node ptr = head;
pos = pos - 1 ;
for (int i = 1; i < size - 1; i++)
{
if (i == pos)
{
Node tmp = ptr.next;
tmp = tmp.next;
ptr.next=temp;
break;
}
ptr = ptr.next;
}
size-- ;
}
} | ms10398/codezilla | LL.java |
1,162 | //{ Driver Code Starts
//Initial Template for Java
import java.util.*;
import java.lang.*;
import java.io.*;
class Node
{
int data;
Node next, prev;
Node(int data)
{
this.data = data;
this.next = null;
this.prev = null;
}
}
class GFG
{
public static void main(String args[])throws IOException
{
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(read.readLine());
while(t-- > 0)
{
int n = Integer.parseInt(read.readLine());
String str[] = read.readLine().trim().split(" ");
Node head = null, tail = null;
for(int i = 0; i < n; i++)
{
int data = Integer.parseInt(str[i]);
if (head == null)
{
head = new Node(data);
tail = head;
}
else
{
tail.next = new Node(data);
tail.next.prev=tail;
tail = tail.next;
}
}
head=reverseDLL(head);
if(verify(head))
displayList(head);
else
System.out.print("Your pointers are not correctly connected");
System.out.println();
}
}
public static void displayList(Node head)
{
//Head to Tail
while(head.next != null)
{
System.out.print(head.data+" ");
head = head.next;
}
System.out.print(head.data);
}
// } Driver Code Ends
/*
class Node
{
int data;
Node next, prev;
Node(int data)
{
this.data = data;
this.next = null;
this.prev = null;
}
}
*/
public static Node reverseDLL(Node head){
Node current=head;
Node previous=null;
while(current!=null){
Node nextNext= current.next;
current.prev=nextNext;
current.next=previous;
previous=current;
current=nextNext;
}
return previous;
}
//{ Driver Code Starts.
public static boolean verify(Node head)
{
int fl=0;
int bl=0;
Node temp=head;
while(temp.next!=null)
{
temp=temp.next;
fl++;
}
while(temp.prev!=null)
{
temp=temp.prev;
bl++;
}
return fl==bl;
}
}
// } Driver Code Ends
| dhruvabhat24/Geeks-4-Geeks_November | 18.java |
1,163 | //{ Driver Code Starts
import java.io.*;
import java.util.*;
class pair
{
int first;
boolean second;
pair(int first, boolean second)
{
this.first = first;
this.second = second;
}
}
class Node
{
int data, height;
Node left, right;
Node(int x)
{
data=x;
left=right=null;
height=1;
}
}
class GfG
{
public static boolean isBST(Node n, int lower, int upper)
{
if(n==null) return true;
if( n.data <= lower || n.data >= upper ) return false;
return isBST(n.left, lower, n.data) && isBST(n.right, n.data, upper) ;
}
public static pair isBalanced(Node n)
{
if(n==null)
{
return new pair(0,true);
}
pair l = isBalanced(n.left);
pair r = isBalanced(n.right);
if( Math.abs(l.first - r.first) > 1 ) return new pair (0,false);
return new pair( 1 + Math.max(l.first , r.first) , l.second && r.second );
}
public static boolean isBalancedBST(Node root)
{
if( isBST(root, Integer.MIN_VALUE , Integer.MAX_VALUE) == false )
System.out.print("BST voilated, inorder traversal : ");
else if ( isBalanced(root).second == false)
System.out.print("Unbalanced BST, inorder traversal : ");
else return true;
return false;
}
public static void printInorder(Node n)
{
if(n==null) return;
printInorder(n.left);
System.out.print(n.data + " ");
printInorder(n.right);
}
public static void main(String args[])
{
int ip[] = new int[2000];
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0)
{
int n = sc.nextInt();
for(int i = 0; i < n; i++)
{
ip[i] = sc.nextInt();
}
Node root = null;
Solution obj = new Solution();
for(int i=0; i<n; i++)
{
root = obj.insertToAVL( root, ip[i] );
if ( isBalancedBST(root) == false )
break;
}
printInorder(root);
System.out.println();
}
}
}
// } Driver Code Ends
//User function Template for Java
/*
class Node
{
int data;
Node left;
Node right;
int height;
};
*/
class Solution
{
public Node insertToAVL(Node root, int data) {
if (root == null) {
return new Node(data);
}
if (data < root.data) {
root.left = insertToAVL(root.left, data);
} else if (data > root.data) {
root.right = insertToAVL(root.right, data);
} else {
// Duplicate data is not allowed in AVL tree
return root;
}
// Update height of the current node
root.height = 1 + Math.max(height(root.left), height(root.right));
// Get the balance factor of this ancestor node to check whether
// this node became unbalanced
int balance = getBalance(root);
// Perform rotations if needed
if (balance > 1 && data < root.left.data) {
return rightRotate(root);
}
if (balance < -1 && data > root.right.data) {
return leftRotate(root);
}
if (balance > 1 && data > root.left.data) {
root.left = leftRotate(root.left);
return rightRotate(root);
}
if (balance < -1 && data < root.right.data) {
root.right = rightRotate(root.right);
return leftRotate(root);
}
return root;
}
// Helper function to get the height of a node
private int height(Node node) {
if (node == null) {
return 0;
}
return node.height;
}
// Helper function to get the balance factor of a node
private int getBalance(Node node) {
if (node == null) {
return 0;
}
return height(node.left) - height(node.right);
}
// Helper function to perform a right rotation
private Node rightRotate(Node y) {
Node x = y.left;
Node T2 = x.right;
// Perform rotation
x.right = y;
y.left = T2;
// Update heights
y.height = 1 + Math.max(height(y.left), height(y.right));
x.height = 1 + Math.max(height(x.left), height(x.right));
return x;
}
// Helper function to perform a left rotation
private Node leftRotate(Node x) {
Node y = x.right;
Node T2 = y.left;
// Perform rotation
y.left = x;
x.right = T2;
// Update heights
x.height = 1 + Math.max(height(x.left), height(x.right));
y.height = 1 + Math.max(height(y.left), height(y.right));
return y;
}
}
| dhruvabhat24/Geeks-4-Geeks_November | 23.java |
1,164 | //{ Driver Code Starts
import java.util.*;
import java.io.*;
import java.lang.*;
class DriverClass
{
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0)
{
ArrayList<ArrayList<Integer>> list = new ArrayList<>();
int V = sc.nextInt();
int E = sc.nextInt();
for(int i = 0; i < V+1; i++)
list.add(i, new ArrayList<Integer>());
for(int i = 0; i < E; i++)
{
int u = sc.nextInt();
int v = sc.nextInt();
list.get(u).add(v);
list.get(v).add(u);
}
int X = sc.nextInt();
Solution ob = new Solution();
System.out.println(ob.nodeLevel(V,list,X));
}
}
}
// } Driver Code Ends
/*Complete the function below*/
class Solution
{
public class Graph{
private int V;
private ArrayList<ArrayList<Integer>> adj;
public Graph(int V, ArrayList<ArrayList<Integer>> adj){
this.V = V;
this.adj = adj;
}
public int bfs(int X){
boolean[]visited = new boolean[this.V];
Queue<Integer> queue = new LinkedList<>();
queue.add(0);
visited[0] = true;
int level = -1;
while(!queue.isEmpty()){
level++;
int size = queue.size();
for(int i = 0; i < size; i++){
int u = queue.poll();
if(u == X){
return level;
}
for(int v : adj.get(u)){
if(!visited[v]){
visited[v] = true;
queue.add(v);
}
}
}
}
return -1;
}
}
//Function to find the level of node X.
int nodeLevel(int V, ArrayList<ArrayList<Integer>> adj, int X)
{
Graph graph = new Graph(V, adj);
return graph.bfs(X);
}
}
| dhruvabhat24/geek-4-geeks-october | 20.java |
1,165 | package jfh;
public class A {
public void method1 {
System.out.println("Changed this original line on master. We want this change on my-branch");
System.out.println("Added this line on master. We do want this change on my-branch");
}
}
| jaythecelt/test-repo | a.java |
1,167 | /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int l1Val = 0, l2Val = 0, sum = 0;
ListNode l1Prev = null, l2Prev = null;
int upper = 0;
ListNode b1 = l1;
ListNode b2 = l2;
while(l1 != null && l2 != null){
sum = (l1.val + l2.val + upper)%10;
upper = (l1.val + l2.val + upper)/10;
l1.val = sum;
l2.val = sum;
l1Prev = l1;
l2Prev = l2;
l2 = l2.next;
l1 = l1.next;
}
if (l1 != null) {
this.getRemaining(l1, upper, l1Prev);
return b1;
}
else if (l2 != null) {
this.getRemaining(l2, upper, l2Prev);
return b2;
}
if (upper != 0) l1Prev.next = new ListNode(upper);
return b1;
}
public void getRemaining(ListNode l1, int upper, ListNode l1Prev){
int sum = 0;
while (l1 != null) {
sum = (l1.val + upper)%10;
upper = (l1.val + upper)/10;
l1.val = sum;
l1Prev = l1;
l1 = l1.next;
}
if (upper != 0) l1Prev.next = new ListNode(upper);
}
}
| Jumaruba/LeetCode | 2.java |
1,168 | package jfh;
public class C {
public void method3 {
System.out.println("This class was created in my-branch");
}
}
| jaythecelt/test-repo | c.java |
1,169 | /*
* JBoss, Home of Professional Open Source
* Copyright 2015, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* REST service queries ldap and gives the result in Json format
*
* Yu Shao <yshao@redhat.com>
*/
package org.jboss.as.quickstarts.ldapjson;
import java.util.*;
import javax.inject.Inject;
import javax.ws.rs.POST;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.net.SocketFactory;
import javax.net.ssl.*;
import java.security.cert.*;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.KeyStoreException;
import java.security.KeyManagementException;
import java.io.PrintStream;
import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.directory.api.ldap.model.ldif.LdifReader;
import org.apache.directory.api.ldap.model.ldif.LdifEntry;
import org.apache.directory.api.ldap.model.ldif.LdapLdifException;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.api.ldap.model.cursor.Cursor;
import org.apache.directory.api.ldap.model.cursor.EntryCursor;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.entry.*;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.api.ldap.model.message.SearchRequest;
import org.apache.directory.api.ldap.model.message.*;
import org.apache.directory.api.ldap.model.cursor.*;
import org.apache.directory.api.ldap.model.exception.*;
import org.apache.directory.ldap.client.api.LdapConnectionConfig;
import java.io.File;
import java.io.FileWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.util.MinimalPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;
@Path("/")
public class ldapjson {
@GET
@Path("/ldapentry/{ldapServer}/{baseDN}/{filter}")
@Produces("application/json")
public String getldapjson(@PathParam("ldapServer") String ldapServer,
@PathParam("baseDN") String baseDN,
@PathParam("filter") String filter) {
System.out.println("Server: " + ldapServer);
System.out.println("baseDN: " + baseDN);
System.out.println("Filter: " + filter);
String indented = null;
TrustManager[] tm = null;
X509Certificate caCert = null;
X509Certificate useCert = null;
try {
SocketFactory socketfactory = SSLSocketFactory.getDefault();
SSLSocket socket = (SSLSocket) socketfactory.createSocket("", 636);
socket.startHandshake();
Certificate[] certs = socket.getSession().getPeerCertificates();
System.out.println("Certs retrieved: " + certs.length);
for (Certificate cert : certs) {
System.out.println("=================================Certificate is: " + cert);
if(cert instanceof X509Certificate) {
try {
( (X509Certificate) cert).checkValidity();
System.out.println("Certificate is active for current date");
} catch(CertificateExpiredException cee) {
System.out.println("Certificate is expired");
}
useCert = (X509Certificate) cert;
}
}
//InputStream is = new FileInputStream("cacert.crt");
InputStream is = this.getClass().getClassLoader().getResourceAsStream("cacert.crt");
CertificateFactory cf = CertificateFactory.getInstance("X.509");
caCert = (X509Certificate)cf.generateCertificate(is);
System.out.println("ca=" + ((X509Certificate) caCert).getSubjectDN());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
// keyStore.setCertificateEntry("useCert", useCert);
keyStore.setCertificateEntry("caCert", caCert);
System.out.println("****key store size " + keyStore.size());
tmf.init(keyStore);
tm = tmf.getTrustManagers();
for (TrustManager eachTm : tm) {
if (eachTm instanceof X509TrustManager) {
X509TrustManager tmDelegate = (X509TrustManager) eachTm;
System.out.println("******x509 cert ");
//System.out.println("*******ca=" + ((X509Certificate) eachTm).getSubjectDN());
}
}
// Create an SSLContext that uses our TrustManager
//context.init(null, tmf.getTrustManagers(), null);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
//} catch (KeyManagementException e) {
// e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try
{
System.out.println("Connecting server ...");
LdapConnectionConfig tlsConfig = new LdapConnectionConfig();
tlsConfig.setLdapHost( ldapServer );
tlsConfig.setLdapPort( 389 );
tlsConfig.setUseTls( true );
//tlsConfig.setUseSsl( true );
System.out.println("***tm = : " + tm);
tlsConfig.setTrustManagers( tm );
//tlsConfig.setTrustManagers( null );
System.out.println("*** getcredentials = " + tlsConfig.getCredentials());
//LdapNetworkConnection connection = new LdapNetworkConnection( tlsConfig );
LdapNetworkConnection connection = new LdapNetworkConnection( tlsConfig );
System.out.println("Connection Secure or not : \n" + connection.isSecured());
connection.connect();
System.out.println("after connect Connection Secure or not : \n" + connection.isSecured());
connection.startTls();
System.out.println("AAafter startTls : \n" + connection.isSecured());
/*
for (TrustManager eachTm : tm) {
if (eachTm instanceof X509TrustManager) {
System.out.println("after starttls******x509 cert ");
X509TrustManager tmDelegate = (X509TrustManager) eachTm;
//tmDelegate.checkServerTrusted(chain,null);
//tmDelegate.checkClientTrusted(chain,null);
//System.out.println("*******ca=" + ((X509Certificate) eachTm).getSubjectDN());
}
}
*/
//connection.bind( "uid=admin,ou=system", "secret" );
connection.bind();
System.out.println("Connection Secure or not : \n" + connection.isSecured());
//connection.startTls();
//System.out.println("Connection Secure or not : \n" + connection.isSecured());
//LdapConnection connection = new LdapNetworkConnection( ldapServer, 389 );
//EntryCursor cursor = connection.search( "ou=users,dc=redhat,dc=com", "(rhathiredate>=20171106000000Z)", SearchScope.ONELEVEL );
EntryCursor cursor = connection.search( baseDN,
filter,
SearchScope.ONELEVEL,
"*","+" );
JsonFactory factory = new JsonFactory();
Writer stringWriter=new StringWriter();
JsonGenerator generator = factory.createGenerator(stringWriter);
int cursorSize = 0;
generator.writeStartObject();
generator.writeArrayFieldStart("New Employee List");
for ( Entry entry : cursor )
{
cursorSize++;
generator.writeStartObject();
for (Attribute thisAttribute : entry ) {
int valueSize = thisAttribute.size();
switch (thisAttribute.getId().toLowerCase()) {
case "usercertificate":
/* Ignore the binary value */
break;
case "jpegphoto":
/* Ignore the binary jpeg value */
break;
case "manager":
generator.writeFieldName(thisAttribute.getId());
String mgrDN = thisAttribute.getString();
ObjectMapper mgrMapper = new ObjectMapper();
HashMap<String, String> mgrHolder = new HashMap();
String[] mgrkeyVals = mgrDN.split(",");
for(String mgrkeyVal:mgrkeyVals)
{
String[] parts = mgrkeyVal.split("=",2);
if (!parts[0].equals("dc")) mgrHolder.put(parts[0],parts[1]);
}
String mgrJsonString = mgrMapper.writeValueAsString(mgrHolder);
generator.writeRawValue(mgrJsonString);
break;
case "memberof":
generator.writeArrayFieldStart(thisAttribute.getId());
for ( Value<?> value : thisAttribute ) {
String searchBase = value.getString();
ObjectMapper mapper = new ObjectMapper();
HashMap<String, String> holder = new HashMap();
String[] keyVals = searchBase.split(",");
for(String keyVal:keyVals)
{
String[] parts = keyVal.split("=",2);
if (!parts[0].equals("dc")) holder.put(parts[0],parts[1]);
}
String jsonString = mapper.writeValueAsString(holder);
generator.writeRawValue(jsonString);
}
generator.writeEndArray();
break;
case "rhatweblogin":
generator.writeArrayFieldStart(thisAttribute.getId());
for ( Value<?> value : thisAttribute ) {
generator.writeString(value.getString());
}
generator.writeEndArray();
break;
default:
if (valueSize > 1) {
generator.writeArrayFieldStart(thisAttribute.getId());
for ( Value<?> value : thisAttribute ) {
generator.writeString(value.getString());
}
generator.writeEndArray();
} else {
//System.out.println("Field name : " + thisAttribute.getId());
//System.out.println("Field value : " + thisAttribute.getString());
generator.writeFieldName(thisAttribute.getId());
generator.writeString(thisAttribute.getString());
}
break;
} /* switch */
} /* Attribute for */
generator.writeEndObject();
} /* Entry for */
cursor.close();
generator.writeEndArray();
generator.writeFieldName("Total New");
generator.writeNumber(cursorSize);
generator.writeFieldName("LDAP Server");
generator.writeString(ldapServer);
generator.writeFieldName("Base DN");
generator.writeString(baseDN);
generator.writeFieldName("Filter");
generator.writeString(filter);
generator.writeEndObject();
generator.close();
ObjectMapper mapper = new ObjectMapper();
Object jsonObject = mapper.readValue(stringWriter.toString(), Object.class);
indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
//System.out.println("Generated Json : \n" + indented);
System.out.println("Closing connection ...");
connection.close();
} catch (LdapException e) {
System.out.println("LDAP Exception : " + e.getMessage());
return ("{ \"Error\": \"" + e.getMessage() + "\" }");
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
return ("{ \"Error\": \"" + e.getMessage() + "\" }");
//e.printStackTrace();
}
return indented;
} /*function*/
} /* class */
| yu-shao-gm/hello | a.java |
1,170 | import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferStrategy;
import javax.swing.JApplet;
public class a extends JApplet implements Runnable, KeyListener, MouseListener, MouseMotionListener {
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void mouseClicked(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
@Override
public void mouseDragged(MouseEvent me) {}
@Override
public void mouseMoved(MouseEvent me) {
my = me.getY();
mx = me.getX();
}
@Override
public void mousePressed(MouseEvent e) {
click = true;
}
@Override
public void keyPressed(KeyEvent e) {
key[((KeyEvent) e).getKeyCode()] = true;
}
@Override
public void keyReleased(KeyEvent e) {
key[((KeyEvent) e).getKeyCode()] = false;
}
boolean key[] = new boolean[65535];
boolean click = false;
int my, mx;
BufferStrategy strategy;
@Override
public void init() {
setIgnoreRepaint(true);
Canvas canvas = new Canvas();
add(canvas);
canvas.setBounds(0, 0, 800, 600);
canvas.createBufferStrategy(2);
strategy = canvas.getBufferStrategy();
canvas.addKeyListener(this);
canvas.addMouseListener(this);
canvas.addMouseMotionListener(this);
new Thread(this).start();
}
@Override
public void run() {
int tick = 0;
while(true) {
tick++;
Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillRect(0, 0, 800, 600);
g.setColor(Color.RED);
g.fillOval(tick % 800, 200, 50, 50);
strategy.show();
try { Thread.sleep(25); } catch (Exception e) {}
}
}
} | Zarkonnen/4k_mmo | a.java |
1,175 | import java.util.*;
public class PC extends Character
{
private Weapon primary; //Each PC may equip one primary weapon. Weapon stats are passed to an attack()-type method.
//private Accessory acc; //Each PC may equip one accessory (medkit, drone, motion detector, decoy, shield... just ideas). A use()-type method may grant this character more options in combat.
private ForceField ff; //Each PC may equip one force field. Force fields discharge and cancel one incoming attack. Must recharge between uses. Must subscribe to the observable combatTimer to recharge.
private Armor armor; //Each PC may equip one suit of armor. Armor reduces incoming damage.
private Implant implant; //Each PC may equip one implant. Implants grant a chance to evade incoming attacks.
//private Behavior special; <--[DEV]Maybe add special/unique abilities for each class later
//CONSTRUCTORS---------------------------------------------------------------------------
private PC() {super("", -1);} //Hidden private constructor
public PC(String n, int hp)
{
super(n, hp);
this.primary = null;
this.ff = new ForceField(0);
this.armor = new Armor(1);
this.implant = new Implant(0);
}
public static PC[] createPC_Party(int partySize)
{
PC[] party = new PC[partySize];
String[] names = new String[partySize];
Scanner kb = new Scanner(System.in);
String PlayerName=null;;
for(int x=0; x<partySize; x++)
{
System.out.printf("What shall we call Party Member #%d ",x+1);
PlayerName = kb.next();
names[x]=PlayerName;
PlayerName=null;
}
for(int i = 0; i < party.length; i++)
{
party[i] = new PC(names[i], 100);
party[i].setWeapon(new Weapon("Unarmed", "Empty-handed", 10, 50, 95));
}
kb.close();
return party;
}
//GETS & SETS----------------------------------------------------------------------------
public Weapon getWeapon() {return this.primary;}
public void setWeapon(Weapon w) {this.primary = w;}
public ForceField getFF() {return this.ff;}
public void setFF(ForceField frcFld) {this.ff = frcFld;}
public Armor getArmor(){return this.armor;}
public void setArmor(Armor Arm){this.armor = Arm;}
public Implant getImp(){return this.implant;}
public void setImp(Implant imp){this.implant = imp;}
public void defend(int damage, int acc) {
System.out.printf("doing this much damage %d\n",damage);
int DamageToOpponent = 0;
DamageToOpponent = getFF().DefendWith(damage,acc);
if(DamageToOpponent == 0)
return;
DamageToOpponent = getImp().DefendWith(damage, acc);
if(DamageToOpponent == 0)
return;
DamageToOpponent = getArmor().DefendWith(damage,acc);
int Health = super.getCurHp();
System.out.printf("Current Players Health %d\n",Health);
Health = Health - DamageToOpponent;
super.setCurHp(Health);
System.out.printf("new HP after hit %d\n",super.getCurHp());
if(super.getCurHp() < 1)
super.setDef(true);
return;
}
//CLASS-LEVEL METHODS--------------------------------------------------------------------
} | EvanDaley/Alcatraz | PC.java |
1,177 | package com.xk72.charles.gui;
import java.io.UnsupportedEncodingException;
public final class P {
private static int A = 0;
private static int B = 0;
private static int C = 0;
private static int D = 0;
private static int E = 0;
private static int F = 0;
private static int G = 0;
private static int H = 0;
private static int I = 0;
private static int J = 0;
private static int K = 0;
private static int L = 0;
private static int M = 0;
private static int N = 0;
private static int O = 0;
private static String a = "Thanks for looking at the source. Please register Charles if you use it.";
private static final int ap = -1209970333;
private static final int aq = -1640531527;
private static P b = null;
private static final int g = 1;
private static final int h = 2;
private static final int i = 3;
private static final long j = 8800536498351690864L;
private static final long k = -5408575981733630035L;
private static final long l = -6517524745266237632L;
private static final long m = 5911726755176091652L;
private static final String[] n;
private static final int o = 32;
private static int p;
private static int q;
private static int r;
private static int s;
private static int t;
private static int u;
private static int v;
private static int w;
private static int x;
private static int y;
private static int z;
private int P;
private int Q;
private int R;
private int S;
private int T;
private int U;
private int V;
private int W;
private int X;
private int Y;
private int Z;
private int aa;
private int ab;
private int ac;
private int ad;
private int ae;
private int af;
private int ag;
private int ah;
private int ai;
private int aj;
private int ak;
private int al;
private int am;
private int an;
private int ao;
private boolean c;
private String d;
private int e;
private int f;
static {
b = new P();
String[] strArr = new String[i];
strArr[0] = "b241993e8a12c782348e4652cc22c2501d9d6f248e91a3d849275666a0ff7d954fdf638f0d03098c52c4710a5e619b9b09cd6cd027ea3bdb937172b3fdf0bded3d684333798880bb78780f6f6644580409ac882bc021732a";
strArr[g] = "b241993e8a12c782348e4652cc22c250c30afb881b44ba4dd936c44a573755b5276046dc3ae32e58d10f467421f51ca607b0e29f53cd8f38dd9eee548398b195348e4652cc22c2502feb5f8fd884cb3c9a330ee10954d071";
strArr[h] = "8a24264c4ae5e5371d663158ccbd75e5a5d70bef5d61291ba3af58b92fe98f7a5c8f83abe09b0c1b3f469d5ad85a3a01e81a2248a290b22d05f52db22eb8b10af10437ddcf2f437b1a519b09a9c4f2c374a882757515e2e2fde238a4eccc62d3fc36d9a77dcbd7cc05236b02716005836b21e58a07330bb18136139263e71a0f79382179978b680a";
n = strArr;
p = ap;
q = 1444465436;
r = -196066091;
s = -1836597618;
t = 817838151;
u = -822693376;
v = 1831742393;
w = 191210866;
x = -1449320661;
y = 1205115108;
z = -435416419;
A = -2075947946;
B = 578487823;
C = -1062043704;
D = 1592392065;
E = -48139462;
F = -1688670989;
G = 965764780;
H = -674766747;
I = 1979669022;
J = 339137495;
K = -1301394032;
L = 1353041737;
M = -287489790;
N = -1928021317;
O = 726414452;
}
public P() {
this.c = false;
this.d = "Unregistered";
}
private P(String str, String str2) throws LicenceException {
this.c = false;
this.d = "Unregistered";
try {
if (a(c(str, str2))) {
this.d = str;
this.c = true;
return;
}
throw new LicenceException(a((int) h));
} catch (NumberFormatException e) {
throw new LicenceException(a((int) g));
}
}
private static final int a(byte[] bArr) {
int i = 0;
int i2 = 0;
while (i < bArr.length) {
i2 ^= bArr[i];
i2 = (i2 >>> 29) | (i2 << i);
i += g;
}
return i2;
}
private static final long a(String str) {
return (Long.parseLong(str.substring(h, 10), 16) << o) | Long.parseLong(str.substring(10, 18), 16);
}
private String a(int i) {
d(j);
try {
String str = n[i];
byte[] bArr = new byte[(str.length() / h)];
for (int i2 = 0; i2 < bArr.length; i2 += g) {
bArr[i2] = (byte) Integer.parseInt(str.substring(i2 << g, (i2 << g) + h), 16);
}
bArr = c(bArr);
int length = bArr.length;
// ζnullζΉζδΊ0
while (bArr[length - 1] == 0) {
length--;
}
return new String(bArr, 0, length, "UTF-8");
} catch (UnsupportedEncodingException e) {
return "";
}
}
public static String a(String str, String str2) {
try {
b = new P(str, str2);
return null;
} catch (LicenceException e) {
return e.getMessage();
}
}
private static void a(P p) {
b = p;
}
public static boolean a() {
return true;//b.c;
}
private boolean a(long j) {
int b = b(j);
d(j);
for (int i = 0; i < b + 35; i += g) {
j = c(j);
}
return j == m;
}
private static final int b(long j) {
long j2 = 0;
for (int i = 56; i >= 0; i -= 8) {
j2 ^= (j >>> i) & 255;
}
return Math.abs((int) (j2 & 255));
}
private static final int b(String str) {
return Integer.parseInt(str.substring(0, h), 16);
}
public static String b() {
P p = b;
switch (p.f) {
case g /* 1 */:
return p.d;
case h /* 2 */:
return p.d + " - Site License";
case i /* 3 */:
return p.d + " - Multi-Site License";
default:
return p.d;
}
}
private boolean b(String str, String str2) throws LicenceException {
long c = c(str, str2);
int b = b(c);
d(c);
for (int i = 0; i < b + 35; i += g) {
c = c(c);
}
return c == m;
}
private byte[] b(byte[] bArr) {
int length = bArr.length;
int i = length + 4;
if (i % 8 != 0) {
i += 8 - (i % 8);
}
byte[] bArr2 = new byte[i];
System.arraycopy(bArr, 0, bArr2, 4, length);
bArr2[0] = (byte) (length >> 24);
bArr2[g] = (byte) (length >> 16);
bArr2[h] = (byte) (length >> 8);
bArr2[i] = (byte) length;
return c(bArr2);
}
private long c(long j) {
int i = ((int) (j >>> 32)) + this.Q;
int i2 = (((int) j) + this.P) ^ i;
int i3 = i & 31;
i2 = ((i2 >>> (32 - i3)) | (i2 << i3)) + this.R;
i ^= i2;
i3 = i2 & 31;
i = ((i >>> (32 - i3)) | (i << i3)) + this.S;
i2 ^= i;
i3 = i & 31;
i2 = ((i2 >>> (32 - i3)) | (i2 << i3)) + this.T;
i ^= i2;
i3 = i2 & 31;
i = ((i >>> (32 - i3)) | (i << i3)) + this.U;
i2 ^= i;
i3 = i & 31;
i2 = ((i2 >>> (32 - i3)) | (i2 << i3)) + this.V;
i ^= i2;
i3 = i2 & 31;
i = ((i >>> (32 - i3)) | (i << i3)) + this.W;
i2 ^= i;
i3 = i & 31;
i2 = ((i2 >>> (32 - i3)) | (i2 << i3)) + this.X;
i ^= i2;
i3 = i2 & 31;
i = ((i >>> (32 - i3)) | (i << i3)) + this.Y;
i2 ^= i;
i3 = i & 31;
i2 = ((i2 >>> (32 - i3)) | (i2 << i3)) + this.Z;
i ^= i2;
i3 = i2 & 31;
i = ((i >>> (32 - i3)) | (i << i3)) + this.aa;
i2 ^= i;
i3 = i & 31;
i2 = ((i2 >>> (32 - i3)) | (i2 << i3)) + this.ab;
i ^= i2;
i3 = i2 & 31;
i = ((i >>> (32 - i3)) | (i << i3)) + this.ac;
i2 ^= i;
i3 = i & 31;
i2 = ((i2 >>> (32 - i3)) | (i2 << i3)) + this.ad;
i ^= i2;
i3 = i2 & 31;
i = ((i >>> (32 - i3)) | (i << i3)) + this.ae;
i2 ^= i;
i3 = i & 31;
i2 = ((i2 >>> (32 - i3)) | (i2 << i3)) + this.af;
i ^= i2;
i3 = i2 & 31;
i = ((i >>> (32 - i3)) | (i << i3)) + this.ag;
i2 ^= i;
i3 = i & 31;
i2 = ((i2 >>> (32 - i3)) | (i2 << i3)) + this.ah;
i ^= i2;
i3 = i2 & 31;
i = ((i >>> (32 - i3)) | (i << i3)) + this.ai;
i2 ^= i;
i3 = i & 31;
i2 = ((i2 >>> (32 - i3)) | (i2 << i3)) + this.aj;
i ^= i2;
i3 = i2 & 31;
i = ((i >>> (32 - i3)) | (i << i3)) + this.ak;
i2 ^= i;
i3 = i & 31;
i2 = ((i2 >>> (32 - i3)) | (i2 << i3)) + this.al;
i ^= i2;
i3 = i2 & 31;
i = ((i >>> (32 - i3)) | (i << i3)) + this.am;
i2 ^= i;
i3 = i & 31;
i2 = ((i2 >>> (32 - i3)) | (i2 << i3)) + this.an;
i ^= i2;
i3 = i2 & 31;
return (((long) i2) & 4294967295L) + (((long) (((i >>> (32 - i3)) | (i << i3)) + this.ao)) << 32);
}
private long c(String str, String str2) throws LicenceException {
int i = 0;
if (str2.length() != 18) {
throw new LicenceException(a(0));
} else if (str2.equalsIgnoreCase("7055ce2f8cb4f9405f") || str2.equalsIgnoreCase("5bae9d8cdea32760ae")
|| str2.equalsIgnoreCase("f3264994d9ea6bc595") || str2.equalsIgnoreCase("b9930cef009d3a7865")
|| str2.equalsIgnoreCase("62bd6a5f95aa67998e") || str2.equalsIgnoreCase("a1c536c35904e64584")
|| str2.equalsIgnoreCase("d6e5590ecc05edd9b3") || str2.equalsIgnoreCase("8fbe36ce2726458b18")
|| str2.equalsIgnoreCase("042a8352caf1188945") || str2.equalsIgnoreCase("9d26d5088770221c3c")
|| str2.equalsIgnoreCase("e19b2a01905e4129bf") || str2.equalsIgnoreCase("68ebe4c9d792f31057")
|| str2.equalsIgnoreCase("4e4beb8a43e9feb9c7") || str2.equalsIgnoreCase("d04d85b44b306fc9ec")
|| str2.equalsIgnoreCase("2b5d21a38c9452e342") || str2.equalsIgnoreCase("88cb89c26a813bce44")
|| str2.equalsIgnoreCase("76c9ee78c8ab124054") || str2.equalsIgnoreCase("729db7c98163ac7d3d")
|| str2.equalsIgnoreCase("7c1d4761993c412472") || str2.equalsIgnoreCase("08bc0b7ec91cd0f4aa")
|| str2.equalsIgnoreCase("25bafae175decaedcc") || str2.equalsIgnoreCase("3181aae6822ef90ccd")
|| str2.equalsIgnoreCase("d7a8fe9dc9dc919f87") || str2.equalsIgnoreCase("728dae81d9d22aca03")
|| str2.equalsIgnoreCase("119a9b593348fa3e74") || str2.equalsIgnoreCase("04ab87c8d69667878e")
|| str2.equalsIgnoreCase("4b282d851ebd87a7bb") || str2.equalsIgnoreCase("ed526255313b756e42")
|| str2.equalsIgnoreCase("ed5ab211362ab25ca7") || str2.equalsIgnoreCase("18f4789a3df48f3b15")
|| str2.equalsIgnoreCase("67549e44b1c8d8d857") || str2.equalsIgnoreCase("4593c6c54227c4f17d")
|| str2.equalsIgnoreCase("1c59db29042e7df8ef") || str2.equalsIgnoreCase("a647e3dd42ce9b409b")
|| str2.equalsIgnoreCase("7e06d6a70b82858113") || str2.equalsIgnoreCase("ef4b5a48595197a373")
|| str2.equalsIgnoreCase("0ac55f6bebd0330640") || str2.equalsIgnoreCase("1beda9831c78994f43")
|| str2.equalsIgnoreCase("8a2b9debb15766bff9") || str2.equalsIgnoreCase("da0e7561b10d974216")
|| str2.equalsIgnoreCase("86257b04b8c303fd9a") || str2.equalsIgnoreCase("a4036b2761c9583fda")
|| str2.equalsIgnoreCase("18e69f6d5bc820d4d3")) {
throw new LicenceException(a((int) g));
} else {
long parseLong = (Long.parseLong(str2.substring(h, 10), 16) << 32)
| Long.parseLong(str2.substring(10, 18), 16);
int parseInt = Integer.parseInt(str2.substring(0, h), 16);
d(k);
parseLong = c(parseLong);
if (b(parseLong) != parseInt) {
throw new LicenceException(a((int) g));
}
this.e = (int) (((parseLong << 32) >>> 32) >>> 24);
if (this.e == g) {
this.f = g;
} else if (this.e == i) {
this.f = (int) ((((parseLong << 32) >>> 32) >>> 16) & 255);
if (!(this.f == g || this.f == h || this.f == i)) {
throw new LicenceException(a((int) g));
}
} else if (this.e > i) {
this.f = (int) ((((parseLong << 32) >>> 32) >>> 16) & 255);
} else {
throw new LicenceException(a((int) g));
}
d(j);
try {
byte[] bytes = str.getBytes("UTF-8");
int length = bytes.length;
parseInt = length + 4;
if (parseInt % 8 != 0) {
parseInt += 8 - (parseInt % 8);
}
byte[] bArr = new byte[parseInt];
System.arraycopy(bytes, 0, bArr, 4, length);
bArr[0] = (byte) (length >> 24);
bArr[g] = (byte) (length >> 16);
bArr[h] = (byte) (length >> 8);
bArr[i] = (byte) length;
byte[] c = c(bArr);
parseInt = 0;
while (i < c.length) {
parseInt ^= c[i];
parseInt = (parseInt >>> 29) | (parseInt << i);
i += g;
}
return ((((long) (((int) (parseLong >> 32)) ^ parseInt)) << 32) >>> 32) | -6517524747541020672L;
} catch (UnsupportedEncodingException e) {
return -1;
}
}
}
private boolean c() {
return this.c;
}
private byte[] c(byte[] bArr) {
byte[] bArr2 = new byte[bArr.length];
int length = bArr.length;
long j = 0;
int i = 0;
for (int i2 = 0; i2 < length; i2 += g) {
j = (j << 8) | ((long) (bArr[i2] & 255));
i += g;
if (i == 8) {
j = c(j);
bArr2[i2 - 7] = (byte) ((int) (j >>> 56));
bArr2[i2 - 6] = (byte) ((int) (j >>> 48));
bArr2[i2 - 5] = (byte) ((int) (j >>> 40));
bArr2[i2 - 4] = (byte) ((int) (j >>> o));
bArr2[i2 - 3] = (byte) ((int) (j >>> 24));
bArr2[i2 - 2] = (byte) ((int) (j >>> 16));
bArr2[i2 - 1] = (byte) ((int) (j >>> 8));
bArr2[i2] = (byte) ((int) j);
j = 0;
i = 0;
}
}
return bArr2;
}
private String d() {
switch (this.f) {
case g /* 1 */:
return this.d;
case h /* 2 */:
return this.d + " - Site License";
case i /* 3 */:
return this.d + " - Multi-Site License";
default:
return this.d;
}
}
private void d(long j) {
int i = (int) j;
int i2 = (int) (j >>> o);
int i3 = p;
i3 = (i3 >>> 29) | (i3 << i);
this.P = i3;
i += i3;
int i4 = i3 & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + q;
i3 = (i3 >>> 29) | (i3 << i);
this.Q = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + r;
i3 = (i3 >>> 29) | (i3 << i);
this.R = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + s;
i3 = (i3 >>> 29) | (i3 << i);
this.S = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + t;
i3 = (i3 >>> 29) | (i3 << i);
this.T = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + u;
i3 = (i3 >>> 29) | (i3 << i);
this.U = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + v;
i3 = (i3 >>> 29) | (i3 << i);
this.V = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + w;
i3 = (i3 >>> 29) | (i3 << i);
this.W = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + x;
i3 = (i3 >>> 29) | (i3 << i);
this.X = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + y;
i3 = (i3 >>> 29) | (i3 << i);
this.Y = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + z;
i3 = (i3 >>> 29) | (i3 << i);
this.Z = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + A;
i3 = (i3 >>> 29) | (i3 << i);
this.aa = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + B;
i3 = (i3 >>> 29) | (i3 << i);
this.ab = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + C;
i3 = (i3 >>> 29) | (i3 << i);
this.ac = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + D;
i3 = (i3 >>> 29) | (i3 << i);
this.ad = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + E;
i3 = (i3 >>> 29) | (i3 << i);
this.ae = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + F;
i3 = (i3 >>> 29) | (i3 << i);
this.af = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + G;
i3 = (i3 >>> 29) | (i3 << i);
this.ag = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + H;
i3 = (i3 >>> 29) | (i3 << i);
this.ah = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + I;
i3 = (i3 >>> 29) | (i3 << i);
this.ai = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + J;
i3 = (i3 >>> 29) | (i3 << i);
this.aj = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + K;
i3 = (i3 >>> 29) | (i3 << i);
this.ak = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + L;
i3 = (i3 >>> 29) | (i3 << i);
this.al = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + M;
i3 = (i3 >>> 29) | (i3 << i);
this.am = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + N;
i3 = (i3 >>> 29) | (i3 << i);
this.an = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + O;
i3 = (i3 >>> 29) | (i3 << i);
this.ao = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + this.P;
i3 = (i3 >>> 29) | (i3 << i);
this.P = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + this.Q;
i3 = (i3 >>> 29) | (i3 << i);
this.Q = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + this.R;
i3 = (i3 >>> 29) | (i3 << i);
this.R = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + this.S;
i3 = (i3 >>> 29) | (i3 << i);
this.S = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + this.T;
i3 = (i3 >>> 29) | (i3 << i);
this.T = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + this.U;
i3 = (i3 >>> 29) | (i3 << i);
this.U = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + this.V;
i3 = (i3 >>> 29) | (i3 << i);
this.V = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + this.W;
i3 = (i3 >>> 29) | (i3 << i);
this.W = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + this.X;
i3 = (i3 >>> 29) | (i3 << i);
this.X = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + this.Y;
i3 = (i3 >>> 29) | (i3 << i);
this.Y = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + this.Z;
i3 = (i3 >>> 29) | (i3 << i);
this.Z = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + this.aa;
i3 = (i3 >>> 29) | (i3 << i);
this.aa = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + this.ab;
i3 = (i3 >>> 29) | (i3 << i);
this.ab = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + this.ac;
i3 = (i3 >>> 29) | (i3 << i);
this.ac = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + this.ad;
i3 = (i3 >>> 29) | (i3 << i);
this.ad = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + this.ae;
i3 = (i3 >>> 29) | (i3 << i);
this.ae = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + this.af;
i3 = (i3 >>> 29) | (i3 << i);
this.af = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + this.ag;
i3 = (i3 >>> 29) | (i3 << i);
this.ag = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + this.ah;
i3 = (i3 >>> 29) | (i3 << i);
this.ah = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + this.ai;
i3 = (i3 >>> 29) | (i3 << i);
this.ai = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + this.aj;
i3 = (i3 >>> 29) | (i3 << i);
this.aj = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + this.ak;
i3 = (i3 >>> 29) | (i3 << i);
this.ak = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + this.al;
i3 = (i3 >>> 29) | (i3 << i);
this.al = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + this.am;
i3 = (i3 >>> 29) | (i3 << i);
this.am = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + this.an;
i3 = (i3 >>> 29) | (i3 << i);
this.an = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + this.ao;
i3 = (i3 >>> 29) | (i3 << i);
this.ao = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + this.P;
i3 = (i3 >>> 29) | (i3 << i);
this.P = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + this.Q;
i3 = (i3 >>> 29) | (i3 << i);
this.Q = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + this.R;
i3 = (i3 >>> 29) | (i3 << i);
this.R = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + this.S;
i3 = (i3 >>> 29) | (i3 << i);
this.S = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + this.T;
i3 = (i3 >>> 29) | (i3 << i);
this.T = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + this.U;
i3 = (i3 >>> 29) | (i3 << i);
this.U = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + this.V;
i3 = (i3 >>> 29) | (i3 << i);
this.V = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + this.W;
i3 = (i3 >>> 29) | (i3 << i);
this.W = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + this.X;
i3 = (i3 >>> 29) | (i3 << i);
this.X = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + this.Y;
i3 = (i3 >>> 29) | (i3 << i);
this.Y = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + this.Z;
i3 = (i3 >>> 29) | (i3 << i);
this.Z = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + this.aa;
i3 = (i3 >>> 29) | (i3 << i);
this.aa = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + this.ab;
i3 = (i3 >>> 29) | (i3 << i);
this.ab = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + this.ac;
i3 = (i3 >>> 29) | (i3 << i);
this.ac = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + this.ad;
i3 = (i3 >>> 29) | (i3 << i);
this.ad = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + this.ae;
i3 = (i3 >>> 29) | (i3 << i);
this.ae = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + this.af;
i3 = (i3 >>> 29) | (i3 << i);
this.af = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + this.ag;
i3 = (i3 >>> 29) | (i3 << i);
this.ag = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + this.ah;
i3 = (i3 >>> 29) | (i3 << i);
this.ah = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + this.ai;
i3 = (i3 >>> 29) | (i3 << i);
this.ai = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + this.aj;
i3 = (i3 >>> 29) | (i3 << i);
this.aj = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + this.ak;
i3 = (i3 >>> 29) | (i3 << i);
this.ak = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + this.al;
i3 = (i3 >>> 29) | (i3 << i);
this.al = i3;
i += i3 + i2;
i4 = (i3 + i2) & 31;
i = (i >>> (32 - i4)) | (i << i4);
i3 = (i3 + i) + this.am;
i3 = (i3 >>> 29) | (i3 << i);
this.am = i3;
i2 += i3 + i;
i4 = (i3 + i) & 31;
i2 = (i2 >>> (32 - i4)) | (i2 << i4);
i3 = (i3 + i2) + this.an;
i3 = (i3 >>> 29) | (i3 << i);
this.an = i3;
i += i3 + i2;
i2 = (i2 + i3) & 31;
i = (((i >>> (32 - i2)) | (i << i2)) + i3) + this.ao;
this.ao = (i >>> 29) | (i << i);
}
}
class LicenceException extends Exception {
public LicenceException(String str) {
super(str);
}
} | OtherResources/charles-hacking | P.java |
1,183 | import java.util.*;
import java.io.*;
public class f {
public static Planets[] planets;
public static int[][] connected;
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
int numPlanets = stdin.nextInt();
while(numPlanets != 0){
planets = new Planets[numPlanets];
connected = new int[numPlanets][numPlanets];
for(int i = 0; i < connected.length; i++){
Arrays.fill(connected[i], 0);
}
for(int i = 0; i < numPlanets; i++){
planets[i] = new Planets(stdin.nextInt(), stdin.nextInt(), stdin.nextInt(), stdin.nextInt());
if(i != 0){
connected[connector(planets, i)][i] = 1;
connected[i][connector(planets, i)] = 1;
}
}
int[] maxDistances = new int[numPlanets];
for(int i = 0; i < planets.length; i++){
maxDistances[i] = bf(i);
}
//System.out.println("all max: " + Arrays.toString(maxDistances));
ArrayList<Planets> valid = new ArrayList();
int min = maxDistances[0];
for(int m = 0; m < maxDistances.length; m++){
if(maxDistances[m] < min) min = maxDistances[m];
}
for(int m = 0; m < maxDistances.length; m++){
if(maxDistances[m] == min) valid.add(planets[m]);
}
Collections.sort(valid);
for(Planets v : valid){
System.out.print(v.ID + " ");
}
System.out.println();
numPlanets = stdin.nextInt();
}
}
public static int bf(int src){
int[] dist = new int[planets.length];
for(int i = 0; i < planets.length; i++){
if(i == src) dist[i] = 0;
else dist[i] = 20000;
}
//System.out.println("from " + src + ": " + Arrays.toString(dist));
for(int i = 0; i < planets.length; i++){
for(int j = 0; j < planets.length; j++){
for(int k = 0; k < planets.length; k++){
if(connected[j][k] == 1){
if(dist[j] + connected[j][k] < dist[k]){
dist[k] = dist[j] + connected[j][k];
}
}
}
}
}
Arrays.sort(dist);
//System.out.println(src + ": " + Arrays.toString(dist));
return dist[dist.length-1];
}
public static int djikstras(int source){
Point[] distanceD = new Point[planets.length];
Arrays.fill(distanceD, new Point(Integer.MAX_VALUE, source));
distanceD[source].distance = 0;
for(int i = 0; i < planets.length; i++){
int vertex = 0;
int bestSeen = Integer.MAX_VALUE;
for(int j = 0; j < planets.length; j++){
if(!distanceD[j].visited && distanceD[j].distance < bestSeen){
bestSeen = distanceD[j].distance;
vertex = j;
}
}
distanceD[vertex].visited = true;
for(int j = 0; j < planets.length; j++){
if(distanceD[vertex].distance+connected[vertex][j] < distanceD[j].distance){
distanceD[j].distance = distanceD[vertex].distance+ connected[vertex][j];
distanceD[j].previous = vertex;
}
}
}
Arrays.sort(distanceD);
for(int i = 0; i < distanceD.length; i++){
System.out.println(distanceD[i].distance);
}
return distanceD[distanceD.length-1].distance;
}
public static int connector(Planets[] p, int index){
int best = 0;
double distance = -1;
for(int k = 0; k < index; k++){
double tempD = Math.sqrt(Math.pow(p[k].x-p[index].x, 2) + Math.pow(p[k].y-p[index].y, 2) + Math.pow(p[k].z-p[index].z, 2));
if(tempD < distance || distance == -1){
best = k;
distance = tempD;
}
}
return best;
}
}
class Point implements Comparable<Point>{
public int distance;
public int previous;
public boolean visited;
public Point(int d, int p){
distance = d;
previous = p;
visited = false;
}
@Override
public int compareTo(Point p) {
return distance - p.distance;
}
}
class Planets implements Comparable<Planets>{
int ID;
double x;
double y;
double z;
public Planets(int id, int a, int b, int c){
ID = id;
x = a;
y = b;
z = c;
}
@Override
public int compareTo(Planets o) {
return this.ID - o.ID;
}
}
/*
5
1 0 0 0
2 0 0 1
3 0 0 2
4 0 0 3
5 0 0 4
5
1 0 0 0
2 1 1 0
3 3 2 0
4 2 1 0
5 3 0 0
10
21 71 76 4
97 32 5 69
70 33 19 35
3 79 81 8
31 91 17 67
52 31 48 75
48 90 14 4
41 73 2 21
83 74 41 69
26 32 30 24
0
*/ | isabelacmor/programmingteam | f.java |
1,185 | // public class S
// {
// //String s;
// public S(String s){
// this.s = s;
// }
// public String get(){
// return s;
// }
// public static void main(String [] args){
// S s = new S("hello world!");
// System.out.println(s.get());
// System.out.println(s.mySubstring(1,5));
// }
// public String mySubstring(int start, int end){
// char [] c = this.get().toCharArray();
// StringBuilder sb = new StringBuilder();
// for(int i = start; i < end; i++){
// sb.append(c[i]);
// }
// return sb.toString();
// }
// public String mySubstring(int start){
// return " ";
// }
// } | kylelong/weeklyProblems | S.java |
1,188 | public class x implements de {
public dk[] a;
public dk[] b;
public int c;
public vi d;
private dk f;
public boolean e;
public x(vi entityplayer) {
this.a = new dk[36];
this.b = new dk[4];
this.c = 0;
this.e = false;
this.d = entityplayer;
}
public dk a() {
if (this.c < 9 && this.c >= 0)
return this.a[this.c];
return null;
}
private int g(int i) {
for (int j = 0; j < this.a.length; j++) {
if (this.a[j] != null && (this.a[j]).c == i)
return j;
}
return -1;
}
private int b(int i, int j) {
for (int k = 0; k < this.a.length; k++) {
if (this.a[k] != null && (this.a[k]).c == i && this.a[k].i() == j)
return k;
}
return -1;
}
private int d(dk itemstack) {
for (int i = 0; i < this.a.length; i++) {
if (this.a[i] != null && (this.a[i]).c == itemstack.c && this.a[i].d() && (this.a[i]).a < this.a[i].c() && (this.a[i]).a < e() && (!this.a[i].f() || this.a[i].i() == itemstack.i()))
return i;
}
return -1;
}
private int l() {
for (int i = 0; i < this.a.length; i++) {
if (this.a[i] == null)
return i;
}
return -1;
}
public void a(int i, int j, boolean flag, boolean flag1) {
int k = -1;
if (flag) {
k = b(i, j);
} else {
k = g(i);
}
if (k >= 0 && k < 9) {
this.c = k;
return;
}
}
public void a(int i) {
if (i > 0)
i = 1;
if (i < 0)
i = -1;
for (this.c -= i; this.c < 0; this.c += 9);
for (; this.c >= 9; this.c -= 9);
}
private int e(dk itemstack) {
int i = itemstack.c;
int j = itemstack.a;
if (itemstack.c() == 1) {
int k = l();
if (k < 0)
return j;
if (this.a[k] == null)
this.a[k] = dk.b(itemstack);
return 0;
}
int l = d(itemstack);
if (l < 0)
l = l();
if (l < 0)
return j;
if (this.a[l] == null)
this.a[l] = new dk(i, 0, itemstack.i());
int i1 = j;
if (i1 > this.a[l].c() - (this.a[l]).a)
i1 = this.a[l].c() - (this.a[l]).a;
if (i1 > e() - (this.a[l]).a)
i1 = e() - (this.a[l]).a;
if (i1 == 0)
return j;
j -= i1;
(this.a[l]).a += i1;
(this.a[l]).b = 5;
return j;
}
public void b() {
for (int i = 0; i < this.a.length; i++) {
if (this.a[i] != null)
this.a[i].a(this.d.o, this.d, i, (this.c == i));
}
}
public boolean b(int i) {
int j = g(i);
if (j < 0)
return false;
if (--(this.a[j]).a <= 0)
this.a[j] = null;
return true;
}
public boolean c(int i) {
int j = g(i);
return (j >= 0);
}
public boolean a(dk itemstack) {
if (!itemstack.g()) {
int i;
do {
i = itemstack.a;
itemstack.a = e(itemstack);
} while (itemstack.a > 0 && itemstack.a < i);
if (itemstack.a == i && this.d.cc.d) {
itemstack.a = 0;
return true;
}
return (itemstack.a < i);
}
int j = l();
if (j >= 0) {
this.a[j] = dk.b(itemstack);
(this.a[j]).b = 5;
itemstack.a = 0;
return true;
}
if (this.d.cc.d) {
itemstack.a = 0;
return true;
}
return false;
}
public dk a(int i, int j) {
dk[] aitemstack = this.a;
if (i >= this.a.length) {
aitemstack = this.b;
i -= this.a.length;
}
if (aitemstack[i] != null) {
if ((aitemstack[i]).a <= j) {
dk itemstack = aitemstack[i];
aitemstack[i] = null;
return itemstack;
}
dk itemstack1 = aitemstack[i].a(j);
if ((aitemstack[i]).a == 0)
aitemstack[i] = null;
return itemstack1;
}
return null;
}
public void a(int i, dk itemstack) {
dk[] aitemstack = this.a;
if (i >= aitemstack.length) {
i -= aitemstack.length;
aitemstack = this.b;
}
aitemstack[i] = itemstack;
}
public float a(yy block) {
float f = 1.0F;
if (this.a[this.c] != null)
f *= this.a[this.c].a(block);
return f;
}
public yi a(yi nbttaglist) {
for (int i = 0; i < this.a.length; i++) {
if (this.a[i] != null) {
ik nbttagcompound = new ik();
nbttagcompound.a("Slot", (byte)i);
this.a[i].b(nbttagcompound);
nbttaglist.a((um)nbttagcompound);
}
}
for (int j = 0; j < this.b.length; j++) {
if (this.b[j] != null) {
ik nbttagcompound1 = new ik();
nbttagcompound1.a("Slot", (byte)(j + 100));
this.b[j].b(nbttagcompound1);
nbttaglist.a((um)nbttagcompound1);
}
}
return nbttaglist;
}
public void b(yi nbttaglist) {
this.a = new dk[36];
this.b = new dk[4];
for (int i = 0; i < nbttaglist.c(); i++) {
ik nbttagcompound = (ik)nbttaglist.a(i);
int j = nbttagcompound.c("Slot") & 0xFF;
dk itemstack = dk.a(nbttagcompound);
if (itemstack != null) {
if (j >= 0 && j < this.a.length)
this.a[j] = itemstack;
if (j >= 100 && j < this.b.length + 100)
this.b[j - 100] = itemstack;
}
}
}
public int c() {
return this.a.length + 4;
}
public dk d(int i) {
dk[] aitemstack = this.a;
if (i >= aitemstack.length) {
i -= aitemstack.length;
aitemstack = this.b;
}
return aitemstack[i];
}
public String d() {
return "Inventory";
}
public int e() {
return 64;
}
public int a(ia entity) {
dk itemstack = d(this.c);
if (itemstack != null)
return itemstack.a(entity);
return 1;
}
public boolean b(yy block) {
if (block.bZ.k())
return true;
dk itemstack = d(this.c);
if (itemstack != null)
return itemstack.b(block);
return false;
}
public dk e(int i) {
return this.b[i];
}
public int f() {
int i = 0;
int j = 0;
int k = 0;
for (int l = 0; l < this.b.length; l++) {
if (this.b[l] != null && this.b[l].a() instanceof ItemCustomArmor && ((Boolean)mod_noBiomesX.ArmorDurabilities.get()).booleanValue()) {
int i1 = ((ItemCustomArmor)this.b[l].a()).customMaxDamage;
int j1 = this.b[l].h();
int k1 = i1 - j1;
j += k1;
k += i1;
int l1 = ((ItemCustomArmor)this.b[l].a()).customDamageReduceAmount;
i += l1;
} else if (this.b[l] != null && this.b[l].a() instanceof agi) {
int m = ((agi)this.b[l].a()).b;
i += m;
}
}
if (((Boolean)mod_noBiomesX.ArmorDurabilities.get()).booleanValue()) {
if (k == 0)
return 0;
return (i - 1) * j / k + 1;
}
return i;
}
public void f(int i) {
i /= 4;
if (i < 1)
i = 1;
for (int j = 0; j < this.b.length; j++) {
if (this.b[j] != null && this.b[j].a() instanceof agi) {
this.b[j].a(i, this.d);
if ((this.b[j]).a == 0) {
this.b[j].a(this.d);
this.b[j] = null;
}
}
}
}
public void g() {
for (int i = 0; i < this.a.length; i++) {
if (this.a[i] != null) {
this.d.a(this.a[i], true);
this.a[i] = null;
}
}
for (int j = 0; j < this.b.length; j++) {
if (this.b[j] != null) {
this.d.a(this.b[j], true);
this.b[j] = null;
}
}
}
public void h() {
this.e = true;
}
public void b(dk itemstack) {
this.f = itemstack;
this.d.c(itemstack);
}
public dk i() {
return this.f;
}
public boolean b_(vi entityplayer) {
if (this.d.K)
return false;
return (entityplayer.d(this.d) <= 64.0D);
}
public boolean c(dk itemstack) {
for (int i = 0; i < this.b.length; i++) {
if (this.b[i] != null && this.b[i].c(itemstack))
return true;
}
for (int j = 0; j < this.a.length; j++) {
if (this.a[j] != null && this.a[j].c(itemstack))
return true;
}
return false;
}
public void j() {}
public void k() {}
public void a(x inventoryplayer) {
for (int i = 0; i < this.a.length; i++)
this.a[i] = dk.b(inventoryplayer.a[i]);
for (int j = 0; j < this.b.length; j++)
this.b[j] = dk.b(inventoryplayer.b[j]);
}
}
| JohnCartoonist/The-Nostalgia-Project-src | x.java |
1,189 | abstract class Worker {
public abstract double work();
public abstract int getQuantity();
public abstract static String estimatedProjectTime(Worker[] workers, int projectSize);
}
class Runner extends Worker {
public double work() {
return 2.0;
}
public int getQuantity() {
}
public static String estimatedProjectTime(Worker[] workers, int projectSize) {
}
}
class Jogger extends Worker {
public double work() {
return 1.0;
}
public int getQuantity() {
}
public static String estimatedProjectTime(Worker[] workers, int projectSize) {
}
}
class Walker extends Worker {
public double work() {
return 1.0;
}
public int getQuantity() {
}
public static String estimatedProjectTime(Worker[] workers, int projectSize) {
}
}
class Rider extends Worker {
public double work() {
return 0.5;
}
public int getQuantity() {
}
public static String estimatedProjectTime(Worker[] workers, int projectSize) {
}
}
class Driver extends Worker {
public double work() {
return 1.0;
}
public int getQuantity() {
}
public static String estimatedProjectTime(Worker[] workers, int projectSize) {
}
}
public class Triplet <U, V, T> {
public U a;
public V b;
public T c;
Triplet(U a, V b, T c) {
this.a = a;
this.b = b;
this.c = c;
}
public U getFirst() {
return this.a;
}
public V getSecond() {
return this.b;
}
public T getThird() {
return this.c;
}
public void setFirst(U a) {
this.a = a;
}
public void setSecond(V b) {
this.b = b;
}
public void setThird(T c) {
this.c = c;
}
} | Assylzhan-Izbassar/Object-Oriented-Programming-and-Design | 1.java |
1,190 | public abstract class k {
public ry a;
public vh b;
public boolean c = false;
public boolean d = false;
public boolean e = false;
public float[] f = new float[16];
public int g = 0;
private float[] h = new float[4];
public final void a(ry world) {
this.a = world;
b();
a();
}
protected void a() {
float f = 0.0F;
if (((Boolean)mod_noBiomesX.ClassicLight.get()).booleanValue())
f = 0.05F;
for (int i = 0; i <= 15; i++) {
float f1 = 1.0F - i / 15.0F;
this.f[i] = (1.0F - f1) / (f1 * 3.0F + 1.0F) * (1.0F - f) + f;
}
}
protected void b() {
this.b = new vh(this.a);
}
public ej c() {
return new xj(this.a, this.a.t(), this.a.z().r());
}
public boolean a(int i, int j) {
int m = this.a.a(i, j);
return (m == yy.E.bM);
}
public float a(long l, float f) {
int i = (int)(l % 24000L);
float f1 = (i + f) / 24000.0F - 0.25F;
if (f1 < 0.0F)
f1++;
if (f1 > 1.0F)
f1--;
float f2 = f1;
f1 = 1.0F - (float)((Math.cos(f1 * Math.PI) + 1.0D) / 2.0D);
f1 = f2 + (f1 - f2) / 3.0F;
return f1;
}
public int b(long l, float f) {
return (int)(l / 24000L) % 8;
}
public float[] a(float f, float f1) {
if (!((Boolean)mod_noBiomesX.SunriseEffect.get()).booleanValue())
return null;
float f2 = 0.4F;
float f3 = me.b(f * 3.141593F * 2.0F) - 0.0F;
float f4 = -0.0F;
if (f3 >= f4 - f2 && f3 <= f4 + f2) {
float f5 = (f3 - f4) / f2 * 0.5F + 0.5F;
float f6 = 1.0F - (1.0F - me.a(f5 * 3.141593F)) * 0.99F;
f6 *= f6;
this.h[0] = f5 * 0.3F + 0.7F;
this.h[1] = f5 * f5 * 0.7F + 0.2F;
this.h[2] = f5 * f5 * 0.0F + 0.2F;
this.h[3] = f6;
return this.h;
}
return null;
}
public fb b(float f, float f1) {
float f2 = me.b(f * 3.141593F * 2.0F) * 2.0F + 0.5F;
if (f2 < 0.0F)
f2 = 0.0F;
if (f2 > 1.0F)
f2 = 1.0F;
float f3 = 0.7529412F;
float f4 = 0.8470588F;
float f5 = 1.0F;
f3 *= f2 * 0.94F + 0.06F;
f4 *= f2 * 0.94F + 0.06F;
f5 *= f2 * 0.91F + 0.09F;
return fb.b(f3, f4, f5);
}
public boolean d() {
return true;
}
public static k a(int i) {
if (i == -1)
return new aau();
if (i == 0)
return (k)new ix();
if (i == 1)
return new ol();
return null;
}
public float e() {
if (this.a.totalSkyLight == 16)
return 160.0F;
if (((Boolean)mod_noBiomesX.LowHangingClouds.get()).booleanValue())
return 108.0F;
return this.a.c;
}
public boolean f() {
return true;
}
public dh g() {
return null;
}
}
| JohnCartoonist/The-Nostalgia-Project-src | k.java |
1,193 | /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode l = new ListNode();
ListNode prev = l;
int carry = 0;
while(l1!=null && l2!=null){
int val = (l1.val+l2.val + carry)%10;
carry = (l1.val+l2.val + carry)/10;
l.next = new ListNode(val);
l=l.next;
l1 = l1.next;
l2 = l2.next;
}
ListNode l3 = (l1 == null) ? l2 : l1;
while(l3!=null){
int val = (l3.val + carry)%10;
carry = (l3.val + carry)/10;
l.next = new ListNode(val);
l=l.next;
l3 = l3.next;
}
if(carry>0){
l.next = new ListNode(carry);
l = l.next;
}
return prev.next;
}
} | iamtanbirahmed/100DaysOfLC | 2.java |
1,195 |
public class N {
private Object data;
private N next = null;
N(int data)
{
this.data = data;
}
N(Object o,N start)
{ data=o;
next=start;
}
public void setNext(N nodeToAdd)
{
next = nodeToAdd;
}
public N getNext()
{
return next;
}
public Object getData()
{
return this.data;
}
public void setData(int dataToSet)
{
this.data = dataToSet;
}
}
| tiandiao123/Hanoi-Problem | N.java |
1,197 | import java.util.*;
class Employee {
String name;
int yoj;
String address;
Employee(String n, int y , String a){
this.name= n;
this.yoj=y;
this.address=a;
}
public void display()
{
System.out.println(name+"\t "+yoj+"\t "+address);
}
}
public class Main{
public static void main(String[] args)
{
Scanner sc = new Scanner (System.in);
int i;
System.out.println("Enter the number of entries you want to make");
int c = sc.nextInt();
Employee[] ob = new Employee[c];//array of objects is optional i was getting bored
for(i =0;i<c;i++ )
{
System.out.print("Enter the name of the employee: ");
String n = sc.next();
System.out.println("Enter the year of joining: ");
int y = sc.nextInt();
System.out.println("Enter the address of the employee: ");
String a = sc.next();
ob[i] = new Employee(n,y,a);
}
System.out.println("NAME\tYEAR OF JOINING\tADDRESS");
for(i=0;i<c;i++)
{
ob[i].display();
}
}
} | Welding-Torch/Java-Prac | 1.java |
1,198 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class E here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class E extends Mover
{
private int geld = 50;
/**
* Act - do whatever the E wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
for (Actor hero : getObjectsInRange(200, Hero.class))
{
if (Greenfoot.mouseClicked(this))
{
Hero h = (Hero)hero;
h.geefPunt(geld);
h.geefe("E");
Greenfoot.playSound("Sonic Ring sound Effect in stereo.mp3");
getWorld().removeObject(this);
}
}
applyVelocity();
}
}
| ROCMondriaanTIN/project-greenfoot-game-MarekBeers | E.java |
1,199 | // This File Link : https://packages.nego.network/packages/java-test-github/m.java
package com.negodev;
import com.negodev.utils.Network.Network;
class Main {
public static void main(String[] args) {
double value = 99.5;
String formattedValue = Network.provideHost(value);
System.out.println("Response = " + formattedValue);
}
}
| kardespro/java-tests | m.java |
1,200 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class R here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class G extends Mover
{
private int geld = 50;
String G = "G";
/**
* Act - do whatever the E wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
for (Actor hero : getObjectsInRange(200, Hero.class))
{
if (Greenfoot.mouseClicked(this))
{
Hero h = (Hero)hero;
h.geefPunt(geld);
h.geefg(G);
Greenfoot.playSound("Sonic Ring sound Effect in stereo.mp3");
getWorld().removeObject(this);
}
}
applyVelocity();
}
}
| ROCMondriaanTIN/project-greenfoot-game-MarekBeers | G.java |
1,204 | package demo1;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
class Account {
private final int accountNumber;
private final String accountHolder;
private double balance;
public Account(int accountNumber, String accountHolder, double initialBalance) {
this.accountNumber = accountNumber;
this.accountHolder = accountHolder;
this.balance = initialBalance;
}
public synchronized void deposit(double amount) {
balance += amount;
}
public synchronized boolean withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
return true;
}
return false;
}
public synchronized double getBalance() {
return balance;
}
}
class AccountManager {
private static final AccountManager INSTANCE = new AccountManager();
private final Map<Integer, Account> accounts = new HashMap<>();
private AccountManager() {}
public static AccountManager getInstance() {
return INSTANCE;
}
public synchronized void createAccount(int accountNumber, String accountHolder, double initialBalance) {
if (!accounts.containsKey(accountNumber)) {
accounts.put(accountNumber, new Account(accountNumber, accountHolder, initialBalance));
System.out.println("Account created for " + accountHolder + " with account number " + accountNumber);
} else {
System.out.println("Account with account number " + accountNumber + " already exists.");
}
}
public synchronized void deposit(int accountNumber, double amount) {
Account account = accounts.get(accountNumber);
if (account != null) {
account.deposit(amount);
System.out.println("Deposited " + amount + " into account " + accountNumber);
} else {
System.out.println("Account with account number " + accountNumber + " not found.");
}
}
public synchronized void withdraw(int accountNumber, double amount) {
Account account = accounts.get(accountNumber);
if (account != null) {
if (account.withdraw(amount)) {
System.out.println("Withdrawn " + amount + " from account " + accountNumber);
} else {
System.out.println("Insufficient balance in account " + accountNumber);
}
} else {
System.out.println("Account with account number " + accountNumber + " not found.");
}
}
public synchronized double getBalance(int accountNumber) {
Account account = accounts.get(accountNumber);
if (account != null) {
return account.getBalance();
} else {
System.out.println("Account with account number " + accountNumber + " not found.");
return 0.0;
}
}
}
public class ABCD {
public static void main(String[] args) {
AccountManager accountManager = AccountManager.getInstance();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("\nMenu:");
System.out.println("1. Create Account");
System.out.println("2. Deposit");
System.out.println("3. Withdraw");
System.out.println("4. Check Balance");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter Account Number: ");
int accountNumber = scanner.nextInt();
System.out.print("Enter Account Holder: ");
String accountHolder = scanner.next();
System.out.print("Enter Initial Balance: ");
double initialBalance = scanner.nextDouble();
accountManager.createAccount(accountNumber, accountHolder, initialBalance);
break;
case 2:
System.out.print("Enter Account Number: ");
accountNumber = scanner.nextInt();
System.out.print("Enter Deposit Amount: ");
double depositAmount = scanner.nextDouble();
accountManager.deposit(accountNumber, depositAmount);
break;
case 3:
System.out.print("Enter Account Number: ");
accountNumber = scanner.nextInt();
System.out.print("Enter Withdrawal Amount: ");
double withdrawalAmount = scanner.nextDouble();
accountManager.withdraw(accountNumber, withdrawalAmount);
break;
case 4:
System.out.print("Enter Account Number: ");
accountNumber = scanner.nextInt();
double balance = accountManager.getBalance(accountNumber);
System.out.println("Account Balance: " + balance);
break;
case 5:
System.out.println("Exiting the program.");
scanner.close();
System.exit(0);
default:
System.out.println("Invalid choice. Please try again.");
}
}
}
}
| Ranganathb082/hackerrank-problems | 7.java |
1,205 | import java.util.Scanner;
class BankAccount {
private double balance;
public BankAccount(double balance) {
this.balance = balance;
}
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposit successful. New balance: " + balance);
} else {
System.out.println("Invalid deposit amount.");
}
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrawal successful. New balance: " + balance);
} else {
System.out.println("Insufficient funds or invalid withdrawal amount.");
}
}
}
public class ATM {
private BankAccount account;
public ATM(BankAccount account) {
this.account = account;
}
public void displayMenu() {
System.out.println("\nATM Interface");
System.out.println("1. Withdraw");
System.out.println("2. Deposit");
System.out.println("3. Check Balance");
System.out.println("4. Exit");
}
public void start() {
Scanner scanner = new Scanner(System.in);
boolean exit = false;
while (!exit) {
displayMenu();
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter amount to withdraw: ");
double withdrawAmount = scanner.nextDouble();
account.withdraw(withdrawAmount);
break;
case 2:
System.out.print("Enter amount to deposit: ");
double depositAmount = scanner.nextDouble();
account.deposit(depositAmount);
break;
case 3:
System.out.println("Your current balance is: " + account.getBalance());
break;
case 4:
System.out.println("Thank you for using the ATM. Goodbye!");
exit = true;
break;
default:
System.out.println("Invalid choice. Please enter a number between 1 and 4.");
}
}
scanner.close();
}
public static void main(String[] args) {
BankAccount userAccount = new BankAccount(1000); // Initialize with initial balance
ATM atm = new ATM(userAccount);
atm.start();
}
}
| Sooriyan12/CODSOFT3 | ATM.java |
1,206 | // { Driver Code Starts
//Initial Template for Java
//Initial Template for Java
//Initial Template for Java
/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
class Array {
// Driver code
public static void main (String[] args) throws IOException{
// Taking input using buffered reader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int testcases = Integer.parseInt(br.readLine());
// looping through all testcases
while(testcases-- > 0){
int sizeOfArray = Integer.parseInt(br.readLine());
int arr [] = new int[sizeOfArray];
String line = br.readLine();
String[] elements = line.trim().split("\\s+");
for(int i = 0;i<sizeOfArray;i++){
arr[i] = Integer.parseInt(elements[i]);
}
Complete obj = new Complete();
arr = obj.game_with_number(arr, sizeOfArray);
for(int i=0; i< sizeOfArray;i++){
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
}
// } Driver Code Ends
//User function Template for Java
class Complete{
// Function for finding maximum and value pair
public static int[] game_with_number (int arr[], int n) {
// Complete the function
for(int i =0 ; i<arr.length -1; i++){
arr[i] = arr[i]|arr[i+1];
}
return arr;
}
}
| Raghav-Verma25/GeeksforGeeks | OR.java |
1,207 |
import java.util.NoSuchElementException;
/**
* Ett vΓ€ldigt enkelt testprogram som testar nΓ₯gra av
* metoderna i Graph och kastar undantag om de inte fungerar.
* <p>
* Absolut inte heltΓ€ckande tester sΓ₯:
* fel == inte ok.
* inga fel != godkΓ€nt (det kan finnas andra fel).
* <p>
* Filen ska inte lΓ€mnas in.
*/
public class I1 {
private static final double VERSION = 2.1;
private static final String UPDATED = "2023-04-11";
private static final String MISSING_NODE = "Z";
private final Graph<String> stringGraph = new ListGraph<>();
public I1() {
System.out.println("A small test program that tries to check to fundamental operations.");
System.out.printf("Version %.1f, last updated %s%n", VERSION, UPDATED);
System.out.println("No errors doesn't mean the code is correct, just that it passed very basic testing.");
}
public static void main(String[] args) throws Exception {
var app = new I1();
// testa att grafen Γ€r tom frΓ₯n start
app.test0_new_graph_is_empty();
// testa att lΓ€gga till nod
app.test1_add_no_duplicate();
// testa att lΓ€gga till samma nod igen
app.test2_add_with_duplicate();
// testa connect
app.test3_connect();
// testa disconnect
app.test4_disconnect();
// testa remove
app.test5_remove();
// klart
app.tests_finished();
}
private void test0_new_graph_is_empty() throws Exception {
if (!stringGraph.getNodes().isEmpty())
throw new Exception("Error: newly created graph should be empty.");
}
private void test1_add_no_duplicate() throws Exception {
stringGraph.add("A");
if (stringGraph.getNodes().size() != 1)
throw new Exception("Error: graph should have 1 node after add 'A'.");
}
private void test2_add_with_duplicate() throws Exception {
stringGraph.add("A");
if (stringGraph.getNodes().size() != 1)
throw new Exception("Error: graph should still have 1 node after add 'A' a second time.");
}
private void test3_connect() throws Exception {
test3_connect_ok();
test3_connect_throws_connection_exists();
test3_connect_throws_missing_node();
test3_connect_throws_negative_weight();
}
private void test3_connect_ok() throws Exception {
stringGraph.add("B");
if (stringGraph.getNodes().size() != 2)
throw new Exception("Error: graph should have 2 nodes after adding 'A' and 'B'");
stringGraph.connect("A", "B", "A <=> B", 1);
if (stringGraph.getEdgeBetween("A", "B") == null)
throw new Exception("Error: no edge exist between 'A' and 'B'. (Or getEdgeBetween doesn't work...");
if (stringGraph.getEdgeBetween("B", "A") == null)
throw new Exception("Error: no edge exist between 'B' and 'A'. (Or getEdgeBetween doesn't work...");
}
private void test3_connect_throws_connection_exists() throws Exception {
stringGraph.add("B");
if (stringGraph.getNodes().size() != 2)
throw new Exception("Error: graph should have 2 node after adding 'A' and 'B'.");
try {
stringGraph.connect("A", "B", "A <=> B", 1);
} catch (IllegalStateException e) {
// ok
return;
}
throw new Exception("Error: should have thrown IllegalStateException.");
}
private void test3_connect_throws_missing_node() throws Exception {
stringGraph.add("B");
if (stringGraph.getNodes().size() != 2)
throw new Exception("Error: graph should have 2 node after adding 'A' and 'B'.");
try {
stringGraph.connect("A", MISSING_NODE, "A <=> Z", 1);
} catch (NoSuchElementException e) {
// ok
return;
}
throw new Exception("Error: should have thrown NoSuchElementException.");
}
private void test3_connect_throws_negative_weight() throws Exception {
stringGraph.add("B");
if (stringGraph.getNodes().size() != 2)
throw new Exception("Error: graph should have 2 node after adding 'A' and 'B'.");
try {
stringGraph.connect("A", "B", "A <=> B", -1);
} catch (IllegalArgumentException e) {
// ok
return;
}
throw new Exception("Error: should have thrown IllegalArgumentException.");
}
private void test4_disconnect() throws Exception {
test4_disconnect_ok();
test4_disconnect_throws_no_connection_exists();
test4_disconnect_throws_missing_node();
}
private void test4_disconnect_ok() throws Exception {
stringGraph.disconnect("A", "B");
if (stringGraph.getEdgeBetween("A", "B") != null) {
throw new Exception("Error: edge not disconnected.");
}
}
private void test4_disconnect_throws_missing_node() throws Exception {
try {
stringGraph.disconnect("A", MISSING_NODE);
} catch (NoSuchElementException e) {
// ok
return;
}
throw new Exception("Error: should have thrown NoSuchElementException.");
}
private void test4_disconnect_throws_no_connection_exists() throws Exception {
stringGraph.add("C");
try {
stringGraph.disconnect("A", "C");
} catch (IllegalStateException e) {
// ok
return;
}
throw new Exception("Error: should have thrown IllegalStateException.");
}
private void test5_remove() throws Exception {
test5_remove_missing_node();
test5_remove_ok();
}
private void test5_remove_missing_node() throws Exception {
try {
stringGraph.remove(MISSING_NODE);
} catch (NoSuchElementException e) {
// ok
return;
}
throw new Exception("Error: should have thrown NoSuchElementException.");
}
private void test5_remove_ok() throws Exception {
stringGraph.remove("C");
if (stringGraph.getNodes().contains("C")) {
throw new Exception("Error: node not removed.");
}
}
private void tests_finished() {
System.out.printf("%n ==> No exceptions thrown so all tests passed. <== %n");
}
}
| DanOzb/Prog2 | Uppgift1/src/I1.java |
1,209 | public class Main {
public static void main(String[] args) {
Main obj = new Main();
int terms = 5, last = 1, secondLast = 0;
System.out.println("WITHOUT RECUSION");
obj.withoutRecusion(terms, last, secondLast);
System.out.println();
System.out.println("WITH RECUSION");
obj.withRecusion(terms);
}
public void withoutRecusion(int terms, int last, int secondLast) {
int current = Integer.MIN_VALUE;
for(int i = 0; i < terms; i++) {
if(i < 2) {
current = i;
} else {
current = last + secondLast;
secondLast = last;
last = current;
}
System.out.print(current + " ");
}
}
public static void withRecusion(int terms) {
for(int i = 0; i < terms; i++) {
System.out.print(fibonacci(i) + " ");
}
}
public static int fibonacci(int num) {
if(num < 2)
return num;
return fibonacci(num - 1) + fibonacci(num - 2);
}
}
| tushar-cero/LP3 | A1.java |
1,211 | public class p9 {
public static void main(String[] args) {
Bank bank = new Bank();
SavingsAccount savings = new SavingsAccount(5000);
CheckingAccount checking = new CheckingAccount(3000);
Transaction transaction = new Transaction();
transaction.performTransaction(savings, 1000, true); // Deposit
transaction.performTransaction(checking, 500, false); // Withdraw
System.out.println("Total Bank Accounts: " + Bank.getTotalAccounts());
}
static class Bank {
private static int totalAccounts = 0;
public Bank() {
totalAccounts++;
}
public static int getTotalAccounts() {
return totalAccounts;
}
}
static abstract class Account {
protected double balance;
public Account(double balance) {
this.balance = balance;
}
public abstract void deposit(double amount);
public abstract void withdraw(double amount);
public abstract double getBalance();
}
static class SavingsAccount extends Account {
public SavingsAccount(double balance) {
super(balance);
}
@Override
public void deposit(double amount) {
balance += amount;
}
@Override
public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
} else {
System.out.println("Insufficient balance!");
}
}
@Override
public double getBalance() {
return balance;
}
}
static class CheckingAccount extends Account {
public CheckingAccount(double balance) {
super(balance);
}
@Override
public void deposit(double amount) {
balance += amount;
}
@Override
public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
} else {
System.out.println("Insufficient balance!");
}
}
@Override
public double getBalance() {
return balance;
}
}
static class Transaction {
private final double transactionFee = 1.00;
public final void performTransaction(Account account, double amount, boolean isDeposit) {
if (isDeposit) {
account.deposit(amount);
} else {
account.withdraw(amount);
}
account.withdraw(transactionFee); // Deducting transaction fee
System.out.println("Transaction successful. Current Balance: " + account.getBalance());
}
}
}
| Faizan560/izag | p9.java |
1,212 | // To compile:
//
// javac Q3.java
import java.util.concurrent.atomic.*;
import java.util.Random;
class Q3 {
class SharedArr {
public volatile int[] integers;
SharedArr(int X) {
this.integers = new int[X];
Random rand = new Random();
for (int n = 0; n < X; n++) {
this.integers[n] = rand.nextInt(999) + 1;
}
}
}
class Runner implements Runnable {
int threadN;
int reps;
boolean multithreading;
SharedArr array;
volatile int s;
Runner(SharedArr array, int threadN, int reps, boolean multithreading) {
this.array = array;
this.threadN = threadN;
this.reps = reps;
this.multithreading = multithreading;
}
public void sumWithoutLock() {
this.s = 0;
for (int n : this.array.integers) {
this.s += n;
}
}
public synchronized void sum() {
this.s = 0;
for (int n : this.array.integers) {
this.s += n;
}
}
@Override
public void run() {
if (!multithreading) {
for (int r = 0; r < reps; r++) {
this.sumWithoutLock();
}
} else {
boolean isFirstThread = (this.threadN == 0) ? true : false;
if (isFirstThread) {
for (int r = 0; r < reps; r++) {
this.sum();
}
} else {
while (!Thread.currentThread().isInterrupted()) {
this.sum();
}
}
}
}
}
Q3() {
Long startTime, endTime;
SharedArr testArray5 = new SharedArr(5);
SharedArr testArray5000 = new SharedArr(5000);
int reps = 50000;
Runner runner;
Thread t;
// X = 5, no lock.
float timeSum = 0;
for (int x = 0; x < 10; x++) {
runner = new Runner(testArray5, 0, reps, false);
startTime = System.nanoTime();
try {
t = new Thread(runner);
t.start();
t.join();
} catch (InterruptedException ie) {
System.out.println("Caught " + ie);
}
endTime = System.nanoTime();
timeSum += (endTime - startTime);
}
System.out.println("Average with X = 5, no lock, single thread: " + timeSum / 10 / 1000000000);
// X = 5000, no lock.
timeSum = 0;
for (int x = 0; x < 10; x++) {
runner = new Runner(testArray5000, 0, reps, false);
startTime = System.nanoTime();
try {
t = new Thread(runner);
t.start();
t.join();
} catch (InterruptedException ie) {
System.out.println("Caught " + ie);
}
endTime = System.nanoTime();
timeSum += (endTime - startTime);
}
System.out.println("Average with X = 5000, no lock, single thread: " + timeSum / 10 / 1000000000);
System.out.println();
float[] results;
Thread[] threads;
Runner[] runners;
int cores = Runtime.getRuntime().availableProcessors();
int maxThreads = cores * 2;
long duration;
// X = 5, built-in lock.
System.out.println("Average with X = 5, built-in lock, multithread: ");
for (int x = 0; x < 10; x++) {
results = new float[maxThreads];
for (int ts = 1; ts < (maxThreads + 1); ts++) {
startTime = System.nanoTime();
try {
threads = new Thread[ts];
runners = new Runner[ts];
for (int p = 0; p < ts; p++) {
runners[p] = new Runner(testArray5, p, reps, true);
threads[p] = new Thread(runners[p]);
threads[p].start();
}
threads[0].join();
for (int p = 1; p < ts; p++) {
threads[p].interrupt();
}
} catch (InterruptedException ie) {
System.out.println("Caught " + ie);
}
endTime = System.nanoTime();
duration = (endTime - startTime);
results[ts - 1] = (float) duration / 1000000000;
}
for (int n = 0; n < maxThreads; n++) {
System.out.printf("%.9f", results[n]);
if (n < (maxThreads - 1)) {
System.out.print(", ");
}
}
System.out.println("");
}
// X = 5000, built-in lock.
System.out.println("Average with X = 5000, built-in lock, multithread: ");
for (int x = 0; x < 10; x++) {
results = new float[maxThreads];
for (int ts = 1; ts < (maxThreads + 1); ts++) {
startTime = System.nanoTime();
try {
threads = new Thread[ts];
runners = new Runner[ts];
for (int p = 0; p < ts; p++) {
runners[p] = new Runner(testArray5000, p, reps, true);
threads[p] = new Thread(runners[p]);
threads[p].start();
}
threads[0].join();
for (int p = 1; p < ts; p++) {
threads[p].interrupt();
}
} catch (InterruptedException ie) {
System.out.println("Caught " + ie);
}
endTime = System.nanoTime();
duration = (endTime - startTime);
results[ts - 1] = (float) duration / 1000000000;
}
for (int n = 0; n < maxThreads; n++) {
System.out.printf("%.9f", results[n]);
if (n < (maxThreads - 1)) {
System.out.print(", ");
}
}
System.out.println("");
}
}
public static void main(String args[]) {
Q3 obj = new Q3();
}
}
| chongyangshi/R204 | Q3.java |
1,213 | package csw;
class Person {
private String firstname;
private String lastname;
private int age;
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public static void main(String[] args) {
Person p = new Person();
p.setFirstname("hello");
p.setLastname("world");
p.setAge(20);
System.out.println(p.getFirstname());
System.out.println(p.getLastname());
System.out.println(p.getAge());
}
}
class WithoutToString {
public static void main(String[] args) {
// TODO Auto-generated method stub
Person p = new Person();
System.out.println(p.toString());
System.out.println(p);
System.out.println(p.hashCode());
Person p1 = new Person();
System.out.println(p1.hashCode());
}
} | DurganandChoudhary/CSW2_JAVA | uu.java |
1,214 | import java.util.*;
abstract class Account
{
private int ano;
protected int balance;
{
balance = 0;
}
public Account(int ano,int balance)
{
this.ano = ano;
this.balance = balance;
}
public int checkBal()
{
return balance;
}
public void deposit(int deposit)
{
balance = balance + deposit;
}
public int withdraw(int withdraw)
{
balance = balance-withdraw;
return balance;
}
public void display()
{
System.out.print("\n\t Account No : "+ano);
System.out.print("\n\t Account Balance : "+checkBal());
}
}
class Saving extends Account
{
private int roi;
private int ano;
public Saving(int ano,int balance,int roi)
{
super(ano,balance);
this.ano = ano;
this.roi = roi;
}
public void display()
{
super.display();
System.out.print("\n\t Rate of Intrest : "+roi+"\n");
}
}
class Current extends Account
{
private int odl;
private int ano;
private int withdraw;
private int usedodl,remainingodl;
public Current(int ano,int balance,int odl)
{
super(ano,balance);
this.ano = ano;
this.odl = odl;
}
public int withdraw(int withdraw)
{
if(withdraw > checkBal())
{
balance = balance + odl;
super.withdraw(balance);
return super.checkBal();
}
else
{
super.withdraw(withdraw);
return super.checkBal();
}
}
public void display()
{
super.display();
System.out.print("\n\t Over draft Limit : "+odl+"\n");
System.out.print("\n\t Used over Draft Limit : "+usedodl+"\n");
System.out.print("\n\t Remaining over draft Limit : "+remainingodl+"\n");
}
}
class Q9
{
public static void main(String args[])
{
int ch,accountno=10101,roi = 6,odl = 50000;
String acctype;
int temp=1;
Scanner sc = new Scanner(System.in);
System.out.print("\n\tCreate your Account.");
System.out.print("\n\tEnter your Name : ");
String name = sc.nextLine();
System.out.print("\n\t:: Select your account Type :: ");
System.out.print("\n\tPress 1 for Saving ");
System.out.print("\n\tPress 2 For Current ");
temp = Integer.parseInt(sc.nextLine());
System.out.print("\n\t"+temp);
if(temp == 1)
{
acctype = "Saving";
}
else if(temp == 2)
{
acctype = "Current";
}
else
{
System.out.print("\n\t Please Fill information carefully");
System.out.print("\n\t Please try it again....");
return;
}
System.out.print("\n\tEnter opening balance : ");
int balance = Integer.parseInt(sc.nextLine());
Account obj=null;
if(temp == 1)
{
obj = new Saving(accountno,balance,roi);
}
if(temp == 2)
{
obj = new Current(accountno,balance,odl);
}
do{
System.out.print("\n\t1.Deposit.");
System.out.print("\n\t2.Withdraw.");
System.out.print("\n\t3.Check Balance.");
System.out.print("\n\t4.Check Account infromation.");
System.out.print("\n\t0. Exit ");
System.out.print("\n\tPlease Enter your choice : ");
ch = Integer.parseInt(sc.nextLine());
switch(ch)
{
case 1 :
int deposit;
System.out.print("\n\t Please Enter the amount to deposit : ");
deposit = Integer.parseInt(sc.nextLine());
if(deposit < 0)
{
System.out.printf("\n\t Negative amount can't be deposited");
break;
}
else
{
obj.deposit(deposit);
System.out.print("\n\t Amount deposited successfully\n\tyour closing balance is "+obj.checkBal());
}
break;
case 2 :
int withdraw;
System.out.print("\n\t Please Enter the amount to deposit : ");
withdraw = Integer.parseInt(sc.nextLine());
if(acctype == "Saving")
{
if(withdraw > obj.checkBal())
{
System.out.printf("\n\t Incefficient Balance for withdraw");
break;
}
else
{
obj.withdraw(withdraw);
System.out.print("\n\t Amount Withdraw successfully\n\tyour closing balance is "+obj.checkBal());
}
}
else
{
if(withdraw > (obj.checkBal()+odl))
{
System.out.printf("\n\t Incefficient Balance for withdraw");
}
else
{
obj.withdraw(withdraw);
}
}
break;
case 3 :
System.out.print("\n\t Balance of "+accountno+" is "+obj.checkBal());
break;
case 4 :
System.out.print("\n\t Accont Holder Name : "+name);
obj.display();
break;
case 0 :
break;
default :
System.out.print("\n\t Please enter proper choice");
break;
}
}while(ch!=0);
}
}
| Raj-Patoliya/Sem-1-Java-Programs | Q9.java |
1,215 | import java.util.Scanner;
class acc{
String name;
int acNo;
int time;
int amount;
acc(){
Scanner sc = new Scanner(System.in);
name = sc.nextLine();
acNo = sc.nextInt();
time = sc.nextInt();
amount = sc.nextInt();
}
void withdrawAmt(){
Scanner sc = new Scanner(System.in);
int withdraw = sc.nextInt();
if(withdraw < amount){
amount -=withdraw;
System.out.println("amount withdrawn from account");
}else{
System.out.println("Insufficient balance");
}
}
void print(){
System.out.println("name : " +name);
System.out.println("account number : " +acNo);
System.out.println("Time : " +time);
System.out.println("Amount : " +amount);
}
}
public class fd {
public static void main(String[] args) {
acc p1 = new acc();
p1.withdrawAmt();
p1.print();
}
}
| DAnand05/Java | fd.java |
1,218 | class Solution {
public int maxArea(int[] height) {
int left = 0, right = height.length - 1;
int maxArea = 0;
while (left < right) {
maxArea = Math.max(maxArea, Math.min(height[left], height[right])
* (right - left));
if (height[left] < height[right])
left++;
else
right--;
}
return maxArea;
}
} | caomingkai/Leetcode | 11. Container With Most Water.java |
1,222 | import java.util.Scanner;
import java.io.*;
class exception extends Exception
{
exception()
{
System.out.println("Insufficient Balance");
}
}
class main
{
int bal=0;
void deposit(int amt)
{
bal=bal+amt;
System.out.println("Balance:"+bal);
}
void withdraw(int amt)throws exception
{
if(bal<500)
throw new exception();
else if(bal<amt)
throw new exception();
else
{
bal=bal-amt;
System.out.println("Balance:"+bal);
}
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
main obj=new main();
int opt;
do
{
System.out.println("1.Deposit");
System.out.println("2.Withdraw");
System.out.println("3.Exit");
opt=sc.nextInt();
if(opt==1)
{
System.out.println("Enter the amount to be deposited");
int amt=sc.nextInt();
obj.deposit(amt);
}
else if(opt==2)
{
System.out.println("Enter the amount to be withdrawn");
int amt=sc.nextInt();
try
{
obj.withdraw(amt);
}
catch(exception e)
{}
}
else if(opt!=3)
System.out.println("Enter a valid option");
}while(opt!=3);
}
}
| miraz00/exp6 | 2.java |
1,223 | //P1
//Section 5
//Student ID: 006152874
//Renteria, Carlos,
import java.util.*;
import java.sql.*;
import java.io.*;
public class p1 {
private static String db, user, pwd, driver;
private static int opt;
private static Scanner in = new Scanner(System.in);
private static Scanner input = new Scanner(System.in);
public static void main(String args[]) {
if (args.length != 1) {
System.out.println("Need props file.");
}
else {
init(args[0]);
try {
Class.forName(driver);
/*Connection var*/
Connection conn = null;
/*SQL statement var*/
Statement stmt = null;
conn = DriverManager.getConnection(db, user, pwd);
stmt = conn.createStatement();
mainScreen(stmt);
stmt.close();
conn.close();
} catch (SQLException sqlE) {
sqlE.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
private static void init(String filename) {
try {
Properties props = new Properties();
FileInputStream input = new FileInputStream(filename);
props.load(input);
driver = props.getProperty("jdbc.driver");
db = props.getProperty("jdbc.url");
user = props.getProperty("jdbc.username");
pwd = props.getProperty("jdbc.password");
} catch (Exception e) {
System.out.println("Exception in init()");
e.printStackTrace();
}
}
private static void mainScreen(Statement stmt) throws SQLException {
boolean done = false;
while (!done) {
System.out.println("Welcome to the Self Service Banking System!" +
"\n1. New Customer" +
"\n2. Customer Login" +
"\n3. Exit");
/*Get user input*/
opt = in.nextInt();
switch (opt) {
case 1:
//Prompt for Name Gender Age and Pin, return Id if successful
int id = -1;
System.out.print("Name: ");
String name = input.nextLine();
boolean finished = false;
String gender = "";
while (!finished) {
System.out.print("Gender (M/F): ");
gender = input.nextLine();
if ("mMfF".contains(gender))
finished = true;
}
System.out.print("Age: ");
int age = in.nextInt();
System.out.print("Pin: ");
int pin = in.nextInt();
//Do db call with an insert then return id
id = newCust(name, gender, age, pin, stmt);
System.out.println("YOUR ID IS: " + id);
break;
case 2:
//Prompt for customer ID and pin to authenticate,
//if customer enters 0 for ID and pin go to screen #4
System.out.print("ID: ");
int custId = in.nextInt();
System.out.print("Pin: ");
int custPin = in.nextInt();
if (custId == 0 && custPin == 0) {
adminLogin(stmt);
}
else if (authenticated(custId, custPin, stmt)) {
customerScreen(custId, custPin, stmt);
} else {
System.out.println("WRONG ID OR PIN.");
}
break;
case 3:
//Exit
done = true;
break;
default:
System.out.println("Please choose a valid option (1, 2, or 3).");
break;
}
}
}
private static void adminLogin(Statement stmt) throws SQLException {
boolean done = false;
int id;
while (!done) {
System.out.println("Administrator Main Menu " +
"\n1. Account Summary for a Customer " +
"\n2. Report A :: Customer Information with Total Balance in Decreasing Order " +
"\n3. Report B :: Find the Average Total Balance Between Age Groups" +
"\n4. Exit");
opt = in.nextInt();
switch (opt) {
case 1:
//Get account summary for a customer, provide a customer id
System.out.print("ID: ");
id = in.nextInt();
accSummary(id, stmt);
break;
case 2:
//You would display customer Id, Name, age, gender and total balance
//System.out.print("ID: ");
//id = in.nextInt();
custInfo(stmt);//id, stmt);
break;
case 3:
//Find average total balance between age groups
int minAge, maxAge;
System.out.println("Min age: ");
minAge = in.nextInt();
System.out.println("Max age: ");
maxAge = in.nextInt();
avgTotalBal(minAge, maxAge, stmt);
break;
case 4:
//Exit
done = true;
break;
default:
System.out.println("Please choose a valid option (1, 2, 3, or 4).");
}
}
}
private static void avgTotalBal(int minAge, int maxAge, Statement stmt) throws SQLException {
String sqlAvgTotal = "select avg(age) as \"Average Age\", avg(balance) as \"Average Balance\" "+
"from p1.customer as C, p1.account as A "+
"where C.age >= " + minAge + " and C.age <= "+ maxAge +
" and A.status = 'A'";
ResultSet rs = stmt.executeQuery(sqlAvgTotal);
int age, balance;
System.out.println("AVERAGE AGE\tAVERAGE BALANCE");
while (rs.next()) {
age = rs.getInt("Average age");
balance = rs.getInt("Average Balance");
System.out.println(age + "\t\t" + balance);
}
rs.close();
}
private static void custInfo(Statement stmt) throws SQLException {
String sqlInfo = "select C.ID, Name, Age, Gender, sum(balance) as \"TOTAL BALANCE\" "+
"from p1.customer as C, p1.account as A " +
"where C.id = A.id and A.status = 'A'" +
"group by C.ID, Name, Age, Gender " +
"order by \"TOTAL BALANCE\" desc";
String name, gender;
int id, age, total;
ResultSet rs = stmt.executeQuery(sqlInfo);
System.out.println("ID\tNAME\t\tAGE\tGENDER\tTOTAL BALANCE");
while (rs.next()) {
id = rs.getInt("ID");
name = rs.getString("Name");
age = rs.getInt("Age");
gender = rs.getString("Gender");
total = rs.getInt("TOTAL BALANCE");
if (name.length() >= 10)
System.out.println(id +"\t" + name + "\t" + age + "\t" + gender + "\t" + total);
else
System.out.println(id +"\t" + name + "\t\t" + age + "\t" + gender + "\t" + total);
}
rs.close();
}
private static void customerScreen(int custId, int custPin, Statement stmt) throws SQLException {
boolean done = false;
int balance, accNum, accNum2, id, amount;
String accType;
while (!done) {
System.out.println("Customer Main Menu" +
"\n1. Open Account" +
"\n2. Close Account" +
"\n3. Deposit" +
"\n4. Withdraw" +
"\n5. Transfer" +
"\n6. Account Summary" +
"\n7. Exit");
opt = in.nextInt();
switch (opt) {
case 1:
//Prompt for id, account type, initial balance
//returns account number if successful.
System.out.print("Enter an ID: ");
id = in.nextInt();
System.out.print("What type of account (C)hecking, or (S)avings: ");
accType = input.nextLine();
System.out.print("Enter your initial balance: ");
balance = in.nextInt();
accNum = newAccount(id, accType, balance, stmt);
System.out.println("Your account number is: " + accNum);
break;
case 2:
//Prompt for account number, then change the status to I
//and empty the account balance
System.out.print("Enter an account number: ");
accNum = in.nextInt();
closeAccount(custId, accNum, stmt);
break;
case 3:
//Prompt for account number and amount to deposit
System.out.print("Enter an account number: ");
accNum = in.nextInt();
System.out.print("Enter the amount to deposit: ");
amount = in.nextInt();
deposit(accNum, amount, stmt);
break;
case 4:
//prompt for account number and amount to withdraw
System.out.print("Enter your account number: ");
accNum = in.nextInt();
System.out.print("Enter the amount to withdraw: ");
amount = in.nextInt();
if (!validAcc(accNum, stmt)) {
System.out.println("Invalid account number.");
} else {
withdraw(custId, accNum, amount, stmt);
}
break;
case 5:
//prompt for the source and destination account number and amount
System.out.print("Enter source account number: ");
accNum = in.nextInt();
System.out.print("Enter destination account number: ");
accNum2 = in.nextInt();
System.out.print("Enter transfer amount: ");
amount = in.nextInt();
if (validAcc(accNum, stmt) && validAcc(accNum2, stmt)) {
transfer(custId, accNum, accNum2, amount, stmt);
} else {
System.out.println("Invalid account number(s).");
}
break;
case 6:
//The total balance and each account number and its balance
//that belong to the same customer
accSummary(custId, stmt);
break;
case 7:
//Go back to the previous screen
done = true;
break;
default:
System.out.println("Please choose a valid option (1, 2, 3, 4, 5, 6, or 7).");
break;
}
}
}
private static boolean isOwner(int id, int accNum, Statement stmt) throws SQLException {
String sqlGetID = "select id from p1.account where number = "+accNum;
ResultSet rs = stmt.executeQuery(sqlGetID);
boolean owner = false;
while (rs.next()) {
owner = id == rs.getInt("ID") ? true : false;
}
rs.close();
return owner;
}
private static void accSummary(int custId, Statement stmt) throws SQLException {
String sqlSummary = "select sum(balance) as \"TOTAL BALANCE\" from p1.account where id = "+custId;
int totalBal = -1, accNum, balance;
ResultSet rs1 = stmt.executeQuery(sqlSummary);
while (rs1.next()) {
totalBal = rs1.getInt("TOTAL BALANCE");
}
sqlSummary = "select number, balance from p1.account where id ="+custId + " and status = 'A'";
ResultSet rs2 = stmt.executeQuery(sqlSummary);
System.out.println("TOTAL BALANCE\tACCOUNT\tBALANCE");
String output = totalBal+"";
while(rs2.next()) {
accNum = rs2.getInt("Number");
balance = rs2.getInt("Balance");
output += "\t\t"+accNum +"\t"+balance;
System.out.println(output);
output = "";
}
rs1.close();
rs2.close();
}
private static void transfer(int custId, int accNum, int accNum2, int amount,
Statement stmt) throws SQLException {
if (isOwner(custId, accNum, stmt)) {
withdraw(custId, accNum, amount, stmt);
deposit(accNum2, amount, stmt);
} else {
System.out.println("You cannot transfer from an account that you do not own.");
}
}
private static void withdraw(int id, int accNum, int amt, Statement stmt) throws SQLException {
if (isOwner(id, accNum, stmt)) {
String sqlWithdraw = "update p1.account set balance = " +
"(select balance from p1.account where number = "+accNum+")-"+amt+" where number = "+accNum;
stmt.executeUpdate(sqlWithdraw);
} else {
System.out.println("You are not the owner of " + accNum);
}
}
private static boolean validAcc(int accNum, Statement stmt) throws SQLException {
String sqlValidateAcc = "select id from p1.account where number = "+accNum;
ResultSet rs = stmt.executeQuery(sqlValidateAcc);
int id = -1;
while (rs.next()) {
id = rs.getInt("ID");
}
rs.close();
return id >= 100 ? true : false;
}
private static void deposit(int accNum, int amt, Statement stmt) throws SQLException {
String sqlDeposit = "update p1.account set balance =" +
"(select balance from p1.account where number ="+accNum+")+"+amt+" where number = "+accNum;
stmt.executeUpdate(sqlDeposit);
}
private static void closeAccount(int id, int accNum, Statement stmt) throws SQLException {
if (isOwner(id, accNum, stmt)) {
String sqlClose = "update p1.account set status = 'I', balance = 0 where number =" + accNum;
stmt.executeUpdate(sqlClose);
System.out.println("Account "+accNum+" has been closed.");
} else {
System.out.println("You are not the owner of " + accNum);
}
}
private static int newAccount(int id, String accType, int inBalance,
Statement stmt) throws SQLException {
int accNum = -1;
String sqlMakeAcc = "insert into p1.account (id, balance, type, status) " +
"values ("+id+","+inBalance+",'"+accType+"','A')";
stmt.executeUpdate(sqlMakeAcc);
String getAccNum = "select Number from p1.account where id ='"+id+"'";
ResultSet rs = stmt.executeQuery(getAccNum);
while(rs.next()) {
accNum = rs.getInt("Number");
}
return accNum;
}
private static boolean authenticated(int id, int pin, Statement stmt) throws SQLException {
String sqlVerify = "select pin from p1.customer where id ='" + id + "'";
ResultSet rs = stmt.executeQuery(sqlVerify);
int thePin = -1;
while (rs.next()) {
thePin = rs.getInt("Pin");
}
rs.close();
return thePin == pin ? true : false;
}
private static int newCust(String name, String gender, int age,
int pin, Statement stmt) throws SQLException {
String sql = "insert into P1.Customer (Name, Gender, Age, Pin) values ('"+name+"','"+gender+"',"+age+","+pin+")";
stmt.executeUpdate(sql);
sql = "select id from P1.Customer where name='"+name+"' and gender='"+gender+"' and age='"+age+"'";
ResultSet rs = stmt.executeQuery(sql);
int id = 0;
while (rs.next()) {
id = rs.getInt("ID");
}
rs.close();
return id;
}
}
| crrenter/JDBC-Banking-App | p1.java |