Howdy, Stranger!

We are about to switch to a new forum software. Until then we have removed the registration on this forum.

  • createWriter() ouput based on time of the day
    String date = hour () + ":" + day() + "-" + month() + "-" + year();
    

    be careful with this - windows doesn't like : in filenames.

    i would also stick with just YYDDMMHH format because that way the files sort more sensibly. java's SimpleDateFormat is probably better than using hour() etc because hour() doesn't pad single digit hours and that will also cause confusion. (you can use nf() though)

  • How to use random to get at my color array
    /** 
     * SimpleDateFormat Image Save (v1.0.1)
     * GoToLoop (2017/Aug/25)
     *
     * Forum.Processing.org/two/discussion/23896/
     * how-to-use-random-to-get-at-my-color-array#Item_18
     */
    
    import java.util.Date;
    import java.text.SimpleDateFormat;
    
    static final String FOLDER_PATTERN = "yyyy-MM-dd";
    final SimpleDateFormat foldFormat = new SimpleDateFormat(FOLDER_PATTERN);
    
    static final String FILE_PATTERN = "H-mm-ss-SSS";
    final SimpleDateFormat fileFormat = new SimpleDateFormat(FILE_PATTERN);
    
    static final String FILE_NAME = "chips", EXT_NAME = ".png";
    
    void setup() {
      noLoop();
    }
    
    void draw() {
      background((color) random(#000000));
    }
    
    void mousePressed() {
      if (mouseButton != LEFT)  saveDateImage(getGraphics());
      redraw();
    }
    
    void keyPressed() {
      if (key != ESC)  saveDateImage(getGraphics());
      redraw();
    }
    
    void saveDateImage(final PImage pic) {
      final Date now = new Date();
      final String fold = foldFormat.format(now);
      final String file = fileFormat.format(now);
    
      println(fold, file);
    
      final String name = fold + '/' + file + '.' + FILE_NAME + EXT_NAME;
      final String path = dataPath(name);
    
      println(path, ENTER);
      pic.save(path);
    }
    
  • How to use random to get at my color array

    Cool. Fixed my formatting. I've got an incrementing number to keep the files unique (I think?). Now I'm having trouble incorporating, @GoToLoop, your suggestion. The code looks really simple, but I can't get it to work. I added this to my setup:

      final String PATTERN = "H:mm:ss:SSS";
      final SimpleDateFormat formatter = new SimpleDateFormat(PATTERN);
      Date now = new Date();
      String formatted_date = formatter.format(now);
    

    And then have this for my save in the for loop:

      sourceImage.save("/Users/Petros/Desktop/Chips/IndividualChips/NumberingTest/"+"Chip_"+file_number+"_"+formatted_date.png"); 
      file_number+=1;
    

    But I'm getting the error "String literal is not properly closed by a double quote." Why should file_number not need a double quote but formatted_date does? Or, any suggestions on how to properly put the formatted date into the filename? I'm really thankful for all the help you folks have provided!

  • How to use random to get at my color array

    Thanks @koogs. Is simpleDateFormat included in processing already or do I have to add a library? I found this and this but my code isn't working for it. I put this in the setup section

    int dateFormat;
      dateFormat = SimpleDateFormat("yyyy-MM-dd HH-mm-ss") ;
    

    But the console (right term?) says "The function "SimpleDateFormat(String) does not exist". I'm probably doing something obviously wrong. Any pointers on how to do this right? I've read this and this.

    Definitely get your point about the saveFrame() and #####; that was kind of a shot in the dark. When you say "Add X and y to the filename to save all of them" I'm not sure what you mean. Can you elaborate for me?

  • How to use random to get at my color array

    The ###### in the filename gets replaced with the frame number. But this is the same for all values of your for loop as they are all drawn in the same frame. So each is overridden by the next meaning you only see the last.

    Add X and y to the filename to save all of them.

    And look at Java's simpleDateFormat...

  • I want the sound representing points to be vertical (See description)

    I have modified a lot of code, added them up and came up with this..Here the sound representing points are presented in horizontal ..I want these points to be put vertical..But with this code I cant get my logic right..Any help?TIA..

    import ddf.minim.analysis.*;
    import ddf.minim.*;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.List;
    
    
    Minim minim;
    AudioInput in;
    FFT fft;
    AudioPlayer song;
    String str="X coordinate= || Y cordinate=";
    ArrayList<String> times = new ArrayList();
    
    
    
    // Configuration: spectrogram size (pixels)
    int colmax = 500;
    int rowmax = 250;
    // Sample rate
    float sampleRate = 22050;
    // buffer size (= FFT size, must be power of 2)
    int bufferSize = 1024;
    
    // Variables
    int[][] sgram = new int[rowmax][colmax];
    int col;
    int row;
    int leftedge;
    int topedge;
    int window_len = bufferSize;
    String timeHoover="";
    
    PFont mono;
    
    
    void setup()
    {
      size(580, 250, P3D);
      textMode(SCREEN);
      textFont(createFont("SanSerif", 12));
    
      minim = new Minim(this);
      song = minim.loadFile("theMez.mp3", bufferSize);
      song.loop();
      // setup audio input
      //in = minim.getLineIn(Minim.MONO, bufferSize, sampleRate);
    
      fft = new FFT(song.bufferSize(), song.sampleRate());
    
      // suppress windowing inside FFT - we'll do it ourselves
      fft.window(FFT.NONE);
      times.add("");
    }
    
    void draw()
    {
      background(0);
      stroke(255);
      strokeWeight(3);
      line(70, 0, 70, height);
    
      //song.play();
      // grab the input samples
      float[] samples = song.mix.toArray();
      // apply windowing
      for (int i = 0; i < samples.length/2; ++i) {
        // Calculate & apply window symmetrically around center point
        // Hanning (raised cosine) window
        float winval = (float)(0.5+0.5*Math.cos(Math.PI*(float)i/(float)(window_len/2)));
        if (i > window_len/2)  winval = 0;
        samples[samples.length/2 - i] *= winval;
        samples[samples.length/2 + i] *= winval;
      }
      // zero out first point (not touched by odd-length window)
      samples[0] = 0; 
    
      // perform a forward FFT on the samples in the input buffer
      fft.forward(samples);
    
      // fill in the new column of spectral values
      for (int i = 0; i < colmax /* fft.specSize() */; i++) {
        sgram[row][i] = (int)Math.round(Math.max(0, 2*20*Math.log10(1000*fft.getBand(i))));
    
      }
    
      // next time will be the next column
      row = row+1;
      // wrap back to the first column when we get to the end
      if (row == rowmax) { 
        row = 0;
      }
    
      // Draw points.
      // leftedge is the column in the ring-filled array that is drawn at the extreme left
      // start from there, and draw to the end of the array
    
    
      for (int i= 0; i<colmax; i++)
      {
        for (int j=0; j<row; j++)
        {
          stroke(sgram[j][i]);
          point(100+i,j);
         // l.add(sdf.format(cal.getTime()));
    
        }
      }
    
    
    
      //==============timePrinting
      mono = createFont("Verdana", 12);
      textFont(mono);
       if ( !times.get(0).equals("" + hour() + ":" + minute() + ":" + second())) {
        times.add(0, "" + hour() + ":" + minute() + ":" + second());
      }
     // println(times.size());
      while (times.size() > 15) { 
        times.remove(15);
      }
      for ( int i = 0; i < times.size(); i++) {
        text(times.get(i), 5,  20* i);
    
        if (times.get(i).length()>0)
        {
          //timeHoover= times.get(i);
        stroke(255);
        strokeWeight(2);
        line(5,20*i+5,35,20*i+5);
        }
    
      }
    
    
      text(timeHoover,480,40);
      // Report window size
      //text(str, 8, 10);
    }
    
    
    void mousePressed()
    {
      str="X cordinate = ";
      str += String.valueOf(mouseX);
      str+=" || Y cordinate = ";
      str+=String.valueOf(mouseY);
    }
    
    void mouseDragged() {
      // map mouse position within window to -1..1
      float proportion = map(mouseX, 0, colmax, -1, 0);
      // convert to window length, log scale, 2^8 range
      window_len = (int)Math.round(Math.pow(2.0, 4.0*proportion)*(float)bufferSize);
      text("asdffs",50,50);
    }
    
    void mouseMoved()
    {
    
      int y = mouseY;
      int pos= mouseY/20;
      if (pos<times.size())
      {
        timeHoover = times.get(pos);
        text(timeHoover,480,40);
      }
    }
    
    
    void stop()
    {
      // always close Minim audio classes when you finish with them
      in.close();
      minim.stop();
      super.stop();
    }
    

    And this is the representation: help

  • I want my system time to go from top to bottom (see description please)

    I want my system time to appear from the top of the screen and go downwards but the time which comes from the top should stay there not updated..Like this below

    time

    I have tried something in the code..but each time is getting updated.What I want is current time(lets say 12:00:00) will appear from row 1 and then 12:00:00 will go down through the screen but will not change.And then 12:00:01 will appear from row 1. and go through the screen..I cant get this things right..It gets updated..Any help..TIA..My code

    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    
    //global variables / objects
    
    int Counter;
    int row;
    int timeIndex[] = new int[401];
    
    // =================================================================
    // Main functions
    void setup() {
      size(400, 400);
    
    }
    void draw () {
      time();
    }
    // =================================================================
    // Other functions
    void time() {
        Calendar cal = Calendar.getInstance();
      SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
      
      background(#FFFFFF);
      fill(#000000);
      textAlign(CENTER);
      String total= hour()+" :"+minute()+" :"+second();
      // textFont(words, 50);
        for(int k=row;k>=0;k-=12)
      {
        
        
        text(sdf.format(cal.getTime()),35,k);
      }
     
    
      row+=1;
    
      
    }
    // =================================================
    // classes
    

    My output is like below:

    sdfsfd

  • saveFrame function inconsistency

    Hello guys! Need some help!

    I am trying to use save frame to take a screenshot of a plot I have currently programmed with processing. The plot GUI has several Buttons (made with Cp5) and Toggles. I have set a function which is being called when a button is pressed. However, sometime the frame I take comes with the cp5 buttons GUI but sometimes doesn't. So some frames have the buttons but some don't. For example: 2017_05_10-17_26_38113

    2017_05_10-17_26_40115

    Hope, you can see the frames. The code I use for the button is:

    Button b1 = cp5.addButton("takeScreenShot").setPosition(z, w).setSize(100, 80);
    
      b1.addCallback(new CallbackListener() {
        public void controlEvent(CallbackEvent theEvent) {
          switch(theEvent.getAction()) { 
            case(ControlP5.ACTION_PRESSED): 
            if (flag) {
              println("Taking photo...");
              takeScreenShot();
            }
            break;
             case(ControlP5.ACTION_RELEASED): 
             println("Done");
             flag = true;
             break;
          }
        }
      }
      );
    

    and the function called for the takeFrame():

    void takeScreenShot() {
          String photoDate = new SimpleDateFormat("yyyy_MM_dd-HH_mm_ss").format(new Date());
          String Date = new SimpleDateFormat("yyyy_MM_dd").format(new Date());
          int m = millis()/1000; //for seconds
          saveFrame("C:/Users/. . . .. . ./data/"+ Date + "/photos/" +  "/manual/"+ photoDate + String.valueOf(m)+ ".jpg");
        }
    

    Is there any suggestions on how to tackle this problem?? I would appreciate any help, and any clarifications if needed.

    ps. If the photos don't show, the buttons from cp5 configurations sometimes show sometimes don't. Can't find any reason why.!

  • Regex pattern matching

    Hi, I found some code in the old forum which I'm trying to modify to pull in image URL from a webpage. In the original code it is matching an image tag in the form of

    <IMG SRC="image/1207/AR1520_071112friedman900.jpg"

    Using

    // Optional spaces, the IMG tag and its attribute, capture of the URL, anything after it
    Pattern pat = Pattern.compile("\\s*<IMG SRC=\"(image/.*?)\".*");
    

    However I want to match/extract a tag in the form of

    <a class="link" href="GOPR0237.JPG">GOPR0237.JPG</a>
    

    (where the 4 digits between "GOPR" and ".JPG" are unknown, ultimately it will be compiled into the url

    "http://10.5.5.9:8080/DCIM/100GOPRO/GOPRxxxx.JPG" so the image can be downloaded.

    This is the current full code if anyone's interested

    import processing.net.*;
    import java.util.regex.*;
    import java.util.*;
    import java.text.*;
    
    Client c;
    String URL_BASE = "http://10.5.5.9:8080/DCIM/100GOPRO/";  // Where the Gopro stores it's images
    
    PImage GoProImage;
    
    Pattern pat = Pattern.compile("\\s*href=\"(GOPR.*?)\".*"); //NOT CURRENTLY WORKING!
    
    void setup()
    {
    
      size(4000, 3000); 
      background(50);
      fill(200);
    
      DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
      String imageName = "GoPro-" + df.format(new Date()) + ".jpg";
    
      c=new Client(this, "10.5.5.9", 80);
      c.write("GET /bacpac/SH?t=oakh6214&p=%01 HTTP/1.0\r\n");
      c.write("\r\n");
    
      String url = findImageURL(URL_BASE);
      print(url);
      if (url != null) // Found
      {
        GoProImage = loadCachedImage(imageName, URL_BASE + url);
      }
    }
    
    void draw()
    {
      image(GoProImage, 0, 0);
    }
    
    String findImageURL(String pageURL)
    {
      String url = null;
      String[] lines = loadStrings(pageURL);
      for (String line : lines)
      {
        Matcher m = pat.matcher(line);
        if (m.matches())
        {
          url = m.group(1);
          break;
        }
      }
    
      return url;
    }
    
    PImage loadCachedImage(String fileName, String url)
    {
      PImage img = loadImage(fileName);
      if (img == null) // Not downloaded yet
      {
        img = loadImage(url);
        if (img != null)
        {
          img.save(fileName); // Cache of the file
        } else
        {
          println("Unable to load the image from " + url);
          exit();
        }
      }
      return img;
    }
    
  • UTC/GMT time using UDP / NTP

    I changed your receive function to this other way shown below. Not sure if the negative offsets artificially introduced are due to working with int data types. It will be great to have a better way to do the conversion. Can you comment about that negative value?

    Kf

    import java.nio.ByteBuffer;
    import java.util.Date;
    import java.text.SimpleDateFormat;
    
    
    void receive( byte[] data )  // <-- default handler
    {   
      // NOTICE ByteBuffer.wrap(data, 40, 4).getInt() is same value as your variable "af" in your code
      ByteBuffer bb =ByteBuffer.wrap(data, 40, 4);
      //2*1104494400   is the offset to get correct time
      //Factor of 1000 to convert seconds to msecs
      Date date = new Date( (long)(ByteBuffer.wrap(data, 40, 4).getInt()-2*1104494400)* 1000);
      SimpleDateFormat sdf = new SimpleDateFormat("EEEE,MMMM d,yyyy h:mm,a");
      System.out.println(sdf.format(date));
    
    }
    
  • How to copy the out canvas image in the screen without saving image file?

    Check this code:

    Kf

    //REFERENCE: https://docs.oracle.com/javase/7/docs/api/java/awt/Robot.html
    //REFERENCE: http://stackoverflow.com/questions/4490454/how-to-take-a-screenshot-in-java
    //REFERENCE: https://processing.org/reference/PImage_get_.html
    //REFERENCE: https://forum.processing.org/two/discussion/9874/how-to-take-control-of-the-mouse-outside-the-sketch-window#latest
    
    import java.awt.Rectangle;
    import java.awt.Robot;
    import java.awt.Toolkit;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import javax.imageio.ImageIO;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.*;
    
    
    
    Robot rbt;
    boolean loadNow=false;
    PImage img;
    
    void setup() {
      size(600,600);
    
      try {
        rbt = new Robot();
      } 
      catch(Exception e) {
        e.printStackTrace();
      }
    }
    
    void draw() {
    
      if(loadNow==true){
        img=loadImage("screenshot.jpg");
        println(img.width+" "+img.height);
        image(img.get(200,200,600,600),0,0);   //HERE is where you setup the parameters to grab box B as shown in your post.
        loadNow=false;
      }
    }
    
    void mouseReleased() {
      BufferedImage image2 = rbt.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
      println("Capturing image...");
    
      try {
        ImageIO.write(image2, "JPG", new File(("screenshot.jpg")));
        println("Saving image...");
        loadNow=true;
      }
      catch (IOException e) {
        e.printStackTrace();
      }
    }
    
  • Is there a way to access a fraction of a second of the system clock? (not millis() related)

    Based on this SimpleDateFormat tutorial: O:-)
    http://docs.Oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html

    import java.util.Date;
    import java.text.SimpleDateFormat;
    
    final String PATTERN = "H:mm:ss:SSS";
    final SimpleDateFormat formatter = new SimpleDateFormat(PATTERN);
    
    Date now = new Date();
    String result = formatter.format(now);
    
    println(result);
    exit();
    
  • my for-loop skips a position

    i tried to adjust a slit scan video code to move the copy command from left to right through the video. that works, but in the output it skips a position, leaving a white strip between. how can i make the output dense?

    import processing.video.*;
    Movie myMovie;
    int pos;
    int sliceSize = 5;
    int outputcounter= 1;
    String date;
    void setup() {
      size(5000, 720);
      myMovie = new Movie(this, "versuch1.mp4");
      myMovie.loop();
      pos = 0;
      date = timestamp();
      //myMovie.jump(176);
    }
    void draw() {
      if (myMovie.available()) {
        myMovie.read();
        pushMatrix();
        for (int i=0; i<1280; i+= sliceSize){
        //translate(width/2, height/2);
        //rotate(HALF_PI);
        //translate(-width/2, -height/2);
        //tint(255, 20);
        copy(myMovie, i, 0, sliceSize, myMovie.height, pos, 0, sliceSize, height); //(copy (quelle, x , y, breite, höhe, position im neuen bild, ))
        scale(-1,1);
        pos+=sliceSize*i; //horizontal gefilmt
        //copy(myMovie, 0, myMovie.height/2, myMovie.width, sliceSize, 0, pos, width, sliceSize); //vertical gefilmt
        //pos-=sliceSize;
        if (pos>width) {
          saveFrame("png/"+ date+"/"+nf(outputcounter,3)+".png");
          outputcounter++;
          pos = 0;
        }
        }
        //image(myMovie, 0,0,960,540);}
        popMatrix();
      }
      }
    
    
    // Called every time a new frame is available to read
    /**void movieEvent(Movie m) {
     m.read();
     }*/
    
    void keyPressed() {
      if (key == 32) {
        saveFrame("png/output_"+timestamp()+".png");
      }
    }
    
    String timestamp() {
      return new java.text.SimpleDateFormat("yyyy_MM_dd_kkmmss").format(new java.util.Date ());
    }
    
    //webseite 100vh quadrat (3/4=133) png= 001.png, 002.png
    
  • Minified JSON

    Hi,

    I've written the following code to convert a CSV file into JSON and it all works fast and efficiently. The only issue I have is that it produces an 'unminified' JSON format rather than my preferred format of 'minified'. Is there a simple change I could make to the program or an option I could use to produce a minified format?

    Many thanks!

    Table csv  = loadTable("D:/09SEP16.csv", "header");
    JSONArray values = new JSONArray();
    int i=0;
    String isoDate; 
    
    for (TableRow r : csv.rows ()) {
          JSONObject json = new JSONObject();
          try{ 
           isoDate = new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("ddMMMyy").parse(r.getString("DATE")));
          } 
          catch (Exception e){
            println("Date Error");
            isoDate = "01-01-2017";
          }
    
          json.setString("T", r.getString("TIME"));
          json.setInt("S", r.getInt("S"));
          json.setString("U", r.getString("USER"));
          json.setString("F", r.getString("FULLPATH"));
          json.setString("i", isoDate);
          values.setJSONObject(i++, json);
        }
    
        saveJSONArray(values, "D:/09SEP16.json");
        println(csv.getRowCount());
        exit();
    
  • yyyyMMdd to EPOCH conversion

    Look at java's SimpleDateFormat

  • How to save multiple .PDF files from the same sketch?

    do you have multiple beginRecord()s as well as multiple endRecord()s? i think you need to.

    just change the filename in the beginRecord(). use a counter, or frameCount, or simpleDateFormat to generate a unique filename.

  • Date format

    SimpleDateFormat is a Java Class; so the nearest equivalent for use with p5js is JavaScript's built-in Date object...

    ...though as koogs says; depending on your needs a substring might be simpler.

  • Date format

    Is SimpleDateFormat compatible with P5.JS? I need to convert "YYYY-MM-DD HH:mm:ss" to just a simple "HH". I can't seam to find any instruction on how to set it up. Thanks.