Add items to hashmap in for loop - csv

I'm trying to put items from a csv file in an hashmap. By adding items I mean categorizing them. The csv is filled with the answers from a question list. So the csv is build up like this:
Person Question
- Do you wear glasses
1 Yes
2 Yes
3 No
4 Sometimes
The next step I would like to do is reading the items and put the answer in the hashmap with the key being the name of the answer and the value with the amount of that certain answer.
The hashmap should look like this with the previous example I gave:
Yes, 2
No, 1
Sometimes, 1
I'm looping right now like this:
for (int j = 0; j < dataPersonList.size(); j++)
{
// looping through the csv
while (t.hasNext ())
{
// looping through the hashmap
Map.Entry me = (Map.Entry)t.next();
if (dataPersonVar.glasses.equals(me.getKey()))
{
// if the item in the csv is the same as the item in the hashmap
hm.put(me.getKey(), me.getValue() =+ 1); // the value gets +1
}
else
{
// a new item is made and gets automatically 1
hm.put(dataPersonVar.glasses,1);
}
}
}
But obviously this doesn't work. I'm a starter with hashmaps but really think the hashmap is the solution for my problem. I'm working in Processing. Does anybody have an idea how to solve this? If I'm not clear enough let me know!
Thanks in advance
Edit:
As requested I hereby post the full code:
import java.util.Iterator;
import java.util.Map;
HashMap hm = new HashMap();
import de.bezier.data.*;
int totalParticipants;
int bgWidth = 1000;
int bgHeight = 1000;
int x;
int eSize = 10;
int opacity = 100;
float xLocation;
float yLocation;
String travelType;
int travelTime;
int border=400;
float dataMinLat=1000;
float dataMaxLat;
float dataMinLon=1000;
float dataMaxLon;
float xLocationMM = (5.17880);
float yLocationMM = (52.22541);
ArrayList dataPersonList = new ArrayList();
ArrayList dataFunctionList = new ArrayList(100);
Point[] pointList = new Point[1000];
float angle;
XlsReader reader;
PImage kaart;
void setup ()
{
textSize(10);
size(bgWidth, bgHeight);
background(0);
noStroke();
smooth();
//kaart = loadImage("map.png");
yLocationMM = 0 - yLocationMM;
reader = new XlsReader( this, "MMdata.xls" ); // assumes file to be in the data folder
totalParticipants = reader.getLastRowNum();
for (int i = 1;i < totalParticipants+1; i++) {
DataPerson dataPerson = new DataPerson();
dataPerson.function = reader.getString(i, 23);
dataPerson.firstName = reader.getString(i, 1);
dataPerson.lastName = reader.getString(i, 2);
dataPerson.glasses = reader.getString(i, 20);
dataPerson.longitude = reader.getFloat(i, 55);
dataPerson.latitude = reader.getFloat(i, 54);
dataPerson.location = reader.getString(i, 8);
dataPerson.ownage = reader.getString(i, 14);
dataPerson.traveltime = reader.getInt(i, 31);
dataPerson.establishment = reader.getString(i, 58);
dataPerson.traveltype = reader.getString(i, 17);
dataPersonList.add(dataPerson);
}
for (int i = 0; i < dataPersonList.size(); i++) {
DataPerson person = (DataPerson) dataPersonList.get(i);
for (int j = 0; j < dataFunctionList.size() + 1; j++) {
DataFunction dataFunction = null;
if (j < dataFunctionList.size())
{
dataFunction = (DataFunction) dataFunctionList.get(j);
}
if (dataFunction != null) {
if (person.function.equals(dataFunction.function)) {
dataFunction.persons.add(person);
dataFunction.amount ++;
break;
}
}
else {
dataFunction = new DataFunction();
dataFunction.function = person.function;
dataFunction.amount = 1;
dataFunction.persons.add(person);
dataFunctionList.add(dataFunction);
break;
}
}
}
for (int i = 0; i < dataPersonList.size(); i++) {
DataPerson dataPersonVar = (DataPerson) dataPersonList.get(i);
if (dataPersonVar.longitude > dataMaxLon) {
dataMaxLon = dataPersonVar.longitude;
}
else if (dataPersonVar.longitude < dataMinLon) {
dataMinLon = dataPersonVar.longitude;
}
if (dataPersonVar.latitude > dataMaxLat) {
dataMaxLat = dataPersonVar.latitude;
}
else if (dataPersonVar.latitude < dataMinLat) {
dataMinLat = dataPersonVar.latitude;
}
}
}
class DataPerson
{
String function;
String firstName;
String lastName;
String glasses;
float longitude;
float latitude;
String location;
String ownage;
int traveltime;
String establishment;
String traveltype;
String fullName()
{
return firstName + " " + lastName;
}
}
class DataFunction
{
String function;
int amount;
ArrayList persons = new ArrayList();
String getPersonNames()
{
String output = "";
for (int i = 0; i < persons.size(); i++) {
DataPerson person = (DataPerson) persons.get(i);
output += person.firstName + "(" + person.glasses + ") ";
}
return output;
}
}
class Point
{
float x;
float y;
}
void draw()
{
background(0);
strokeWeight(2);
x=50;
int xText=80;
int procentGlasses;
noStroke();
pushMatrix();
scale(1.40, 0.89);
//image(kaart, -250, -360);
popMatrix();
for (int i = 0; i < dataPersonList.size(); i++) {
DataPerson dataPersonVar = (DataPerson) dataPersonList.get(i);
if (dataPersonVar != null) {
xLocation = map(dataPersonVar.longitude, dataMinLon, dataMaxLon, border, bgWidth-border);
yLocation = map(dataPersonVar.latitude, dataMinLat, dataMinLat+(dataMaxLon-dataMinLon), border, bgHeight-border);
travelType = (dataPersonVar.traveltype);
noFill();
if (travelType.equals("By car")) {
stroke(0, 0, 255, opacity+100);
}
else if (travelType.equals("By public transport")) {
stroke(255, 0, 0, opacity);
}
else {
stroke(255, opacity);
}
//text(dataPersonVar.firstName, xLocation, yLocation);
noStroke();
strokeWeight(4);
stroke(100, 15);
strokeWeight(2);
}
}
for (int i = 0; i < dataPersonList.size(); i++) {
DataPerson dataPersonVar = (DataPerson) dataPersonList.get(i);
if (dataPersonVar != null) {
xLocation = map(dataPersonVar.longitude, dataMinLon, dataMaxLon, border, bgWidth-200);
yLocation = map(dataPersonVar.latitude, dataMinLat, dataMinLat+(dataMaxLon-dataMinLon), border, bgHeight-200);
noStroke();
fill(255, 200);
ellipse(xLocation, yLocation, eSize, eSize);
//println(dataPersonVar.glasses);
Iterator t = hm.entrySet().iterator(); // Get an iterator
for (int j = 0; j < dataPersonList.size(); j++) {
while (t.hasNext ()) {
Map.Entry me = (Map.Entry)t.next();
println("die in de dataPersonshit is "+dataPersonVar.glasses+". En de andere waarde is "+me.getKey());
if (dataPersonVar.glasses.equals(me.getKey())) {
hm.put(me.getKey(), ((Integer)me.getValue()) + 1);
}
else {
hm.put(dataPersonVar.glasses, 1);
//println("YEAH");
}
}
}
/////////drawing the circle///////////////
angle = ((PI*2)/15*1)/dataPersonList.size()*i;
stroke(255, 100, 50, 50);
noFill();
strokeWeight(3);
pointList[i] = new Point();
pointList[i].x = bgWidth/2+sin(angle)*400; // de punt van x = 400 ( het middelpunt van de cirkel ) + sin((360 graden) / het totaal
pointList[i].y = bgHeight/2+cos(angle)*400;
beginShape();
vertex(xLocation, yLocation);
quadraticVertex((xLocation+pointList[i].x)/2, yLocation, pointList[i].x, pointList[i].y);
endShape();
}
}
}
Unfortunately I can't give you the csv but I hope the code at least helps.

