i want to classify string type dataset with test and training labeled.
i use this code in Eclipse java while i import Weka.jar file already
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import weka.classifiers.functions.SMO;
import weka.filters.unsupervised.attribute.StringToWordVector;
import weka.core.Instances;
public class Classify {
public static void main(String[] args) throws Exception {
//load data set for training//
BufferedReader breader = null;
breader = new BufferedReader(new FileReader("C:/nfrtraining.arff"));
Instances train = new Instances(breader);
train.setClassIndex(train.numAttributes() - 1);
//test data set for testing//
breader = new BufferedReader(new FileReader("C:/nfrtesting1.arff"));
Instances test = new Instances(breader);
test.setClassIndex(test.numAttributes() - 1);
// classifier applied
SMO svm = new SMO();
svm.buildClassifier(train);
System.out.println(svm.getCapabilities().toString());
Instances labeled = new Instances(test);
//for label instances
for (int i = 0; i < test.numInstances(); i++) {
double clsLabel = svm.classifyInstance(test.instance(i));
labeled.instance(i).setClassValue(clsLabel);
}
//save labeled data
BufferedWriter writer = new BufferedWriter(
new FileWriter("c:/labelled.arrf"));
writer.write(labeled.toString());
}
}
when i run this code an error is displayed like:
at weka.core.Capabilities.test(Capabilities.java:1277)
at weka.core.Capabilities.test(Capabilities.java:1208)
at weka.core.Capabilities.testWithFail(Capabilities.java:1506)
at weka.classifiers.functions.SMO.buildClassifier(SMO.java:1330)
at Classify.main(Classify.java:30)
this error is in scr file i am unable to eid. please someone help to resolve this problem
Related
I have extracted features using jaudio from GTZAN dataset.
Trying to add genre class label to arff file using java code. Here is the code.
import java.io.*;
import weka.core.Attribute;
import weka.core.FastVector;
import weka.core.Instances;
import weka.core.converters.ArffSaver;
public class AddAttribute
{
public static void main(String[] args) throws Exception
{
if (args.length != 2) {
System.out.println("\nUsage: java AddAttribute <file.arff> <genre>\n");
System.exit(1);
}
String filename = args[0];
String genre = args[1];
// load dataset
Instances data = new Instances(new BufferedReader(new FileReader(filename)));
Instances newData = new Instances(data);
// add new attribute
FastVector values = new FastVector();
values.addElement("jazz");
values.addElement("pop");
values.addElement("metal");
values.addElement("classical");
Attribute genreAttr = new Attribute("Genre", values);
newData.insertAttributeAt(genreAttr, newData.numAttributes());
// add to each instance
for (int i = 0; i < newData.numInstances(); i++) {
newData.instance(i).setValue(newData.numAttributes() - 1, genre);
}
// save back to the original arff file
ArffSaver saver = new ArffSaver();
saver.setInstances(newData);
saver.setFile(new File(filename));
saver.writeBatch();
}
}
it gives the following error.
Cannot create new output file. Standard out is used.
I am testing a rest API and I want to build a simple java program to do the following (I am new to java). I export in a file multiple JSON responses from JMeter and then I want them to be checked for all the mandatory response parameters. I want the program to read the paramters from a CSV file and to check for each of them everywhere in the JSONs (they are more than 600). Currently I am using this snippet but it just compares what are the differences between the two files:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Test {
public Test(){
System.out.println("Test.Test()");
}
public static void main(String[] args) throws Exception {
BufferedReader br1 = null;
BufferedReader br2 = null;
String sCurrentLine;
List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();
br1 = new BufferedReader(new FileReader("C:\\Users\\text1.txt"));
br2 = new BufferedReader(new FileReader("C:\\Users\\text2.txt"));
while ((sCurrentLine = br1.readLine()) != null) {
list1.add(sCurrentLine);
}
while ((sCurrentLine = br2.readLine()) != null) {
list2.add(sCurrentLine);
}
List<String> tmpList = new ArrayList<String>(list1);
tmpList.removeAll(list2);
System.out.println("content from SavedResponses.txt which is not there in DBResponses.txt");
for(int i=0;i<tmpList.size();i++){
System.out.println(tmpList.get(i)); //content from test.txt which is not there in test2.txt
}
System.out.println("content from DBResponses.txt which is not there in SavedResponses.txt");
tmpList = list2;
tmpList.removeAll(list1);
for(int i=0;i<tmpList.size();i++){
System.out.println(tmpList.get(i)); //content from test2.txt which is not there in test.txt
}
}
}
Any help is highly appreciated!
I want to add some code to the C source code, so I try to use ASTRewrite.
My Github project: cdt-rewrite
My code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import org.eclipse.cdt.core.dom.ast.ASTVisitor;
import org.eclipse.cdt.core.dom.ast.IASTIfStatement;
import org.eclipse.cdt.core.dom.ast.IASTStatement;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.core.dom.ast.gnu.c.GCCLanguage;
import org.eclipse.cdt.core.dom.rewrite.ASTRewrite;
import org.eclipse.cdt.core.model.ILanguage;
import org.eclipse.cdt.core.parser.DefaultLogService;
import org.eclipse.cdt.core.parser.FileContent;
import org.eclipse.cdt.core.parser.IncludeFileContentProvider;
import org.eclipse.cdt.core.parser.ScannerInfo;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.ltk.core.refactoring.Change;
public class Main {
public static void main(String[] args) throws Exception {
IASTTranslationUnit u = getTranslationUnit(new File("D:/test.c"));
System.out.println(u.getRawSignature());
ASTRewrite rw = ASTRewrite.create(u);
u.accept(new ASTVisitor(true) {
#Override
public int visit(IASTStatement stm) {
if (stm instanceof IASTIfStatement){
rw.insertBefore(stm.getParent(), stm,
rw.createLiteralNode("callTo(1,2,3);"), null);
}
return PROCESS_CONTINUE;
}
});
Change c = rw.rewriteAST();
c.perform(new NullProgressMonitor());
//String changedSource = someHowGetCode(c);
}
static IASTTranslationUnit getTranslationUnit(File source) throws Exception{
FileContent reader = FileContent.create(
source.getAbsolutePath(),
getContentFile(source).toCharArray());
return GCCLanguage.getDefault().getASTTranslationUnit(
reader,
new ScannerInfo(),
IncludeFileContentProvider.getSavedFilesProvider(),
null,
ILanguage.OPTION_IS_SOURCE_UNIT,
new DefaultLogService());
}
static String getContentFile(File file) throws IOException {
StringBuilder content = new StringBuilder();
String line;
try (BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(file)))) {
while ((line = br.readLine()) != null)
content.append(line).append('\n');
}
return content.toString();
}
}
But when I run this code, an exception is occur:
int test(int x){
if (x < 0)
return 0;
int i, s = 0;
for (i = 1; i < x; i++)
s = s + i;
return s;
}
Exception in thread "main" java.lang.NullPointerException
at org.eclipse.cdt.internal.formatter.ChangeFormatter.formatChangedCode(ChangeFormatter.java:92)
at org.eclipse.cdt.internal.core.dom.rewrite.changegenerator.ChangeGenerator.generateChange(ChangeGenerator.java:117)
at org.eclipse.cdt.internal.core.dom.rewrite.changegenerator.ChangeGenerator.generateChange(ChangeGenerator.java:104)
at org.eclipse.cdt.internal.core.dom.rewrite.ASTRewriteAnalyzer.rewriteAST(ASTRewriteAnalyzer.java:26)
at org.eclipse.cdt.core.dom.rewrite.ASTRewrite.rewriteAST(ASTRewrite.java:212)
at Main.main(Main.java:44)
Does anyone know how to solve this exception?
Thanks you
AFAIK This code is dependent on running in OSGi, but you appear to have made a Java project with a main. You need to a plug-in project with a MANIFEST.MF that references what you require.
You can create an Eclipse Application if you want to control the entry point to the program. If you want to graduate this rewriting code to be part of Eclipse/CDT, then different entry points such as an Eclipse Command tied to a menu/toolbar/key combination may be what you want.
So I have a few other classes like this one, I call the method in using an object in the run file. I want to write every output of every class into the same text file. However at the moment only one output is being saved to the text file, as it is overwriting each time, how do I do this using a print writer seen below?
Any guidance is much appreciated!
Class:
package cw;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JFileChooser;
import java.io.IOException;
public class LineCounter {
public static void TotalLines() throws IOException {
Scanner sc = new Scanner(TextAnalyser.class.getResourceAsStream("test.txt"));
PrintWriter out = new PrintWriter(new FileWriter("C:\\Users\\Sam\\Desktop\\Report.txt"));
int linetotal = 0;
while (sc.hasNextLine()) {
sc.nextLine();
linetotal++;
}
out.println("The total number of lines in the file = " + linetotal);
out.close();
System.out.println("The total number of lines in the file = " + linetotal);
}
}
Run File:
package cw;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JFileChooser;
import java.io.IOException;
public class TextAnalyser {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(TextAnalyser.class.getResourceAsStream("test.txt"));
LineCounter Lineobject = new LineCounter();
WordCounter Wordobject = new WordCounter();
NumberCounter Numberobject = new NumberCounter();
DigitCounter Digitobject = new DigitCounter();
SpaceCounter Spaceobject = new SpaceCounter();
NumberAverage Noavgobject = new NumberAverage();
WordAverage Wordavgobject = new WordAverage();
Palindromes Palindromeobject = new Palindromes();
VowelCounter Vowelobject = new VowelCounter();
ConsonantCounter Consonantobject = new ConsonantCounter();
WordOccurenceTotal RepeatsObject = new WordOccurenceTotal();
Lineobject.TotalLines();
Wordobject.TotalWords();
Numberobject.TotalNumbers();
Digitobject.TotalDigits();
Spaceobject.TotalSpaces();
Noavgobject.NumberAverage();
Wordavgobject.WordAverage();
Vowelobject.TotalVowels();
Consonantobject.TotalConsonant();
Palindromeobject.TotalPalindromes();
//RepeatsObject.TotalRepeats();
}
}
You want to use the second argument of the FileWriter constructor to set the append mode:
new FileWriter("name_of_your_file.txt", true);
instead of:
new FileWriter("name_of_your_file.txt");
I am getting arrayoutofbond error while running below given code,
sometime it is running as expected and sometime it is giving error.
Could anyone help me where I am wrong.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class getFileContent{
public void listFiles() throws IOException, InterruptedException{
File directory = new File("C:\\ScriptLogFile\\");
File[] myarray;
myarray=directory.listFiles();
int i=0;
ArrayList<String> arrayList = new ArrayList<String>();
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy_hhmmss");
Date curDate = new Date();
String strDate = sdf.format(curDate);
String fileName = strDate;
File file = new File("C:\\ExcelReport_"+fileName+".csv");
FileWriter fileWritter = new FileWriter(file, true);
BufferedWriter bwr = new BufferedWriter(fileWritter);
String filename = null;
try {
for (int j = 0; j < myarray.length; j++)
{
File path=myarray[j];
FileInputStream fis = new FileInputStream (path);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
if(path.isFile()){
if(path.getName().endsWith(".csv")){
filename = path.getName();
String line;
bwr.write(filename+",");
while ((line = br.readLine()) != null) {
if(line.contains("-")){
String[] part = line.split("-");
arrayList.add(part[1]);
bwr.write(arrayList.get(i)+",");
i++;
}
else{
}
}
bwr.write("\r\n");
}
}
}
}catch (FileNotFoundException e) {
e.printStackTrace();
}
bwr.close();
}
public static void main(String[] args) throws IOException, InterruptedException {
getFileContent gfc = new getFileContent();
gfc.listFiles();
}
}
We need a stack trace to see where the exception is raised. However you seem to be making assumptions about the length of part[]. Remember arrays are 0-indexed, the first entry would be at index 0 i.e. part[0]. Even then, in general there really needn't be many entries at all: "xyz".split("-") is an array of length 1 whose only element, "xyz", is at index 0.