I've recently stumbled upon Tiny GP (A Genetic Programming program), and I found it pretty useful, so I decided to change all System.out.println() in the program to a write to text file method.
Problem: In the text file, for some reason, only says "PROBLEM SOLVED", instead of printing out generations and other things that it is supposed to (see code).
Tiny GP modified class file:
package main;
/*
* Program: tiny_gp.java
*
* Author: Riccardo Poli (email: rpoli#essex.ac.uk)
*
* Modified by Preston Tang
*/
import java.util.*;
import java.io.*;
import java.text.DecimalFormat;
public class tiny_gp {
String Name;
double[] fitness;
char[][] pop;
static Random rd = new Random();
static final int ADD = 110,
SUB = 111,
MUL = 112,
DIV = 113,
FSET_START = ADD,
FSET_END = DIV;
static double[] x = new double[FSET_START];
static double minrandom, maxrandom;
static char[] program;
static int PC;
static int varnumber, fitnesscases, randomnumber;
static double fbestpop = 0.0, favgpop = 0.0;
static long seed;
static double avg_len;
static final int MAX_LEN = 10000,
POPSIZE = 100000,
DEPTH = 5,
GENERATIONS = 100,
TSIZE = 2;
public static final double PMUT_PER_NODE = 0.05,
CROSSOVER_PROB = 0.9;
public static double[][] targets;
public double run() {
/* Interpreter */
char primitive = program[PC++];
if (primitive < FSET_START) {
return (x[primitive]);
}
switch (primitive) {
case ADD:
return (run() + run());
case SUB:
return (run() - run());
case MUL:
return (run() * run());
case DIV: {
double num = run(), den = run();
if (Math.abs(den) <= 0.001) {
return (num);
} else {
return (num / den);
}
}
}
return (0.0); // should never get here
}
public int traverse(char[] buffer, int buffercount) {
if (buffer[buffercount] < FSET_START) {
return (++buffercount);
}
switch (buffer[buffercount]) {
case ADD:
case SUB:
case MUL:
case DIV:
return (traverse(buffer, traverse(buffer, ++buffercount)));
}
return (0); // should never get here
}
public void setup_fitness(String fname) {
try {
int i, j;
String line;
BufferedReader in
= new BufferedReader(
new FileReader(fname));
line = in.readLine();
StringTokenizer tokens = new StringTokenizer(line);
varnumber = Integer.parseInt(tokens.nextToken().trim());
randomnumber = Integer.parseInt(tokens.nextToken().trim());
minrandom = Double.parseDouble(tokens.nextToken().trim());
maxrandom = Double.parseDouble(tokens.nextToken().trim());
fitnesscases = Integer.parseInt(tokens.nextToken().trim());
targets = new double[fitnesscases][varnumber + 1];
if (varnumber + randomnumber >= FSET_START) {
Write("too many variables and constants");
//System.out.println("too many variables and constants");
}
for (i = 0; i < fitnesscases; i++) {
line = in.readLine();
tokens = new StringTokenizer(line);
for (j = 0; j <= varnumber; j++) {
targets[i][j] = Double.parseDouble(tokens.nextToken().trim());
}
}
in.close();
} catch (FileNotFoundException e) {
Write("ERROR: Please provide a data file");
//System.out.println("ERROR: Please provide a data file");
System.exit(0);
} catch (Exception e) {
Write("ERROR: Incorrect data format");
//System.out.println("ERROR: Incorrect data format");
System.exit(0);
}
}
public double fitness_function(char[] Prog) {
int i = 0, len;
double result, fit = 0.0;
len = traverse(Prog, 0);
for (i = 0; i < fitnesscases; i++) {
for (int j = 0; j < varnumber; j++) {
x[j] = targets[i][j];
}
program = Prog;
PC = 0;
result = run();
fit += Math.abs(result - targets[i][varnumber]);
}
return (-fit);
}
public int grow(char[] buffer, int pos, int max, int depth) {
char prim = (char) rd.nextInt(2);
int one_child;
if (pos >= max) {
return (-1);
}
if (pos == 0) {
prim = 1;
}
if (prim == 0 || depth == 0) {
prim = (char) rd.nextInt(varnumber + randomnumber);
buffer[pos] = prim;
return (pos + 1);
} else {
prim = (char) (rd.nextInt(FSET_END - FSET_START + 1) + FSET_START);
switch (prim) {
case ADD:
case SUB:
case MUL:
case DIV:
buffer[pos] = prim;
one_child = grow(buffer, pos + 1, max, depth - 1);
if (one_child < 0) {
return (-1);
}
return (grow(buffer, one_child, max, depth - 1));
}
}
return (0); // should never get here
}
public int print_indiv(char[] buffer, int buffercounter) {
int a1 = 0, a2;
if (buffer[buffercounter] < FSET_START) {
if (buffer[buffercounter] < varnumber) {
Write("X" + (buffer[buffercounter] + 1) + " ");
//System.out.print("X" + (buffer[buffercounter] + 1) + " ");
} else {
WriteDouble(x[buffer[buffercounter]]);
//System.out.print(x[buffer[buffercounter]]);
}
return (++buffercounter);
}
switch (buffer[buffercounter]) {
case ADD:
Write("(");
//System.out.print("(");
a1 = print_indiv(buffer, ++buffercounter);
Write(" + ");
//System.out.print(" + ");
break;
case SUB:
Write("(");
//System.out.print("(");
a1 = print_indiv(buffer, ++buffercounter);
Write(" - ");
//System.out.print(" - ");
break;
case MUL:
Write("(");
//System.out.print("(");
a1 = print_indiv(buffer, ++buffercounter);
Write(" * ");
//System.out.print(" * ");
break;
case DIV:
Write("(");
//System.out.print("(");
a1 = print_indiv(buffer, ++buffercounter);
Write(" / ");
//System.out.print(" / ");
break;
}
a2 = print_indiv(buffer, a1);
Write(")");
//System.out.print(")");
return (a2);
}
public static char[] buffer = new char[MAX_LEN];
public char[] create_random_indiv(int depth) {
char[] ind;
int len;
len = grow(buffer, 0, MAX_LEN, depth);
while (len < 0) {
len = grow(buffer, 0, MAX_LEN, depth);
}
ind = new char[len];
System.arraycopy(buffer, 0, ind, 0, len);
return (ind);
}
public char[][] create_random_pop(int n, int depth, double[] fitness) {
char[][] pop = new char[n][];
int i;
for (i = 0; i < n; i++) {
pop[i] = create_random_indiv(depth);
fitness[i] = fitness_function(pop[i]);
}
return (pop);
}
public void stats(double[] fitness, char[][] pop, int gen) {
int i, best = rd.nextInt(POPSIZE);
int node_count = 0;
fbestpop = fitness[best];
favgpop = 0.0;
for (i = 0; i < POPSIZE; i++) {
node_count += traverse(pop[i], 0);
favgpop += fitness[i];
if (fitness[i] > fbestpop) {
best = i;
fbestpop = fitness[i];
}
}
avg_len = (double) node_count / POPSIZE;
favgpop /= POPSIZE;
Write("Generation=" + gen + " Avg Fitness=" + (-favgpop)
+ " Best Fitness=" + (-fbestpop) + " Avg Size=" + avg_len
+ "\nBest Individual: ");
//System.out.print("Generation=" + gen + " Avg Fitness=" + (-favgpop)
// + " Best Fitness=" + (-fbestpop) + " Avg Size=" + avg_len
// + "\nBest Individual: ");
print_indiv(pop[best], 0);
Write("\n");
//System.out.print("\n");
//System.out.flush();
}
public int tournament(double[] fitness, int tsize) {
int best = rd.nextInt(POPSIZE), i, competitor;
double fbest = -1.0e34;
for (i = 0; i < tsize; i++) {
competitor = rd.nextInt(POPSIZE);
if (fitness[competitor] > fbest) {
fbest = fitness[competitor];
best = competitor;
}
}
return (best);
}
public int negative_tournament(double[] fitness, int tsize) {
int worst = rd.nextInt(POPSIZE), i, competitor;
double fworst = 1e34;
for (i = 0; i < tsize; i++) {
competitor = rd.nextInt(POPSIZE);
if (fitness[competitor] < fworst) {
fworst = fitness[competitor];
worst = competitor;
}
}
return (worst);
}
public char[] crossover(char[] parent1, char[] parent2) {
int xo1start, xo1end, xo2start, xo2end;
char[] offspring;
int len1 = traverse(parent1, 0);
int len2 = traverse(parent2, 0);
int lenoff;
xo1start = rd.nextInt(len1);
xo1end = traverse(parent1, xo1start);
xo2start = rd.nextInt(len2);
xo2end = traverse(parent2, xo2start);
lenoff = xo1start + (xo2end - xo2start) + (len1 - xo1end);
offspring = new char[lenoff];
System.arraycopy(parent1, 0, offspring, 0, xo1start);
System.arraycopy(parent2, xo2start, offspring, xo1start,
(xo2end - xo2start));
System.arraycopy(parent1, xo1end, offspring,
xo1start + (xo2end - xo2start),
(len1 - xo1end));
return (offspring);
}
public char[] mutation(char[] parent, double pmut) {
int len = traverse(parent, 0), i;
int mutsite;
char[] parentcopy = new char[len];
System.arraycopy(parent, 0, parentcopy, 0, len);
for (i = 0; i < len; i++) {
if (rd.nextDouble() < pmut) {
mutsite = i;
if (parentcopy[mutsite] < FSET_START) {
parentcopy[mutsite] = (char) rd.nextInt(varnumber + randomnumber);
} else {
switch (parentcopy[mutsite]) {
case ADD:
case SUB:
case MUL:
case DIV:
parentcopy[mutsite]
= (char) (rd.nextInt(FSET_END - FSET_START + 1)
+ FSET_START);
}
}
}
}
return (parentcopy);
}
public void print_parms() {
Write("-- TINY GP (Java version) --\n");
//System.out.print("-- TINY GP (Java version) --\n");
Write("SEED=" + seed + "\nMAX_LEN=" + MAX_LEN
+ "\nPOPSIZE=" + POPSIZE + "\nDEPTH=" + DEPTH
+ "\nCROSSOVER_PROB=" + CROSSOVER_PROB
+ "\nPMUT_PER_NODE=" + PMUT_PER_NODE
+ "\nMIN_RANDOM=" + minrandom
+ "\nMAX_RANDOM=" + maxrandom
+ "\nGENERATIONS=" + GENERATIONS
+ "\nTSIZE=" + TSIZE
+ "\n----------------------------------\n");
// System.out.print("SEED=" + seed + "\nMAX_LEN=" + MAX_LEN
// + "\nPOPSIZE=" + POPSIZE + "\nDEPTH=" + DEPTH
// + "\nCROSSOVER_PROB=" + CROSSOVER_PROB
// + "\nPMUT_PER_NODE=" + PMUT_PER_NODE
// + "\nMIN_RANDOM=" + minrandom
// + "\nMAX_RANDOM=" + maxrandom
// + "\nGENERATIONS=" + GENERATIONS
// + "\nTSIZE=" + TSIZE
// + "\n----------------------------------\n");
}
public tiny_gp(String fname, long s) {
fitness = new double[POPSIZE];
seed = s;
if (seed >= 0) {
rd.setSeed(seed);
}
setup_fitness(fname);
for (int i = 0; i < FSET_START; i++) {
x[i] = (maxrandom - minrandom) * rd.nextDouble() + minrandom;
}
pop = create_random_pop(POPSIZE, DEPTH, fitness);
}
public void evolve() {
int gen = 0, indivs, offspring, parent1, parent2, parent;
double newfit;
char[] newind;
print_parms();
stats(fitness, pop, 0);
for (gen = 1; gen < GENERATIONS; gen++) {
if (fbestpop > -1e-5) {
Write("PROBLEM SOLVED\n");
//System.out.print("PROBLEM SOLVED\n");
System.exit(0);
}
for (indivs = 0; indivs < POPSIZE; indivs++) {
if (rd.nextDouble() < CROSSOVER_PROB) {
parent1 = tournament(fitness, TSIZE);
parent2 = tournament(fitness, TSIZE);
newind = crossover(pop[parent1], pop[parent2]);
} else {
parent = tournament(fitness, TSIZE);
newind = mutation(pop[parent], PMUT_PER_NODE);
}
newfit = fitness_function(newind);
offspring = negative_tournament(fitness, TSIZE);
pop[offspring] = newind;
fitness[offspring] = newfit;
}
stats(fitness, pop, gen);
}
Write("PROBLEM *NOT* SOLVED\n");
//System.out.print("PROBLEM *NOT* SOLVED\n");
System.exit(1);
}
public void Write(String context) {
FileWriter fileWriter;
try {
fileWriter = new FileWriter("GP.txt");
try (BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {
bufferedWriter.write(context);
}
} catch (IOException ex) {
}
}
public void WriteDouble(double context) {
FileWriter fileWriter;
try {
fileWriter = new FileWriter("GP.txt");
try (BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {
String ncontext = Double.toString(context);
bufferedWriter.write(ncontext);
}
} catch (IOException ex) {
}
}
};
The Functions Mapper file that uses the Tiny GP class file:
package function_mapper;
import javax.swing.JOptionPane;
import main.*;
public class Function_Mapper {
public static void main(String[] args) {
String fname = JOptionPane.showInputDialog(null, "File Name", "Input Dialog", JOptionPane.INFORMATION_MESSAGE);
long s = -1;
if (args.length == 2) {
s = Integer.valueOf(args[0]).intValue();
fname = args[1];
}
if (args.length == 1) {
fname = args[0];
}
tiny_gp gp = new tiny_gp(fname, s);
gp.evolve();
}
}
Much help appreciated, thanks!
The Write method overwrites the contents of the file on each invocation. There are two ways to fix this.
An easier one, is to append file, instead of overwriting it. It could be achieved by passing append argument to the FileWriter (I simplified code a little bit along the way).
// true on the next line means "append"
try (Writer writer = new FileWriter("GP.txt", true)) {
writer.write(Double.toString(context));
} catch (IOException ex) {
}
A harder, but much fore efficient one is to openwriter in the constructor, use it in Write method, and close in the specially introduced close method of the tiny_gp.
I am using Ghost4j to convert multipage PDFs to multipage TIFF images. I haven't found an example of how this is done.
Using below code I'm able to convert the multipage PDF to images but how do I create a single multipage TIFF image out of it?
PDFDocument lDocument = new PDFDocument();
lDocument.load(filePath);
// create renderer
SimpleRenderer lRenderer = new SimpleRenderer();
// set resolution (in DPI)
lRenderer.setResolution(300);
// render as images
List<Image> lImages = lRenderer.render(lDocument);
Iterator<Image> lImageIterator = lImages.iterator();
//how to convert the images to a single TIFF image?
While this is not exactly what you are doing I did something similar. I combined multiple images in one directory into a tiff file with separate pages. Take a look at this code and see if you can pick out what you need. Also you will need external jars/libraries for this to work they can be downloaded just google them. I hope this helps you.
public class CombineImages {
private static String directory = null;
private static String combinedImageLocation = null;
private static DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
private static int folderCount = 0;
private static int totalFolderCount = 0;
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter the directory path that contains the images: ");
directory = scanner.nextLine(); //initialize directory
System.out.println("Please enter a location for the new combined images to be placed: ");
combinedImageLocation = scanner.nextLine(); //initialize directory
if(!(combinedImageLocation.charAt((combinedImageLocation.length() - 1)) == '\\'))
{
combinedImageLocation += "\\";
}
if(!(directory.charAt((directory.length() - 1)) == '\\'))
{
directory += "\\";
}
scanner.close();
//directory = "C:\\Users\\sorensenb\\Desktop\\CombinePhotos\\";
//combinedImageLocation = "C:\\Users\\sorensenb\\Desktop\\NewImages\\";
File filesDirectory;
filesDirectory = new File(directory);
File[] files; //holds files in given directory
if(filesDirectory.exists())
{
files = filesDirectory.listFiles();
totalFolderCount = files.length;
folderCount = 0;
if(files != null && (files.length > 0))
{
System.out.println("Start Combining Files...");
System.out.println("Start Time: " + dateFormat.format(new Date()));
combineImages(files);
System.out.println("Finished Combining Files.");
System.out.println("Finish Time: " + dateFormat.format(new Date()));
}
}
else
{
System.out.println("Directory does not exist!");
System.exit(1);
}
}
public static void combineImages(File[] files)
{
int fileCounter = 1;
ArrayList<String> allFiles = new ArrayList<String>();
String folderBase = "";
String parentFolder = "";
String currentFileName = "";
String previousFileName = "";
File previousFile = null;
int counter = 0;
for(File file:files)
{
if(file.isDirectory())
{
folderCount++;
System.out.println("Folder " + folderCount + " out of " + totalFolderCount + " folders.");
combineImages(file.listFiles());
}
else
{
try {
folderBase = file.getParentFile().getCanonicalPath();
parentFolder = file.getParentFile().getName();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(counter == 0)
{
allFiles.add(file.getName().substring(0, file.getName().indexOf('.')));
}
else
{
currentFileName = file.getName();
previousFileName = previousFile.getName();
currentFileName = currentFileName.substring(0, currentFileName.indexOf('.'));
previousFileName = previousFileName.substring(0, previousFileName.indexOf('.'));
if(!currentFileName.equalsIgnoreCase(previousFileName))
{
allFiles.add(currentFileName);
}
}
}
previousFile = file;
counter++;
}
System.out.println("Total Files to be Combined: " + allFiles.size());
for(String currentFile:allFiles)
{
System.out.println("File " + fileCounter + " out of " + allFiles.size() + " CurrentFile: " + currentFile);
try {
createNewImage(currentFile, files, folderBase, parentFolder);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fileCounter++;
}
}
***public static void createNewImage(String currentFile, File[] files, String folderBase, String parentFolder) throws IOException
{
//BufferedImage image;
int totalHeight = 0;
int maxWidth = 0;
int currentHeight = 0;
ArrayList<String> allFiles = new ArrayList<String>();
for(File file:files)
{
if((file.getName().substring(0, file.getName().indexOf('.'))).equalsIgnoreCase(currentFile))
{
allFiles.add(file.getName());
}
}
allFiles = sortFiles(allFiles);
BufferedImage image[] = new BufferedImage[allFiles.size()];
SeekableStream ss = null;
PlanarImage op = null;
for (int i = 0; i < allFiles.size(); i++) {
ss = new FileSeekableStream(folderBase + "\\" + allFiles.get(i));
ImageDecoder decoder = ImageCodec.createImageDecoder("tiff", ss, null);
op = new NullOpImage(decoder.decodeAsRenderedImage(0),
null, null, OpImage.OP_IO_BOUND);
image[i] = op.getAsBufferedImage();
}
op.dispose();
ss.close();
/*BufferedImage convertImage;
for(int i = 0; i < image.length; i++)
{
convertImage = new BufferedImage(image[i].getWidth(),image[i].getHeight(), BufferedImage.TYPE_BYTE_GRAY);
Graphics g = convertImage.getGraphics();
g.drawImage(convertImage, 0, 0, null);
g.dispose();
image[i] = convertImage;
}*/
File folderExists = new File(combinedImageLocation);
if(!folderExists.exists())
{
folderExists.mkdirs();
}
TIFFEncodeParam params = new TIFFEncodeParam();
params.setCompression(TIFFEncodeParam.COMPRESSION_GROUP3_1D);
int changeName = 1;
String tempCurrentFile = currentFile;
while((new File(combinedImageLocation + tempCurrentFile + "Combined.tif").exists()))
{
tempCurrentFile = currentFile;
tempCurrentFile += ("(" + changeName + ")");
changeName++;
}
currentFile = tempCurrentFile;
OutputStream out = new FileOutputStream(combinedImageLocation + currentFile + "Combined" + ".tif");
ImageEncoder encoder = ImageCodec.createImageEncoder("tiff", out, params);
Vector vector = new Vector();
for (int i = 1; i < allFiles.size(); i++) {
vector.add(image[i]);
}
params.setExtraImages(vector.iterator());
encoder.encode(image[0]);
for(int i = 0; i < image.length; i++)
{
image[i].flush();
}
out.close();
System.gc();
/*for(String file:allFiles)
{
image = ImageIO.read(new File(folderBase, file));
int w = image.getWidth();
int h = image.getHeight();
totalHeight += h;
if(w > maxWidth)
{
maxWidth = w;
}
image.flush();
}
BufferedImage combined = new BufferedImage((maxWidth), (totalHeight), BufferedImage.TYPE_BYTE_GRAY);
for(String file:allFiles)
{
Graphics g = combined.getGraphics();
image = ImageIO.read(new File(folderBase, file));
int h = image.getHeight();
g.drawImage(image, 0, currentHeight, null);
currentHeight += h;
image.flush();
g.dispose();
}
File folderExists = new File(combinedImageLocation + parentFolder + "\\");
if(!folderExists.exists())
{
folderExists.mkdirs();
}
ImageIO.write(combined, "TIFF", new File(combinedImageLocation, (parentFolder + "\\" + currentFile + "Combined.tif")));
combined.flush();
System.gc();*/
}***
public static ArrayList<String> sortFiles(ArrayList<String> allFiles)
{
ArrayList<String> sortedFiles = new ArrayList<String>();
ArrayList<String> numbers = new ArrayList<String>();
ArrayList<String> letters = new ArrayList<String>();
for(String currentFile:allFiles)
{
try
{
Integer.parseInt(currentFile.substring((currentFile.indexOf('.') + 1)));
numbers.add(currentFile);
}catch(Exception e)
{
letters.add(currentFile);
}
}
//String[] numbersArray = new String[numbers.size()];
//String[] lettersArray = new String[letters.size()];
for(int i = 0; i < numbers.size(); i++)
{
sortedFiles.add(numbers.get(i));
}
for(int i = 0; i < letters.size(); i++)
{
sortedFiles.add(letters.get(i));
}
return sortedFiles;
}
}
Hi i found some code after do some Google and i am using this code to Encrypt the string (witch i set as parameter in web-service)
and it's working fine, it's to hard for me to understand this code so put hole class.
public class RSA {
Vector<Object> vectEnc;
Object enc[];
private long P, Q;
private long N, M, E = 11;
private long D;
public RSA() {
P = 6151;
Q = 8807;
N = P * Q;
M = (P - 1) * (Q - 1);
E = 11;
D = 44310191;
vectEnc = new Vector<Object>();
}
public String doEncryption(String message) {
try {
String str = new BASE64Encoder().encode(message.getBytes("UTF-8"));
String encString = "";
for (int i = 0; i < str.length(); i += 3) {
String tempAsci = "1";
String tempStr;
for (int h = 0; h < 3; h++) {
int total = i + h;
if (total < str.length()) {
tempStr = String.valueOf((int) (str.subSequence(total,
total + 1).charAt(0)) - 30);
if (tempStr.length() < 2) {
tempStr = "0" + tempStr;
}
} else {
break;
}
tempAsci = tempAsci + tempStr;
}
vectEnc.add(tempAsci + "1");
}
enc = vectEnc.toArray();
vectEnc.removeAllElements();
for (int i = 0; i < enc.length; i++) {
long base = Long.parseLong(enc[i].toString());
long powMod = powMod(base, E, N);
encString = encString + String.valueOf(powMod) + " ";
}
return encString;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public String doDecryption(String codeMsg) {
String[] decryptArray = codeMsg.split(" ");
String decryptStr = "";
String originalStr = "";
for (int i = 0; i < decryptArray.length; i++) {
long base = Long.parseLong(decryptArray[i]);
long powMod = powMod(base, D, N);
String powModString = String.valueOf(powMod);
decryptStr = decryptStr
+ powModString.subSequence(1, powModString.length() - 1);
}
for (int i = 0; i < decryptStr.length(); i += 2) {
char ch = (char) (Integer.parseInt(decryptStr.subSequence(i, i + 2)
.toString()) + 30);
originalStr = originalStr + ch;
}
BASE64Decoder decoder = new BASE64Decoder();
byte[] decBytes = null;
try {
decBytes = decoder.decodeBuffer(originalStr);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String decodeStr = new String(decBytes);
return decodeStr;
}
public long powMod(long base, long exp, long modula) {
long accum = 1;
int i = 0;
long base2 = base;
while ((exp >> i) > 0) {
if (((exp >> i) & 1) == 1) {
accum = mo((accum * base2), modula);
}
base2 = mo((base2 * base2), modula);
i++;
}
return accum;
}
public long mo(long g, long l) {
return (long) (g - (l * Math.floor(g / l)));
}
}
But the problem is when the String Length is more the 56 it throw the Exception Like
java.lang.NumberFormatException: For input string: "174-17-201"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at com.info.test.RSA.doEncryption(RSA.java:49)
at com.info.test.Test.main(Test.java:56)
i even no what is the algorithm is use by this code ,i do some Google and i found simple solution is make a part of string and do Encryption it Like this.
int MAX_LAN = 55;
List<String> splitEqually = splitEqually(string,MAX_LAN);
String encodeString = "";
for (int i = 0; i < splitEqually.size(); i++) {
encodeString +=rsa.doEncryption(splitEqually.get(i));
}
System.out.println(encodeString);
public static List<String> splitEqually(String text, int size) {
List<String> ret = new ArrayList<String>((text.length() + size - 1) / size);
for (int start = 0; start < text.length(); start += size) {
ret.add(text.substring(start, Math.min(text.length(), start + size)));
}
return ret;
}
and it working fine , so is it proper method or not ??
I would strongly suggest using Java's built-in cryptographic libraries for this. Follow this series of articles on how to perform RSA encryption/decryption in Java:
http://www.javamex.com/tutorials/cryptography/rsa_encryption.shtml
I apologize for asking such a question, but I am lost and cannot figure out what to do.
I am reading the book Beginning Android Games 2nd Edition. I actually finished reading the book just today. I planned on making my own small 3D Game, just to test my knowledge. Well, my issue is that the ObjLoader that we made for the framework in the book won't show my .obj file. It either just crashes, shows some triangles, or fills have the screen a grayish color. I have tried making these .obj files in AutoDesk Maya 2013, Wings 3D, and Blender. But none of them show my object I designed. Even just a simple cube. Again, I'm sorry for asking such a question, but I would like to know if there is something special I need to do during exporting to get this ObjLoader to load it? I know for a fact that I am doing the loading correct. It works for the .obj provided. Here is the ObjLoader's code(straight from the book). Thanks in advance.
package com.badlogic.androidgames.framework.gl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import com.badlogic.androidgames.framework.impl.GLGame;
public class ObjLoader {
public static Vertices3 load(GLGame game, String file) {
InputStream in = null;
try {
in = game.getFileIO().readAsset(file);
List<String> lines = readLines(in);
float[] vertices = new float[lines.size() * 3];
float[] normals = new float[lines.size() * 3];
float[] uv = new float[lines.size() * 2];
int numVertices = 0;
int numNormals = 0;
int numUV = 0;
int numFaces = 0;
int[] facesVerts = new int[lines.size() * 3];
int[] facesNormals = new int[lines.size() * 3];
int[] facesUV = new int[lines.size() * 3];
int vertexIndex = 0;
int normalIndex = 0;
int uvIndex = 0;
int faceIndex = 0;
for (int i = 0; i < lines.size(); i++) {
String line = lines.get(i);
if (line.startsWith("v ")) {
String[] tokens = line.split("[ ]+");
vertices[vertexIndex] = Float.parseFloat(tokens[1]);
vertices[vertexIndex + 1] = Float.parseFloat(tokens[2]);
vertices[vertexIndex + 2] = Float.parseFloat(tokens[3]);
vertexIndex += 3;
numVertices++;
continue;
}
if (line.startsWith("vn ")) {
String[] tokens = line.split("[ ]+");
normals[normalIndex] = Float.parseFloat(tokens[1]);
normals[normalIndex + 1] = Float.parseFloat(tokens[2]);
normals[normalIndex + 2] = Float.parseFloat(tokens[3]);
normalIndex += 3;
numNormals++;
continue;
}
if (line.startsWith("vt")) {
String[] tokens = line.split("[ ]+");
uv[uvIndex] = Float.parseFloat(tokens[1]);
uv[uvIndex + 1] = Float.parseFloat(tokens[2]);
uvIndex += 2;
numUV++;
continue;
}
if (line.startsWith("f ")) {
String[] tokens = line.split("[ ]+");
String[] parts = tokens[1].split("/");
facesVerts[faceIndex] = getIndex(parts[0], numVertices);
if (parts.length > 2)
facesNormals[faceIndex] = getIndex(parts[2], numNormals);
if (parts.length > 1)
facesUV[faceIndex] = getIndex(parts[1], numUV);
faceIndex++;
parts = tokens[2].split("/");
facesVerts[faceIndex] = getIndex(parts[0], numVertices);
if (parts.length > 2)
facesNormals[faceIndex] = getIndex(parts[2], numNormals);
if (parts.length > 1)
facesUV[faceIndex] = getIndex(parts[1], numUV);
faceIndex++;
parts = tokens[3].split("/");
facesVerts[faceIndex] = getIndex(parts[0], numVertices);
if (parts.length > 2)
facesNormals[faceIndex] = getIndex(parts[2], numNormals);
if (parts.length > 1)
facesUV[faceIndex] = getIndex(parts[1], numUV);
faceIndex++;
numFaces++;
continue;
}
}
float[] verts = new float[(numFaces * 3)
* (3 + (numNormals > 0 ? 3 : 0) + (numUV > 0 ? 2 : 0))];
for (int i = 0, vi = 0; i < numFaces * 3; i++) {
int vertexIdx = facesVerts[i] * 3;
verts[vi++] = vertices[vertexIdx];
verts[vi++] = vertices[vertexIdx + 1];
verts[vi++] = vertices[vertexIdx + 2];
if (numUV > 0) {
int uvIdx = facesUV[i] * 2;
verts[vi++] = uv[uvIdx];
verts[vi++] = 1 - uv[uvIdx + 1];
}
if (numNormals > 0) {
int normalIdx = facesNormals[i] * 3;
verts[vi++] = normals[normalIdx];
verts[vi++] = normals[normalIdx + 1];
verts[vi++] = normals[normalIdx + 2];
}
}
Vertices3 model = new Vertices3(game.getGLGraphics(), numFaces * 3,
0, false, numUV > 0, numNormals > 0);
model.setVertices(verts, 0, verts.length);
return model;
} catch (Exception ex) {
throw new RuntimeException("couldn't load '" + file + "'", ex);
} finally {
if (in != null)
try {
in.close();
} catch (Exception ex) {
}
}
}
static int getIndex(String index, int size) {
int idx = Integer.parseInt(index);
if (idx < 0)
return size + idx;
else
return idx - 1;
}
static List<String> readLines(InputStream in) throws IOException {
List<String> lines = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null)
lines.add(line);
return lines;
}
}
I've got a program that reads an input file with 4000 1's or 0's, one on each line.
The program compiles fine but when it runs I get the following error:
ˇ˛0Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at Project1.main(Project1.java:27)
For some reason when I look at the text file, the first line is a 0 and nothing else yet when the program reads the first line it gets ˇ˛0. I also tried using a buffered reader with no luck. Could anyone please offer some input. Thank you!
Here's my code:
import java.io.*;
import java.util.Random;
import java.util.Scanner;
public class Project1 {
public static void main(String[] args) {
int [] stream = new int[4000];
int [] received = new int[4000];
int corrupt = 0;
float standardDev = 0;
float [] averages = new float[4000];
float averagev = 0;
float voltage = 0;
try {
Scanner st = new Scanner(new File("CS 380 bit feed.txt"));
System.out.print(st.next());
FileWriter outFile = new FileWriter("output");
PrintWriter out = new PrintWriter(outFile);
int i=0;
Random rand = new Random();
stream[i]=st.nextInt();
if (stream[i] == 0)
voltage = (float) (2.49 * rand.nextFloat());
else
voltage = (float) ((2.5 * rand.nextFloat()) + 2.5);
if (voltage < 2.5)
received[i] = 0;
else
received[i] = 1;
averagev = voltage;
averages[i] = voltage;
if (stream[i] != received[i])
corrupt++;
i++;
while (i < 4000) {
stream[i]=st.nextInt();
if (stream[i] == 0)
voltage = (float) 2.49 * rand.nextFloat();
else
voltage = (float) ((2.5 * rand.nextFloat()) + 2.5);
averagev = ((averagev * i) + voltage)/(i+1);
if (voltage <= averagev)
received[i] = 0;
else
received[i] = 1;
if (stream[i] != received[i])
corrupt++;
i++;
}
averagev = 0;
int j = 0;
while (j < 4000) {
for (int k = 0; k<8; k++) {
out.print(received[j]);
averagev = averages[i] + averagev;
j++;
}
out.println(" " + averages[j]);
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
averagev = averagev / 4000;
for (int k = 0; k<4000; k++)
standardDev = ((averagev - averages[k])*(averagev - averages[k])) + standardDev;
standardDev = standardDev/4000;
System.out.println("Errors: " + corrupt);
System.out.println("Percentage Corrupt: " + corrupt / 4000);
System.out.println("Average of Average Voltages: " + averagev);
System.out.println("Standard Deviation: " + standardDev);
}
}
Look at the file in a hex editor. It might be corrupt or have a Byte Order Mark at the beginning, which wouldn't necessarily show up in a text editor.