You don't really need to iterate over the map to do what you seem to be trying to do. Here is an example with a similar csv as you have described:
import java.util.Map;
Map<String, Integer> answers = new HashMap<String,Integer>();
//String [] fileInput = loadStrings("question.csv");
String [] fileInput = new String [] {
"1,Yes", "2,No", "3,Yes", "4,Sometimes", "5,Yes", "6,No", "7,No", "8,No"
};
for (int i = 0 ; i < fileInput.length; i++) {
String [] line = split(fileInput[i],",");
String newAnswer = line[1];
if(!answers.containsKey(newAnswer)) answers.put(newAnswer,1);
else answers.put(newAnswer,answers.get(newAnswer)+1);
}
println(answers);

Related

I have a problem with a mouseclicked funktion in proccessing

In my main class i have made an array to spawn a few green circles. I tried to get the background to change when i clicked on one of them with a boolean which is supposed to come true when clicking while over the circle... I am new to programming as a whole and I am not really sure how to solve this problem.. I dont really know where the data of the x and y positions of the green circles are displayed and how the klicked function is supposed to find them because all of them are created at random positions and in an other class. So here is my code so far:
class Gesicht {
//Eigenschaften
boolean fail = false;
float whEllipse= 200;
float yPos = random(-whEllipse, height);
float xPos = random(-whEllipse, height);
float xSpeed = 1;
float P = 1;
//Constructor
Gesicht() {
// this.yPos = yPos;
// this.xPos = xPos;
}
//Methoden/Funktionen
void move() {
//paint();
xPos += xSpeed;
yPos += (P*sin(radians(xPos))+1); //+1 macht dass sich das Gesicht langsam runter bewegt.
if (xPos>= width+whEllipse/2) {
// P = P+1; Maybe falls ich größere Amplitude will
xPos = -whEllipse/2;
}
if (yPos >= height+whEllipse/2) {
yPos = random(-whEllipse, height/2);
xPos = random(-200, whEllipse/2);
}
}
boolean klicked() {
if (mouseX > xPos-whEllipse/2 && mouseX < xPos+whEllipse/2
&& mouseY > yPos-whEllipse/2 && mouseY < yPos+whEllipse/2
&& mousePressed) {
return true;
}
return false;
}
void klick() {
if (klicked()) {
fail = true;
}
}
void spawn() {
move();
fill(0, 255, 0);
circle(xPos, yPos, whEllipse);
}
}
this is the class where i tried to put my funktions.
int farbe = 255;
Gesicht[] grün;
Gesichter[] rot;
Gesichterer[] blau;
void settings() {
size(700, 700);
}
void setup() {
rot = new Gesichter[10];
for ( int i = 0; i< rot.length; i++) {
rot[i]= new Gesichter();
}
grün = new Gesicht[15];
for ( int i = 0; i< grün.length; i++) {
grün[i]= new Gesicht();
}
blau = new Gesichterer[20];
for ( int i = 0; i< blau.length; i++) {
blau[i]= new Gesichterer();
}
}
void draw() {
background(farbe);
if(variable.klicked()){
background(150,0,0);
}
for ( int i = 0; i< grün.length; i++) {
grün[i].spawn();
}
for ( int i = 0; i< rot.length; i++) {
rot[i].spawn();
}
for (int i = 0; i< blau.length; i++) {
blau[i].spawn();
}
}
And this is my main class.
The funktion never gets true in the moment... I hope someone can help me ://
Would be very grateful.
You might be trying a bit hard without cleaning up your code which on long run leads to more headaches.
I say based on the following:
you have a klicked() but also a klick() method which doesn't do much: klick() should suffice
You only define a Gesicht class, however you additioanlly attempt to instantiate Gesichter and Gesichterer which don't exist (at least not in the code you posted)
if(variable.klicked()){ background(150,0,0); } refers to an unusuable variable called variable (a placeholder perhaps?). Even if that variable existed, the red background would've only briefly flashed while klicked() was true.
You're very close though:
the klicked() method does what you want
farbe already stores the background colour
You could do something like this:
class Gesicht {
//Eigenschaften
boolean fail = false;
float whEllipse= 200;
float yPos = random(-whEllipse, height);
float xPos = random(-whEllipse, height);
float xSpeed = 1;
float P = 1;
//Constructor
Gesicht() {
// this.yPos = yPos;
// this.xPos = xPos;
}
//Methoden/Funktionen
void move() {
//paint();
xPos += xSpeed;
yPos += (P*sin(radians(xPos))+1); //+1 macht dass sich das Gesicht langsam runter bewegt.
if (xPos>= width+whEllipse/2) {
// P = P+1; Maybe falls ich größere Amplitude will
xPos = -whEllipse/2;
}
if (yPos >= height+whEllipse/2) {
yPos = random(-whEllipse, height/2);
xPos = random(-200, whEllipse/2);
}
}
boolean klicked() {
if (mouseX > xPos-whEllipse/2 && mouseX < xPos+whEllipse/2
&& mouseY > yPos-whEllipse/2 && mouseY < yPos+whEllipse/2
&& mousePressed) {
return true;
}
return false;
}
void klick() {
if (klicked()) {
fail = true;
}
}
void spawn() {
move();
fill(0, 255, 0);
circle(xPos, yPos, whEllipse);
}
}
int farbe = 255;
Gesicht[] green;
Gesicht[] rot;
Gesicht[] blau;
void settings() {
size(700, 700);
}
void setup() {
//rot = new Gesicht[10];
//for ( int i = 0; i< rot.length; i++) {
// rot[i]= new Gesicht();
//}
//green = new Gesicht[15];
//for ( int i = 0; i< green.length; i++) {
// green[i]= new Gesicht();
//}
blau = new Gesicht[20];
for ( int i = 0; i< blau.length; i++) {
blau[i]= new Gesicht();
}
}
void draw() {
background(farbe);
//if (variable.klicked()) {
// background(150, 0, 0);
//}
//for ( int i = 0; i< green.length; i++) {
// if(green[i].klicked()){
// farbe = color(red(farbe), random(255), blue(farbe));
// }
// green[i].spawn();
//}
//for ( int i = 0; i< rot.length; i++) {
// rot[i].spawn();
//}
for (int i = 0; i< blau.length; i++) {
if(blau[i].klicked()){
farbe = color(red(farbe), green(farbe), random(255));
}
blau[i].spawn();
}
}
(Only one array of circles is uncommented for simplicity/easy testing. Feel free to adjust as needed)
One final touch you could add, if you want the background to only change once when you click (as opposed to continously while the mouse is pressed), is debouncing. The idea is to use a state/variable to keep track if the button was previously pressed or not to only chance the background once until the states change again. (You could implement this using an extra boolean variable in your class or perhaps simpler, use the mouseClicked() callback to iterate over your array simply to check which instance has been klicked() to change the background accordingly).

Processing program works until I add it to a webpage

I have this .pde program that works perfectly on the Processing software, but when I add it to a webpage it just doesn't load. If I replace the code with any other .pde program it works fine, so inserting .pde programs in an html file is not the issue. I'm not sure if the problem is that it's not loading the external image and file or what. But here's the full code, thank you in advance!
(I also tried converting it to p5.js but it's just way too complicated and I'm not familiar with it!)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>TITOLO</title>
<script src="processing.js" type="text/javascript"></script>
<link rel="stylesheet" href="css/style1.css">
</head>
<body>
<h1>Titolo – HOME</h1>
<div id="programma">
<script src="https://cdnjs.cloudflare.com/ajax/libs/processing.js/1.6.6/processing.min.js"></script>
<canvas id="pjs"></canvas></div>
<script type="application/processing" data-processing-target="pjs">
final int STAGE_WIDTH = 1200;
final int STAGE_HEIGHT = 950;
final int NB_PARTICLES = 60000;
final float MAX_PARTICLE_SPEED = 5;
final int MIN_LIFE_TIME = 20;
final int MAX_LIFE_TIME = 80;
final String IMAGE_PATH = "starrynight.jpg";
myVector tabParticles[];
float particleSize = 1.2;
PImage myImage;
int imageW;
int imageH;
color myPixels[];
FlowField ff;
GUI gui;
void setup()
{
size(1200, 950, P3D);
background(0);
initializeImage();
initializeParticles();
ff = new FlowField(5);
gui = new GUI(this);
gui.setup();
}
void initializeImage()
{
myImage = loadImage(IMAGE_PATH);
imageW = myImage.width;
imageH = myImage.height;
myPixels = new color[imageW * imageH];
myImage.loadPixels();
myPixels = myImage.pixels;
image(myImage, 0, 0);
}
void setParticle(int i) {
tabParticles[i] = new myVector((int)random(imageW), (int)random(imageH));
tabParticles[i].prevX = tabParticles[i].x;
tabParticles[i].prevY = tabParticles[i].y;
tabParticles[i].count = (int)random(MIN_LIFE_TIME, MAX_LIFE_TIME);
tabParticles[i].myColor = myPixels[(int)(tabParticles[i].y)*imageW + (int)(tabParticles[i].x)];
}
void initializeParticles()
{
tabParticles = new myVector[NB_PARTICLES];
for (int i = 0; i < NB_PARTICLES; i++)
{
setParticle(i);
}
}
void draw()
{
ff.setRadius(gui.getR());
ff.setForce(gui.getF());
particleSize = gui.getS();
float vx;
float vy;
PVector v;
for (int i = 0; i < NB_PARTICLES; i++)
{
tabParticles[i].prevX = tabParticles[i].x;
tabParticles[i].prevY = tabParticles[i].y;
v = ff.lookup(tabParticles[i].x, tabParticles[i].y);
vx = v.x;
vy = v.y;
vx = constrain(vx, -MAX_PARTICLE_SPEED, MAX_PARTICLE_SPEED);
vy = constrain(vy, -MAX_PARTICLE_SPEED, MAX_PARTICLE_SPEED);
tabParticles[i].x += vx;
tabParticles[i].y += vy;
tabParticles[i].count--;
if ((tabParticles[i].x < 0) || (tabParticles[i].x > imageW-1) ||
(tabParticles[i].y < 0) || (tabParticles[i].y > imageH-1) ||
tabParticles[i].count < 0) {
setParticle(i);
}
strokeWeight(1.5*particleSize);
stroke(tabParticles[i].myColor, 250);
line(tabParticles[i].prevX, tabParticles[i].prevY, tabParticles[i].x, tabParticles[i].y);
}
ff.updateField();
}
void mouseDragged() {
if(mouseX>950 && mouseY>830) return;
ff.onMouseDrag();
}
void keyPressed() {
//if (key =='s' || key == 'S') {
// ff.saveField();
//}
}
class myVector extends PVector
{
myVector (float p_x, float p_y) {
super(p_x, p_y);
}
float prevX;
float prevY;
int count;
color myColor;
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
class FlowField {
PVector[][] field;
PVector[][] tempField;
int cols, rows;
int resolution;
int affectRadius;
float force;
File file = new File(dataPath("field.txt"));
FlowField(int r) {
resolution = r;
cols = 1200 / resolution;
rows = 950 / resolution;
field = new PVector[cols][rows];
tempField = new PVector[cols][rows];
init();
affectRadius = 3;
force = 1;
}
void setRadius(int r) {
affectRadius = r;
}
void setForce(float f) {
force = f;
}
void init() {
try {
for (int i=0; i<cols; i++) {
for (int j=0; j<rows; j++) {
tempField[i][j] = new PVector(0, 0);
}
}
readField();
}
catch(Exception e) {
for (int i=0; i<cols; i++) {
for (int j=0; j<rows; j++) {
field[i][j] = new PVector(0, 0);
}
}
}
}
PVector lookup(float x, float y) {
int column = int(constrain(x/resolution, 0, cols-1));
int row = int(constrain(y/resolution, 0, rows-1));
return PVector.add(field[column][row],tempField[column][row]);
}
void drawBrush() {
pushStyle();
noFill();
stroke(255, 255, 255);
ellipse(mouseX, mouseY, affectRadius*10, affectRadius*10);
popStyle();
}
void drawField(float x, float y, PVector v) {
int column = int(constrain(x/resolution, 0, cols-1));
int row = int(constrain(y/resolution, 0, rows-1));
for (int i=-affectRadius; i<=affectRadius; i++) {
for (int j=-affectRadius; j<=affectRadius; j++) {
if (i*i+j*j<affectRadius*affectRadius) {
try {
tempField[column+i][row+j].add(v).mult(0.9);
}
catch(Exception e) {
}
}
}
}
}
void updateField(){
for (int i=0; i<cols; i++) {
for (int j=0; j<rows; j++) {
tempField[i][j].mult(0.992);
}
}
}
void onMouseDrag() {
PVector direc = new PVector(mouseX-pmouseX, mouseY-pmouseY).normalize();
drawField(pmouseX, pmouseY, direc.mult(force));
}
void saveField() {
try {
FileWriter out = new FileWriter(file);
for (int i=0; i<cols; i++) {
for (int j=0; j<rows; j++) {
out.write(field[i][j].x+","+field[i][j].y+"\t");
}
out.write("\r\n");
}
out.close();
}
catch(Exception e) {
}
}
void readField() throws IOException {
try {
BufferedReader in = new BufferedReader(new FileReader(file));
String line;
for (int i = 0; (line = in.readLine()) != null; i++) {
String[] temp = line.split("\t");
for (int j=0; j<temp.length; j++) {
String[] xy = temp[j].split(",");
float x = Float.parseFloat(xy[0]);
float y = Float.parseFloat(xy[1]);
field[i][j] = new PVector(x, y);
}
}
in.close();
}
catch(Exception e) {
throw new IOException("no field.txt");
}
}
}
import controlP5.*;
class GUI {
ControlP5 cp5;
Slider sliderR;
Slider sliderF;
Slider sliderS;
GUI(PApplet thePApplet){
cp5 = new ControlP5(thePApplet);
}
void setup(){
cp5.setColorBackground(0x141414);
sliderR = cp5.addSlider("Radius")
.setPosition(980,890)
.setRange(1,20)
.setValue(12).setSize(150,25);
sliderF = cp5.addSlider("Force")
.setPosition(980,918)
.setRange(0.1,0.5)
.setValue(0.3).setSize(150,25);
sliderS = cp5.addSlider("Particle Size")
.setPosition(980,862)
.setRange(0.8,2)
.setValue(1.5).setSize(150,25);
}
int getR(){
return int(sliderR.getValue());
}
float getF(){
return sliderF.getValue();
}
float getS(){
return sliderS.getValue();
}
}
</script>
</body>

Write a JSON file with cubePosition Data to spawn a 10x10x10 cube

Here I'm trying to write a code that can write and create a JSON File for me with the data I provide like row, column and depth.
For example, I need to spawn a 10 x 10 x 10 cube. And I give this data in unity Inspector also in the code when I'm serializing it.
I tried achieving this in a for loop and writing the JSON file. But I'm not getting the output I wanted. I am expecting output where the cube locations are different and in place what happens instead is all the data or cube position in my data is the one before the number I give. that is if I gave my row, column, and depth to be 10. So my data is like x: 9, y: 9, z:9 for the whole 1000 elements.Better explained in image down below.I know I'm doing a mistake at some point just not able to figure out where. Thanks for the help in Advance
public class JSONWriter : MonoBehaviour
{
[SerializeField] int rows , columns, depth = 10;
[SerializeField] float padding;
public enum CubeType
{
white,
yellow,
blue,
red,
green
}
private readonly IReadOnlyDictionary<CubeType, Color> colors = new Dictionary<CubeType, Color>
{
{CubeType.white, Color.white},
{CubeType.yellow, Color.yellow},
{CubeType.blue, Color.blue},
{CubeType.red, Color.red},
{CubeType.green, Color.green}
};
[System.Serializable]
public class CubeData
{
public Vector3 cubePosition;
public CubeType Cube;
}
[System.Serializable]
public class CubeDataList
{
public CubeData[] cubeDatas;
}
public void outputJSON()
{
string strOutput = JsonUtility.ToJson(myCubeDataList);
File.WriteAllText(Application.dataPath + "/Resources/10x10x10.txt", strOutput);
}
//CubeData myCubeData = new CubeData();
public CubeDataList myCubeDataList = new CubeDataList();
void Start()
{
for (int x = 0; x < myCubeDataList.cubeDatas.Length; x++)
{
//Debug.Log(myCubeDataList.cubeDatas.Length);
for (int i = 0; i < depth; i++)
{
for (int j = 0; j < columns; j++)
{
for (int k = 0; k < rows; k++)
{
myCubeDataList.cubeDatas[x].cubePosition = new Vector3(i, j, k) * padding;
//myCubeDataList.cubeDatas[x].Cube = Random.Range(CubeType, 3f);
}
}
}
}
}
}
You do not want to go through all i, j, k for each and every element x!
What you are doing is basically overwriting each and every element with the values for i=9, j=9, k=9.
Instead of an array I would rather simply use a dynamic List like
[Serializable]
public class CubeDataList
{
public List<CubeData> cubeDatas;
}
and then dynamically add them via
myCubeDataList.cubeDatas = new List<CubeData>(i * j * k);
for (int i = 0; i < depth; i++)
{
for (int j = 0; j < columns; j++)
{
for (int k = 0; k < rows; k++)
{
var data = new CubeData();
data.cubePosition = new Vector3(i, j, k) * padding;
data.Cube = Random.Range(CubeType, 3f);
myCubeDataList.cubeDatas.Add(data);
}
}
}
Or if you really want to go with an array
for (int i = 0; i < depth; i++)
{
for (int j = 0; j < columns; j++)
{
for (int k = 0; k < rows; k++)
{
var data = new CubeData();
myCubeDataList.cubeDatas[x].cubePosition = new Vector3(i, j, k) * padding;
myCubeDataList.cubeDatas[x].Cube = Random.Range(CubeType, 3f);
x++;
}
}
}
Though, from your previous question I know you actually do not want to fill the cube completely!
You actually only want the external shape (like a wall) and leave the cube empty on the inside.
So what you actually want would probably rather be
myCubeDataList.cubeDatas = new List<CubeData>(i * j * k);
for (int i = 0; i < depth; i++)
{
for (int j = 0; j < columns; j++)
{
for (int k = 0; k < rows; k++)
{
if(i == 0 || i == depth - 1
|| j == 0 || j == depth - 1
|| k == 0 || k == depth - 1)
{
var data = new CubeData();
data.cubePosition = new Vector3(i, j, k) * padding;
// TODO random enum (see below)
myCubeDataList.cubeDatas.Add(data);
}
}
}
}
For the random enum vlaue see e.g. this answer and do
private Random random = new Random();
and then where it says // TODO insert
var values = Enum.GetValues(typeof(Bar));
data.Cube = (CubeType)values.GetValue(random.Next(values.Length));

No NVENC capable devices found

I met a weird question.I have been using FFmpeg's NVENC to encode video .It is strange that I can use h264_nvenc smoothly without problem,but when I replace h264_nvenc with hevc_nvenc,I got the problem "No NVENC capable devices found".The FFmpeg version I am using is 3.2,and I use command line to encode with hevc_nvenc,it works ok.My code is here:
#include "stdafx.h"
int flush_encoder(AVFormatContext *fmt_ctx, unsigned int stream_index)
{
int ret;
int got_frame;
AVPacket enc_pkt;
if (!(fmt_ctx->streams[stream_index]->codec->codec->capabilities &
CODEC_CAP_DELAY))
return 0;
while (1) {
printf("Flushing stream #%u encoder\n", stream_index);
//ret = encode_write_frame(NULL, stream_index, &got_frame);
enc_pkt.data = NULL;
enc_pkt.size = 0;
av_init_packet(&enc_pkt);
ret = avcodec_encode_video2(fmt_ctx->streams[stream_index]->codec, &enc_pkt,
NULL, &got_frame);
av_frame_free(NULL);
if (ret < 0)
break;
if (!got_frame){
ret = 0;
break;
}
printf("Succeed to encode 1 frame! 编码成功1帧!\n");
/* mux encoded frame */
ret = av_write_frame(fmt_ctx, &enc_pkt);
if (ret < 0)
break;
}
return ret;
}
int main(int argc, char* argv[])
{
AVFormatContext* pFormatCtx;
AVOutputFormat* fmt;
AVStream* video_st;
AVCodecContext* pCodecCtx;
AVCodec* pCodec;
uint8_t* picture_buf;
AVFrame* picture;
int size;
FILE *in_file = fopen("test_yuv420p_320x180.yuv", "rb"); //Input YUV data 视频YUV源文件
int in_w = 320, in_h = 180;//宽高
int framenum = 100;
const char* out_file = "ds.hevc";
av_register_all();
//Method1 方法1.组合使用几个函数
pFormatCtx = avformat_alloc_context();
//Guess Format 猜格式
fmt = av_guess_format(NULL, out_file, NULL);
pFormatCtx->oformat = fmt;
//Method 2 方法2.更加自动化一些
//avformat_alloc_output_context2(&pFormatCtx, NULL, NULL, out_file);
//fmt = pFormatCtx->oformat;
//Output Format 注意输出路径
if (avio_open(&pFormatCtx->pb, out_file, AVIO_FLAG_READ_WRITE) < 0)
{
printf("Failed to open output file! 输出文件打开失败");
return -1;
}
video_st = avformat_new_stream(pFormatCtx, 0);
video_st->time_base.num = 1;
video_st->time_base.den = 25;
if (video_st == NULL)
{
return -1;
}
//Param that must set
pCodecCtx = video_st->codec;
pCodecCtx->codec_id =AV_CODEC_ID_HEVC;
//pCodecCtx->codec_id = fmt->video_codec;
pCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO;
pCodecCtx->pix_fmt = AV_PIX_FMT_YUV420P;
pCodecCtx->width = in_w;
pCodecCtx->height = in_h;
pCodecCtx->time_base.num = 1;
pCodecCtx->time_base.den = 25;
pCodecCtx->bit_rate = 400000;
pCodecCtx->gop_size = 12;
//H264
//pCodecCtx->me_range = 16;
//pCodecCtx->max_qdiff = 4;
//pCodecCtx->qcompress = 0.6;
pCodecCtx->qmin = 10;
pCodecCtx->qmax = 51;
//Optional Param
pCodecCtx->max_b_frames = 3;
// Set Option
AVDictionary *param = 0;
//H.264
if (pCodecCtx->codec_id == AV_CODEC_ID_H264) {
av_dict_set(&param, "preset", "slow", 0);
av_dict_set(&param, "tune", "zerolatency", 0);
}
//H.265
if (pCodecCtx->codec_id == AV_CODEC_ID_H265){
av_dict_set(&param, "x265-params", "qp=20", 0);
av_dict_set(&param, "preset", "default", 0);
av_dict_set(&param, "tune", "zero-latency", 0);
}
//Dump Information 输出格式信息
av_dump_format(pFormatCtx, 0, out_file, 1);
//pCodec = avcodec_find_encoder(pCodecCtx->codec_id);
pCodec = avcodec_find_encoder_by_name("hevc_nvenc");
if (!pCodec){
printf("Can not find encoder! 没有找到合适的编码器!\n");
return -1;
}
if (avcodec_open2(pCodecCtx, pCodec, &param) < 0){
printf("Failed to open encoder! 编码器打开失败!\n");
return -1;
}
picture = av_frame_alloc();
size = avpicture_get_size(pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height);
picture_buf = (uint8_t *)av_malloc(size);
avpicture_fill((AVPicture *)picture, picture_buf, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height);
//Write File Header 写文件头
avformat_write_header(pFormatCtx, NULL);
AVPacket pkt;
int y_size = pCodecCtx->width * pCodecCtx->height;
av_new_packet(&pkt, y_size * 3);
for (int i = 0; i<framenum; i++){
//Read YUV 读入YUV
if (fread(picture_buf, 1, y_size * 3 / 2, in_file) < 0){
printf("Failed to read YUV data! 文件读取错误\n");
return -1;
}
else if (feof(in_file)){
break;
}
picture->data[0] = picture_buf; // 亮度Y
picture->data[1] = picture_buf + y_size; // U
picture->data[2] = picture_buf + y_size * 5 / 4; // V
//PTS
picture->pts = i;
picture->format = pCodecCtx->pix_fmt;
picture->width = in_w;
picture->height = in_h;
int got_picture = 0;
//Encode 编码
int ret = avcodec_encode_video2(pCodecCtx, &pkt, picture, &got_picture);
if (ret < 0){
printf("Failed to encode! 编码错误!\n");
return -1;
}
if (got_picture == 1){
printf("Succeed to encode 1 frame! 编码成功1帧!\n");
pkt.stream_index = video_st->index;
ret = av_write_frame(pFormatCtx, &pkt);
av_free_packet(&pkt);
}
}
//Flush Encoder
int ret = flush_encoder(pFormatCtx, 0);
if (ret < 0) {
printf("Flushing encoder failed\n");
return -1;
}
//Write file trailer 写文件尾
av_write_trailer(pFormatCtx);
//Clean 清理
if (video_st){
avcodec_close(video_st->codec);
av_free(picture);
av_free(picture_buf);
}
avio_close(pFormatCtx->pb);
avformat_free_context(pFormatCtx);
fclose(in_file);
system("pause");
return 0;
}
Help!!!!
after a few days of strugglling,once again I try anwser the question myself.The key point is ,when encoding with hevc_nvenc,you must set pCodecCtx->max_b_frames = 0;(at least for version 3.2 of ffmpeg).

Current date wont update

I have 2 buttons one to log in and the other to log out. I would like both of them to show different times but for some reason unknown to me they do not. and when all the info is saved to a file it says null where there's no information. If there is a way to change that it would be greatly appreciated.
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class MainGUI extends JFrame {
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date date = new Date();
String[] columnNames = {"ID", "NAME", "COURSE", "Professor", "Reason for Tutor", "Login Time", "Logout Time"};
Object[][] data = new Object[25][7];
// table
JTable table = new JTable(data, columnNames) {
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
JFrame frame, frame1;
JPanel buttonPanel, buttonPanel2, tablePanel, addPanel, editPanel;
JLabel labelID, labelName, labelCourse, labelProfessor, labelHelp, labelDate, labelDate2;
JTextField txtID, txtName, txtCourse, txtProfessor, txtHelp, txtDate, txtDate2;
JButton btnAdd, btnEdit, btnDelete, btnSort, btnSave, btnAddInput, btnCancel;
int keyCode, rowIndex, rowNumber, noOfStudents;
MainGUI.ButtonHandler bh = new MainGUI.ButtonHandler();
public MainGUI() {
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getSelectionModel().addListSelectionListener(new MainGUI.RowListener());
table.getColumnModel().getColumn(1).setPreferredWidth(150);
table.getColumnModel().getColumn(3).setPreferredWidth(100);
table.getColumnModel().getColumn(4).setPreferredWidth(200);
table.getColumnModel().getColumn(5).setPreferredWidth(150);
table.getColumnModel().getColumn(6).setPreferredWidth(150);
table.getTableHeader().setResizingAllowed(false);
table.getTableHeader().setReorderingAllowed(false);
JScrollPane scrollPane = new JScrollPane(table);
btnAdd = new JButton("Login");
btnAdd.addActionListener(bh);
btnEdit = new JButton("EDIT");
btnEdit.addActionListener(bh);
btnEdit.setEnabled(false);
btnDelete = new JButton("DELETE");
btnDelete.addActionListener(bh);
btnDelete.setEnabled(false);
btnSort = new JButton("Logout");
btnSort.addActionListener(bh);
btnSave = new JButton("SAVE");
btnSave.addActionListener(bh);
btnSave.setActionCommand("Save");
btnAddInput = new JButton("Login");
btnAddInput.addActionListener(bh);
btnAddInput.setActionCommand("AddInput");
btnCancel = new JButton("Cancel");
btnCancel.addActionListener(bh);
labelID = new JLabel("ID");
labelName = new JLabel("NAME");
labelCourse = new JLabel("Course");
labelProfessor = new JLabel("Professor");
labelHelp = new JLabel("Reason for Tutoring");
labelDate = new JLabel("Login");
labelDate2 = new JLabel("Logout");
txtID = new JTextField(20);
txtName = new JTextField(20);
txtCourse = new JTextField(20);
txtProfessor = new JTextField(20);
txtHelp = new JTextField(20);
txtDate = new JTextField(20);
txtDate2 = new JTextField(20);
txtID.setDocument(new MainGUI.JTextFieldLimit(15));
txtID.addKeyListener(keyListener);
tablePanel = new JPanel();
tablePanel.setLayout(new BoxLayout(tablePanel, BoxLayout.PAGE_AXIS));
tablePanel.setBorder(BorderFactory.createEmptyBorder(10, 2, 0, 10));
tablePanel.add(table.getTableHeader());
tablePanel.add(table);
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
c.fill = GridBagConstraints.HORIZONTAL;
buttonPanel.add(btnAdd, c);
c.gridx = 0;
c.gridy = 1;
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
buttonPanel.add(btnEdit, c);
c.gridx = 0;
c.gridy = 2;
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
buttonPanel.add(btnDelete, c);
c.gridx = 0;
c.gridy = 3;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
c.fill = GridBagConstraints.HORIZONTAL;
buttonPanel.add(btnSort, c);
c.gridx = 0;
c.gridy = 4;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
c.fill = GridBagConstraints.HORIZONTAL;
buttonPanel.add(btnSave, c);
frame = new JFrame("Tutoring Database");
frame.setVisible(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.add(tablePanel, BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.EAST);
frame.pack();
addPanel = new JPanel();
addPanel.setLayout(new GridBagLayout());
c.insets = new Insets(1, 0, 1, 1);
c.gridx = 0;
c.gridy = 0;
addPanel.add(labelID, c);
c.gridy = 1;
addPanel.add(labelName, c);
c.gridy = 2;
addPanel.add(labelCourse, c);
c.gridy = 3;
addPanel.add(labelProfessor, c);
c.gridy = 4;
addPanel.add(labelHelp, c);
c.gridy = 5;
addPanel.add(labelDate, c);
c.gridy = 6;
addPanel.add(labelDate2, c);
// text fields
c.gridx = 1;
c.gridy = 0;
c.ipady = 1;
addPanel.add(txtID, c);
c.gridy = 1;
c.ipady = 1;
addPanel.add(txtName, c);
c.gridy = 2;
c.ipady = 1;
addPanel.add(txtCourse, c);
c.gridy = 3;
c.ipady = 1;
addPanel.add(txtProfessor, c);
c.gridy = 4;
c.ipady = 1;
addPanel.add(txtHelp, c);
c.gridy = 5;
c.ipady = 1;
addPanel.add(txtDate, c);
c.gridy = 5;
c.ipady = 1;
addPanel.add(txtDate2, c);
buttonPanel2 = new JPanel();
buttonPanel2.setLayout(new GridLayout(1, 1));
buttonPanel2.add(btnAddInput);
buttonPanel2.add(btnCancel);
frame1 = new JFrame("Student Database");
frame1.setVisible(false);
frame1.setResizable(false);
frame1.setDefaultCloseOperation(HIDE_ON_CLOSE);
frame1.add(addPanel, BorderLayout.CENTER);
frame1.add(buttonPanel2, BorderLayout.PAGE_END);
frame1.pack();
}// end
KeyListener keyListener = new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
keyCode = e.getKeyCode();
if (!(keyCode >= 48 && keyCode <= 57) && !(keyCode >= 96 && keyCode <= 105)
&& !(keyCode >= 37 && keyCode <= 40) && !(keyCode == 127 || keyCode == 8)) {
txtID.setEditable(false);
}
}
#Override
public void keyReleased(KeyEvent e) {
txtID.setEditable(true);
}
};
class RowListener implements ListSelectionListener {
#Override
public void valueChanged(ListSelectionEvent event) {
if (event.getValueIsAdjusting()) {
rowIndex = table.getSelectedRow();
if (data[rowIndex][0] == null || data[rowIndex][0] == "") {
btnEdit.setEnabled(false);
btnDelete.setEnabled(false);
} else {
btnEdit.setEnabled(true);
btnDelete.setEnabled(true);
}
}
}
}
class ButtonHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Login")) {
txtID.setText("");
txtName.setText("");
txtCourse.setText("");
txtProfessor.setText("");
txtHelp.setText("");
txtDate.setText(dateFormat.format(date));
frame1.setTitle("Add Student data"); // title bar name for add
frame1.setVisible(true);
} else if (e.getActionCommand().equals("EDIT")) {
txtID.setText(data[rowIndex][0] + "");
txtName.setText(data[rowIndex][1] + "");
txtCourse.setText(data[rowIndex][2] + "");
txtProfessor.setText(data[rowIndex][3] + "");
txtHelp.setText(data[rowIndex][4] + "");
txtDate.setText(data[rowIndex][5] + "");
txtID.setEditable(false);
frame1.setTitle("Edit Student data");
btnAddInput.setActionCommand("Edit2");
btnAddInput.setText("ACCEPT");
frame1.setVisible(true);
} else if (e.getActionCommand().equals("DELETE")) {
int confirm = JOptionPane.showConfirmDialog(frame, "ARE YOU SURE?", "CONFIRM",
JOptionPane.YES_NO_OPTION);
if (confirm == 0) {
rowIndex = table.getSelectedRow();
rowNumber = 0;
noOfStudents--;
for (int i = 0; i <= 10; i++) {
if (rowIndex != i && i <= noOfStudents) {
data[rowNumber][0] = data[i][0];
data[rowNumber][1] = data[i][1];
data[rowNumber][2] = data[i][2];
data[rowNumber][3] = data[i][3];
data[rowNumber][4] = data[i][4];
data[rowNumber][5] = data[i][5];
rowNumber++;
} else if (rowIndex != i && i > noOfStudents) {
data[rowNumber][0] = "";
data[rowNumber][1] = "";
data[rowNumber][2] = "";
data[rowNumber][3] = "";
data[rowNumber][4] = "";
data[rowNumber][5] = "";
rowNumber++;
}
}
if (noOfStudents == 1000) {
btnAdd.setEnabled(false);
}
else {
btnAdd.setEnabled(true);
}
if (noOfStudents == 0) {
btnDelete.setEnabled(false);
btnEdit.setEnabled(false);
} else {
btnDelete.setEnabled(true);
btnEdit.setEnabled(true);
}
rowIndex = table.getSelectedRow();
if (data[rowIndex][0] == null || data[rowIndex][0] == "") {
btnEdit.setEnabled(false);
btnDelete.setEnabled(false);
} else {
btnEdit.setEnabled(true);
btnDelete.setEnabled(true);
}
table.updateUI();
}
} else if (e.getActionCommand().equals("AddInput")) {
if (txtID.getText().isEmpty() || txtName.getText().isEmpty()
|| txtCourse.getText().isEmpty()// /
|| txtProfessor.getText().isEmpty() || txtHelp.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "PLEASE FILL IN THE BLANKS.", "ERROR!",
JOptionPane.ERROR_MESSAGE);
}
else {
int dup = 0;
for (int i = 0; i < 10; i++) {
if (txtID.getText().equals(data[i][0])) {
JOptionPane.showMessageDialog(null, "ID NUMBER ALREADY EXISTS.", "ERROR!",
JOptionPane.ERROR_MESSAGE);
dup++;
}
}
if (dup == 0) {
rowIndex = table.getSelectedRow();
data[noOfStudents][0] = txtID.getText();
data[noOfStudents][1] = txtName.getText();
data[noOfStudents][2] = txtCourse.getText();
data[noOfStudents][3] = txtProfessor.getText();
data[noOfStudents][4] = txtHelp.getText();
data[noOfStudents][5] = txtDate.getText();
table.updateUI();
frame1.dispose();
noOfStudents++;
if (noOfStudents == 50){
btnAdd.setEnabled(false);
}
else {
btnAdd.setEnabled(true);
}
if (data[rowIndex][0] == null) {
btnEdit.setEnabled(false);
btnDelete.setEnabled(false);
} else {
btnEdit.setEnabled(true);
btnDelete.setEnabled(true);
}
}
}
table.updateUI();
}else if(e.getActionCommand().equals("Save")){
try {
PrintWriter out = new PrintWriter("Tutor.txt");
for(int i = 0; i < 25; i++)
{
for(int j = 0; j < 7; j++)
{
out.print(data[i][j]);
out.print(", ");
if(j == 6){
out.println();
}
} out.flush();
}} catch (FileNotFoundException ex) {
}
} else if (e.getActionCommand().equals("Logout")) {
int confirm = JOptionPane.showConfirmDialog(frame, "ARE YOU SURE?", "CONFIRM",
JOptionPane.YES_NO_OPTION);
if (confirm == 0) {
rowIndex = table.getSelectedRow();
rowNumber = 0;
txtDate2.setText(dateFormat.format(date));
}
}
if (txtID.getText().isEmpty() || txtName.getText().isEmpty()
|| txtCourse.getText().isEmpty() || txtProfessor.getText().isEmpty()
|| txtHelp.getText().isEmpty()|| txtHelp.getText().isEmpty()) {
} else {
data[rowIndex][0] = txtID.getText();
data[rowIndex][1] = txtName.getText();
data[rowIndex][2] = txtCourse.getText();
data[rowIndex][3] = txtProfessor.getText();
data[rowIndex][4] = txtHelp.getText();
data[rowIndex][5] = txtDate.getText();
data[rowIndex][6] = txtDate2.getText();
frame1.dispose();
}
table.updateUI();
}
}
class JTextFieldLimit extends PlainDocument {
private int limit;
JTextFieldLimit(int limit) {
super();
this.limit = limit;
}
JTextFieldLimit(int limit, boolean upper) {
super();
this.limit = limit;
}
#Override
public void insertString(int offset, String str, AttributeSet attr)
throws BadLocationException {
if (str == null) {
return;
}
if ((getLength() + str.length()) <= limit) {
super.insertString(offset, str, attr);
}
}
}
public static void main(String[] args) {
new MainGUI();
}
}
Simple answer withing swimming through your ocean of code, you need to create a new date in your actionPerformed whenever you want to show the updated date
example
public void actionPerforemd(ActionEvent e){
...
date = new Date();
// do something with date
...
}