#java.util.concurrent.TimeUnit
Explore tagged Tumblr posts
3c65 · 3 years ago
Text
package ti;
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.nio.charset.Charset; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern;
import org.jsoup.Connection; import org.jsoup.Jsoup; import org.jsoup.nodes.Document;
import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.collect.Collections2; import com.google.common.collect.Lists;
public class InstagramReplicator { public static InstagramReplicator newInstance(String instagramUser, String tumblrUser, String tagName) throws IOException { return new InstagramReplicator(instagramUser, tumblrUser, tagName); } public void doUpdate() throws IOException { System.out.println("Checking for updates: instagramUser=" + instagramUser);    for(String instagramUrl : loadInstagramUrls()) {    if(!currentImages.contains(instagramUrl))    {        submitPostToTumblr                (                    loadInstagramPost(instagramUrl)                );                currentImages.add(instagramUrl);                if(currentImages.size() > 100)        {            currentImages.remove(currentImages.get(0));        }    } } } private List<String> loadInstagramUrls() throws IOException {    List<String> instagramUrls = findMatches        (            Jsoup.connect("http://instagram.com/" + instagramUser).get().outerHtml(),            "\"link\":\"(http:\\\\/\\\\/instagram\\.com\\\\/p\\\\/[^\\\\]*\\\\/)\"",            true        );        Collections.reverse(instagramUrls);        //System.out.println(instagramUser + " - " + instagramUrls);        return instagramUrls; } private Post loadInstagramPost(String postUrl) throws IOException { System.out.println("Loading post: postUrl=" + postUrl);     String docText = Jsoup.connect(postUrl).get().outerHtml(); //System.out.println("doctext=" + docText); String caption = "<p>" + findMatch(docText, "\"caption\":\"(.*?[^\\\\])\"", false) + "</p>"; String tagRegEx = "#([A-Za-z0-9_]+)"; String userRegEx = "@([A-Za-z0-9_]+)"; List<String> tags = Lists.newArrayList(); tags.addAll(findMatches(caption, tagRegEx, false)); tags.addAll(findMatches(caption, userRegEx, false)); //caption = caption.replaceAll(tagRegEx, "<a href=\\\\\"http://www.gramfeed.com/instagram/tags#$1\\\\\">$0</a>"); caption = caption.replaceAll(userRegEx, "<a href=\\\\\"http://instagram.com/$1\\\\\">$0</a>"); if(docText.contains("\"is_video\":true")) {    caption += "<p><a href=\\\"" + postUrl + "\\\">Watch Video</a></p>"; } return new Post        (            postUrl,            findMatch(docText, "\"display_src\":\"([^\"]*)\"", true), //imageUrl            caption,            Joiner.on(",").join(tags)        ); } private void submitPostToTumblr(Post post) throws IOException { System.out.println("Submitting post: post=" + post); try        {            HttpURLConnection connection = (HttpURLConnection) new URL("http://www.tumblr.com/svc/post/update").openConnection();
           connection.setDoOutput(true);            connection.setDoInput(true);            connection.setInstanceFollowRedirects(false);            connection.setRequestMethod("POST");            connection.setRequestProperty("Cookie", tumblrCookie);            connection.setRequestProperty("X-tumblr-puppies", getSecureFormKey());            connection.setRequestProperty("X-tumblr-form-key","OdhVH6QQTBzl9IZZDViXwyj5vOU");            connection.setRequestProperty("Origin","http://www.tumblr.com");            connection.setRequestProperty("Accept-Encoding","gzip,deflate,sdch");            connection.setRequestProperty("Host","www.tumblr.com");            connection.setRequestProperty("Accept-Language","en-US,en;q=0.8");            connection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36");            connection.setRequestProperty("Content-Type","application/json");            connection.setRequestProperty("Accept","application/json, text/javascript, */*; q=0.01");            connection.setRequestProperty("Referer","http://www.tumblr.com/new/photo");            connection.setRequestProperty("X-Requested-With","XMLHttpRequest");            connection.setRequestProperty("Connection","keep-alive");            connection.setRequestProperty("DNT","1");            connection.setUseCaches(false);
           OutputStream output = connection.getOutputStream();                        output.write            (                ("{\"form_key\":\"OdhVH6QQTBzl9IZZDViXwyj5vOU\",\"context_id\":\"\",\"context_page\":\"dashboard\","                + "\"editor_type\":\"rich\",\"is_rich_text[one]\":\"0\",\"is_rich_text[two]\":\"1\",\"is_rich_text[three]\":\"0\","                + "\"channel_id\":\"" + tumblrUser +                "\",\"post[slug]\":\"\","                + "\"post[source_url]\":\"" + post.postUrl +                "\",\"post[date]\":\"\",\"post[three]\":\"" + post.postUrl +                "\",\"MAX_FILE_SIZE\":\"10485760\",\"post[type]\":\"photo\","                + "\"post[two]\":\"" + post.caption +                "\",\"post[tags]\":\"" + Joiner.on(",").join(userTags, post.tags, instagramUser, "instagram").replace('_', ' ') +                "\",\"post[publish_on]\":\"\",\"post[state]\":\"0 3\",\"post[photoset_layout]\":\"1\",\"post[photoset_order]\":\"o1\","                + "\"images[o1]\":\"" + post.imageUrl + "\",\"photo_src[]\":\"" + post.imageUrl +                "\"}").getBytes(Charset.forName("UTF-8"))            );            output.close();
           InputStream input = connection.getInputStream();            while(input.read() != -1) {}
           System.out.println("Post submission complete, httpStatusCode=" + connection.getResponseCode());
           input.close();        } catch (IOException e)        {    if(consecutiveTumblrErrors++ > 10)    {        System.err.println("FATAL: Too many consecutive tumblr failures, shutting down");        System.exit(1);    }        throw e;        } consecutiveTumblrErrors = 0; } private String getSecureFormKey() throws IOException {        Connection connection = Jsoup.connect("http://www.tumblr.com/svc/secure_form_key")                .header("Cookie", tumblrCookie)                .header("X-tumblr-form-key","OdhVH6QQTBzl9IZZDViXwyj5vOU")                .header("Origin","http://www.tumblr.com")                .header("Accept-Encoding","gzip,deflate,sdch")                .header("Host","www.tumblr.com")                .header("Accept-Language","en-US,en;q=0.8")                .header("User-Agent","Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36")                .header("Content-Type","application/json")                .header("Accept","application/json, text/javascript, */*; q=0.01")                .header("Referer","http://www.tumblr.com/new/photo")                .header("X-Requested-With","XMLHttpRequest")                .header("Connection","keep-alive")                .header("DNT","1")                .header("Content-Length", "0");        connection.post();        String secureFormKey = connection.response().header("X-tumblr-secure-form-key");        System.out.println("secureFormKey=" + secureFormKey);
       return secureFormKey; }
private String findMatch(String string, String regex, boolean isUrl) {    List<String> matches = findMatches(string, regex, isUrl);        if(matches.isEmpty())    {        return "";    }        return matches.get(0); } private List<String> findMatches(String string, String regex, boolean isUrl) {       Matcher matcher = Pattern               .compile(regex)               .matcher(string);
          List<String> matches = Lists.newArrayList();
          while(matcher.find())           {               matches.add               (                   matcher                       .group(1)                       .replace                       (                           (isUrl ? "\\" : ""),                           ""                       )                               );           }
          return matches; } //nested classes private class Post {        public Post(String postUrl, String imageUrl, String caption, String tags) { this.postUrl = postUrl; this.imageUrl = imageUrl; this.caption = caption; this.tags = tags; } @Override        public String toString() {            return "Post [postUrl=" + postUrl + ", imageUrl=" + imageUrl                    + ", caption=" + caption + ", tags=" + tags + "]";        }
       private final String postUrl; private final String imageUrl; private final String caption; private final String tags; }   //constructors
   private InstagramReplicator(String instagramUser, String tumblrUser, String tagName) throws IOException    {        this.instagramUser = instagramUser;        this.tumblrUser = tumblrUser;        this.userTags = tagName;        currentImages = loadInstagramUrls();
      /* currentImages.removeAll        (            Splitter                .on(',')                .trimResults()                .omitEmptyStrings()                .splitToList                (                )        );*/
   }
   //attributes
   private final String instagramUser;    private final String tumblrUser;    private final String userTags;    private final List<String> currentImages;
   //static
   public static void main(String[] args) throws IOException    {        Executors.newScheduledThreadPool(0).scheduleWithFixedDelay        (            new Runnable()            {                List<InstagramReplicator> replicators = Lists.newArrayList                (                    InstagramReplicator.newInstance("willaaaahh", "willaaaahhh", "willa holland"),                    InstagramReplicator.newInstance("emmaroberts", "emmaroberts9", "emma roberts"),                    InstagramReplicator.newInstance("tfarm7", "tfarm11", "taissa farmiga"),                    InstagramReplicator.newInstance("taylorswift", "taylorswift26", "taylor swift,taylorswift13"),                    InstagramReplicator.newInstance("yelyahwilliams", "yelyahwilliams-instagram", "hayley williams"),
                   InstagramReplicator.newInstance("MileyCyrus", "mileycyrus-instagram", "miley cyrus"),                    //InstagramReplicator.newInstance("badgalriri", "badgalriri-instagram", "rihanna"),                    InstagramReplicator.newInstance("beyonce", "beyonce-instagram", "beyonce knowles"),                    InstagramReplicator.newInstance("caradelevingne", "caradelevingne-instagram", "cara delevingne"),                    InstagramReplicator.newInstance("nickiminaj", "nickiminaj-instagram", "nicki minaj"),                    InstagramReplicator.newInstance("emmyrossum", "emmyrossum-instagram", "emmy rossum"),                    InstagramReplicator.newInstance("tigersjaw", "tigersjaw-instagram", "tigers jaw,brianna collins"),                    InstagramReplicator.newInstance("tayjardine", "tayjardine-instagram", "tay jardine,taylor jardine,we are the in crowd"),                    InstagramReplicator.newInstance("lordemusic", "lordemusic-instagram", "lorde")                );
               Iterator<InstagramReplicator> replicatorIterator = replicators.iterator();
               @Override                public void run()                {                    if(!replicatorIterator.hasNext())                    {                        replicatorIterator = replicators.iterator();                    }
                   InstagramReplicator replicator = replicatorIterator.next();
                   try                    {                        replicator.doUpdate();                    }                    catch (Throwable e)                    {                        e.printStackTrace();                    }                }            },            0,            5,            TimeUnit.SECONDS        );    } private static int consecutiveTumblrErrors = 0; private static final String tumblrCookie = ""; }
19 notes · View notes
jesusninoc · 7 years ago
Text
Compilar y ejecutar una clase de Java que ejecuta un cmdlet de PowerShell utilizando Runtime
Compilar y ejecutar una clase de Java que ejecuta un cmdlet de PowerShell utilizando Runtime
Tumblr media
Clase de Java que ejecuta PowerShell (la clase tiene que ser compilada) import java.io.IOException; import java.util.concurrent.TimeUnit; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class EjecutarPowerShell { public static void main(String[] args) throws InterruptedException { Runtime runtime = Runtime.getRuntime(); try { Process process =…
View On WordPress
0 notes
mamoranlcanhapl4 · 4 years ago
Text
Path tracking code
Find the skeleton and the pantograph codes below:
SKELETON
/** ********************************************************************************************************************** * @file       sketch_2_Hello_Wall.pde * @author     Steve Ding, Colin Gallacher, Antoine Weill--Duflos * @version    V1.0.0 * @date       09-February-2021 * @brief      PID example with random position of a target ********************************************************************************************************************** * @attention * * ********************************************************************************************************************** */
 /* library imports *****************************************************************************************************/ import processing.serial.*; import static java.util.concurrent.TimeUnit.*; import java.util.concurrent.*; import controlP5.*; /* end library imports *************************************************************************************************/  
/* scheduler definition ************************************************************************************************/ private final ScheduledExecutorService scheduler      = Executors.newScheduledThreadPool(1); /* end scheduler definition ********************************************************************************************/
ControlP5 cp5;
/* device block definitions ********************************************************************************************/ Board             haplyBoard; Device            widgetOne; Mechanisms        pantograph;
byte              widgetOneID                         = 5; int               CW                                  = 0; int               CCW                                 = 1; boolean           renderingForce                     = false; /* end device block definition *****************************************************************************************/
/* framerate definition ************************************************************************************************/ long              baseFrameRate                       = 120; /* end framerate definition ********************************************************************************************/
/* elements definition *************************************************************************************************/
/* Screen and world setup parameters */ float             pixelsPerMeter                      = 4000.0; float             radsPerDegree                       = 0.01745;
/* pantagraph link parameters in meters */ float             l                                   = 0.07; float             L                                   = 0.09;
/* end effector radius in meters */ float             rEE                                 = 0.006;
/* generic data for a 2DOF device */ /* joint space */ PVector           angles                              = new PVector(0, 0); PVector           torques                             = new PVector(0, 0); PVector           oldangles                           = new PVector(0, 0); PVector           diff                                = new PVector(0, 0);
/* task space */ PVector           posEE                               = new PVector(0, 0); PVector           fEE                                 = new PVector(0, 0);
/* device graphical position */ PVector           deviceOrigin                        = new PVector(0, 0);
/* World boundaries reference */ final int         worldPixelWidth                     = 1000; final int         worldPixelHeight                    = 650;
float x_m,y_m;
// used to compute the time difference between two loops for differentiation long oldtime = 0; // for changing update rate int iter = 0;
/// PID stuff
float P = 0.0; // for I float I = 0; float cumerrorx = 0; float cumerrory = 0; // for D float oldex = 0.0f; float oldey = 0.0f; float D = 0;
//for exponential filter on differentiation float diffx = 0; float diffy = 0; float buffx = 0; float buffy = 0; float smoothing = 0.80;
float xr = 0; float yr = 0; float xO = 0; float yO = 0; int last = 0; int m = 0   ;
// checking everything run in less than 1ms long timetaken= 0;
// set loop time in usec (note from Antoine, 500 is about the limit of my computer max CPU usage) int looptime = 500;
/* graphical elements */ PShape pGraph, joint, endEffector; PShape wall; PShape target; PFont f; /* end elements definition *********************************************************************************************/
/* setup section *******************************************************************************************************/ void setup(){  /* put setup code here, run once: */
 /* screen size definition */  size(1000, 700);
 /* GUI setup */    smooth();  cp5 = new ControlP5(this);  cp5.addTextlabel("Prop")                    .setText("Gain for P(roportional)")                    .setPosition(0,0)                    .setColorValue(color(255,0,0))                    .setFont(createFont("Georgia",20))                    ;  cp5.addKnob("P")               .setRange(0,2)               .setValue(0)               .setPosition(50,25)               .setRadius(50)               .setDragDirection(Knob.VERTICAL)               ;  cp5.addTextlabel("Int")                    .setText("Gain for I(ntegral)")                    .setPosition(0,125)                    .setColorValue(color(255,0,0))                    .setFont(createFont("Georgia",20))                    ;  cp5.addKnob("I")               .setRange(0,2)               .setValue(0)               .setPosition(50,150)               .setRadius(50)               .setDragDirection(Knob.VERTICAL)               ;  cp5.addTextlabel("Deriv")                    .setText("Gain for D(erivative)")                    .setPosition(0,250)                    .setColorValue(color(255,0,0))                    .setFont(createFont("Georgia",20))                    ;  cp5.addKnob("D")               .setRange(0,4)               .setValue(0)               .setPosition(50,275)               .setRadius(50)               .setDragDirection(Knob.VERTICAL)               ;  cp5.addTextlabel("Deriv filt")                    .setText("Exponential filter for Diff")                    .setPosition(0,375)                    .setColorValue(color(255,0,0))                    .setFont(createFont("Georgia",20))                    ;    cp5.addSlider("smoothing")     .setPosition(10,400)     .setSize(200,20)     .setRange(0,1)     .setValue(0.8)     ;  cp5.addTextlabel("Loop time")                    .setText("Loop time")                    .setPosition(0,420)                    .setColorValue(color(255,0,0))                    .setFont(createFont("Georgia",20))                    ;    cp5.addSlider("looptime")     .setPosition(10,450)     .setWidth(200)     .setRange(250,4000) // values can range from big to small as well     .setValue(500)     .setNumberOfTickMarks(16)     .setSliderMode(Slider.FLEXIBLE)     ;  cp5.addButton("RandomPosition")     .setValue(0)     .setPosition(10,500)     .setSize(200,50)     ;  cp5.addButton("ResetIntegrator")     .setValue(0)     .setPosition(10,560)     .setSize(200,50)     ;  cp5.addButton("ResetDevice")     .setValue(0)     .setPosition(10,620)     .setSize(200,50)     ;
 /* device setup */
 /**     * The board declaration needs to be changed depending on which USB serial port the Haply board is connected.   * In the base example, a connection is setup to the first detected serial device, this parameter can be changed   * to explicitly state the serial port will look like the following for different OS:   *   *      windows:      haplyBoard = new Board(this, "COM10", 0);   *      linux:        haplyBoard = new Board(this, "/dev/ttyUSB0", 0);   *      mac:          haplyBoard = new Board(this, "/dev/cu.usbmodem1411", 0);   */  haplyBoard          = new Board(this, "COM3", 0);  widgetOne           = new Device(widgetOneID, haplyBoard);  pantograph          = new Pantograph();
 widgetOne.set_mechanism(pantograph);
 widgetOne.add_actuator(1, CCW, 2);  widgetOne.add_actuator(2, CW, 1);
 widgetOne.add_encoder(1, CCW, 241, 10752, 2);  widgetOne.add_encoder(2, CW, -61, 10752, 1);
 widgetOne.device_set_parameters();
 /* visual elements setup */  background(0);  deviceOrigin.add(worldPixelWidth/2, 0);
 /* create pantagraph graphics */  create_pantagraph();
 target = createShape(ELLIPSE, 0,0, 20, 20);  target.setStroke(color(0));
 /* setup framerate speed */  frameRate(baseFrameRate);    f = createFont("Arial",16,true); // STEP 2 Create Font
 /* setup simulation thread to run at 1kHz */  thread("SimulationThread"); } /* end setup section ***************************************************************************************************/
public void RandomPosition(int theValue) {
   xO = random(-0.3,0.3);    yO = random(-0.3,0.3);
} public void ResetIntegrator(int theValue) {    cumerrorx= 0;    cumerrory= 0; } public void ResetDevice(int theValue) {    widgetOne.device_set_parameters();
}
/* Keyboard inputs *****************************************************************************************************/
/// Antoine: this is specific to qwerty keyboard layout, you may want to adapt
void keyPressed() {  if (key == 'q') {    P += 0.005;  } else if (key == 'a') {    P -= 0.005;  }  else if (key == 'w') {    I += 0.00001;  }  else if (key == 's') {    I -= 0.00001;  }  else if (key == 'e') {    D += 0.1;  }  else if (key == 'd') {    D -= 0.1;  }  else if (key == 'r') {    looptime += 100;  }  else if (key == 'f') {    looptime -= 100;  }    else if (key == 't') {    smoothing += 0.01;  }  else if (key == 'g') {    smoothing -= 0.01;  }  else if (key == ' ') {    cumerrorx= 0;    cumerrory= 0;  }  else if (key == 'i') {    widgetOne.device_set_parameters();  }  else if (key == 'b') {    xr = random(-0.5,0.5);    yr = random(-0.5,0.5);  } }
/* draw section ********************************************************************************************************/ void draw(){  /* put graphical code here, runs repeatedly at defined framerate in setup, else default at 60fps: */  if(renderingForce == false){    background(255);    update_animation(angles.x*radsPerDegree, angles.y*radsPerDegree, posEE.x, posEE.y);
 } } /* end draw section ****************************************************************************************************/
int noforce = 0; long timetook = 0; long looptiming = 0;
/* simulation section **************************************************************************************************/ public void SimulationThread(){ while(1==1) {    long starttime = System.nanoTime();    long timesincelastloop=starttime-timetaken;    iter+= 1;    // we check the loop is running at the desired speed (with 10% tolerance)    if(timesincelastloop >= looptime*1000*1.1) {      float freq = 1.0/timesincelastloop*1000000.0;        println("caution, freq droped to: "+freq + " kHz");    }    else if(iter >= 1000) {      float freq = 1000.0/(starttime-looptiming)*1000000.0;       println("loop running at "  + freq + " kHz");       iter=0;       looptiming=starttime;    }
   timetaken=starttime;
   renderingForce = true;
   if(haplyBoard.data_available()){      /* GET END-EFFECTOR STATE (TASK SPACE) */      widgetOne.device_read_data();
     noforce = 0;      angles.set(widgetOne.get_device_angles());
     posEE.set(widgetOne.get_device_position(angles.array()));
     posEE.set(device_to_graphics(posEE));
     //m = (millis()-last);      //  if(millis() > last+20000){      //  last = millis();      //}
     //if (m <= 2000){      //  xr = xO ;      //  yr = yO ;      //}
     //if (m > 2000 & m <= 8000){      //  xr = xr + 0.0001 ;      //  yr = yr          ;      //}
     //if (m > 8000 & m <= 11000){      //  xr = xr          ;      //  yr = yr - 0.00012;      //}
     //if (m > 11000 & m <= 17000){      //  xr = xr - 0.0001 ;      //  yr = yr          ;      //}
     //if (m > 17000){      //  xr = xr          ;      //  yr = yr + 0.00012;      //}
     x_m = xO*300    ;      y_m = yO*300+350;
// Torques from difference in endeffector and setpoint, set gain, calculate force      float xE = pixelsPerMeter * posEE.x;      float yE = pixelsPerMeter * posEE.y;      long timedif = System.nanoTime()-oldtime;
     float dist_X = x_m-xE;      cumerrorx += dist_X*timedif*0.000000001;      float dist_Y = y_m-yE;      cumerrory += dist_Y*timedif*0.000000001;      //println(dist_Y*k + " " +dist_Y*k);      // println(timedif);      if(timedif > 0) {        buffx = (dist_X-oldex)/timedif*1000*1000;        buffy = (dist_Y-oldey)/timedif*1000*1000;            
       diffx = smoothing*diffx + (1.0-smoothing)*buffx;        diffy = smoothing*diffy + (1.0-smoothing)*buffy;        oldex = dist_X;        oldey = dist_Y;        oldtime=System.nanoTime();      }
   // Forces are constrained to avoid moving too fast
     fEE.x = constrain(P*dist_X,-4,4) + constrain(I*cumerrorx,-4,4) + constrain(D*diffx,-8,8);
     fEE.y = constrain(P*dist_Y,-4,4) + constrain(I*cumerrory,-4,4) + constrain(D*diffy,-8,8);
     if(noforce==1)      {        fEE.x=0.0;        fEE.y=0.0;      }    widgetOne.set_device_torques(graphics_to_device(fEE).array());    //println(f_y);      /* end haptic wall force calculation */
   }
   widgetOne.device_write_torques();
   renderingForce = false;    long timetook=System.nanoTime()-timetaken;    if(timetook >= 1000000) {    println("Caution, process loop took: " + timetook/1000000.0 + "ms");    }    else {      while(System.nanoTime()-starttime < looptime*1000) {      //println("Waiting");      }    }
 } }
/* end simulation section **********************************************************************************************/
/* helper functions section, place helper functions here ***************************************************************/ void create_pantagraph(){  float lAni = pixelsPerMeter * l;  float LAni = pixelsPerMeter * L;  float rEEAni = pixelsPerMeter * rEE;
 pGraph = createShape();  pGraph.beginShape();  pGraph.fill(255);  pGraph.stroke(0);  pGraph.strokeWeight(2);
 pGraph.vertex(deviceOrigin.x, deviceOrigin.y);  pGraph.vertex(deviceOrigin.x, deviceOrigin.y);  pGraph.vertex(deviceOrigin.x, deviceOrigin.y);  pGraph.vertex(deviceOrigin.x, deviceOrigin.y);  pGraph.endShape(CLOSE);
 joint = createShape(ELLIPSE, deviceOrigin.x, deviceOrigin.y, rEEAni, rEEAni);  joint.setStroke(color(0));
 endEffector = createShape(ELLIPSE, deviceOrigin.x, deviceOrigin.y, 2*rEEAni, 2*rEEAni);  endEffector.setStroke(color(0,0,255));  strokeWeight(5);
}
PShape create_wall(float x1, float y1, float x2, float y2){  x1 = pixelsPerMeter * x1;  y1 = pixelsPerMeter * y1;  x2 = pixelsPerMeter * x2;  y2 = pixelsPerMeter * y2;
 return createShape(LINE, deviceOrigin.x + x1, deviceOrigin.y + y1, deviceOrigin.x + x2, deviceOrigin.y+y2); }
void update_animation(float th1, float th2, float xE, float yE){  background(255);    pushMatrix();  float lAni = pixelsPerMeter * l;  float LAni = pixelsPerMeter * L;
 xE = pixelsPerMeter * xE;  yE = pixelsPerMeter * yE;
 th1 = 3.14 - th1;  th2 = 3.14 - th2;
 pGraph.setVertex(1, deviceOrigin.x + lAni*cos(th1), deviceOrigin.y + lAni*sin(th1));  pGraph.setVertex(3, deviceOrigin.x + lAni*cos(th2), deviceOrigin.y + lAni*sin(th2));  pGraph.setVertex(2, deviceOrigin.x + xE, deviceOrigin.y + yE);
 shape(pGraph);  shape(joint);  float[] coord;
 translate(xE, yE);  shape(endEffector);  popMatrix();  arrow(xE,yE,fEE.x,fEE.y);  textFont(f,16);                  // STEP 3 Specify font to be used  fill(0);                         // STEP 4 Specify font color
 x_m = xO*300+500;  y_m = yO*300+350;//mouseY;  pushMatrix();  translate(x_m, y_m);  shape(target);  popMatrix();
}
PVector device_to_graphics(PVector deviceFrame){  return deviceFrame.set(-deviceFrame.x, deviceFrame.y); }
PVector graphics_to_device(PVector graphicsFrame){  return graphicsFrame.set(-graphicsFrame.x, graphicsFrame.y); }
void arrow(float x1, float y1, float x2, float y2) {  x2=x2*10.0;  y2=y2*10.0;  x1=x1+500;  x2=-x2+x1;  y2=y2+y1;
 line(x1, y1, x2, y2);  pushMatrix();  translate(x2, y2);  float a = atan2(x1-x2, y2-y1);  rotate(a);  line(0, 0, -10, -10);  line(0, 0, 10, -10);  popMatrix(); }
/* end helper functions section ****************************************************************************************/
PANTOGRAPH
/** ********************************************************************************************************************** * @file       Pantograph.java * @author     Steve Ding, Colin Gallacher * @version    V3.0.0 * @date       15-January-2021 * @brief      Mechanism extension example ********************************************************************************************************************** * @attention * * ********************************************************************************************************************** */
import static java.lang.Math.*;
public class Pantograph extends Mechanisms{
private float l, L, d; private float th1, th2; private float tau1, tau2; private float f_x, f_y; private float x_E, y_E; private float pi = 3.14159265359f; private float JT11, JT12, JT21, JT22; private float gain = 1.0f;
public Pantograph(){    this.l = 0.07f;    this.L = 0.09f;    this.d = 0.0f;  } public void torqueCalculation(float[] force){ f_x = force[0]; f_y = force[1];
   tau1 = JT11*f_x + JT12*f_y; tau2 = JT21*f_x + JT22*f_y; tau1 = tau1*gain; tau2 = tau2*gain;  }  public void forwardKinematics(float[] angles){      float l1 = l;    float l2 = l;    float L1 = L;    float L2 = L;
   th1 = pi/180*angles[0];    th2 = pi/180*angles[1];
   // Forward Kinematics    float c1 = (float)cos(th1);    float c2 = (float)cos(th2);    float s1 = (float)sin(th1);    float s2 = (float)sin(th2);    float xA = l1*c1;    float yA = l1*s1;    float xB = d+l2*c2;
   float yB = l2*s2;    float hx = xB-xA;    float hy = yB-yA;    float hh = (float) pow(hx,2) + (float) pow(hy,2);    float hm = (float)sqrt(hh);    float cB = - ((float) pow(L2,2) - (float) pow(L1,2) - hh) / (2*L1*hm);
   float h1x = L1*cB * hx/hm;    float h1y = L1*cB * hy/hm;    float h1h1 = (float) pow(h1x,2) + (float) pow(h1y,2);    float h1m = (float) sqrt(h1h1);    float sB = (float) sqrt(1-pow(cB,2));  
   float lx = -L1*sB*h1y/h1m;    float ly = L1*sB*h1x/h1m;
   float x_P = xA + h1x + lx;    float y_P = yA + h1y + ly;
   float phi1 = (float)acos((x_P-l1*c1)/L1);    float phi2 = (float)acos((x_P-d-l2*c2)/L2);
   float c11 = (float) cos(phi1);    float s11 =(float) sin(phi1);    float c22= (float) cos(phi2);    float s22 = (float) sin(phi2);
   float dn = L1 *(c11 * s22 - c22 * s11);    float eta = (-L1 * c11 * s22 + L1 * c22 * s11 - c1 * l1 * s22 + c22 * l1 * s1)  / dn;    float nu = l2 * (c2 * s22 - c22 * s2)/dn;
   JT11 = -L1 * eta * s11 - L1 * s11 - l1 * s1;    JT12 = L1 * c11 * eta + L1 * c11 + c1 * l1;    JT21 = -L1 * s11 * nu;    JT22 = L1 * c11 * nu;
   x_E = x_P;    y_E = y_P;      } public void forceCalculation(){ } public void positionControl(){ } public void inverseKinematics(){ } public void set_mechanism_parameters(float[] parameters){ this.l = parameters[0]; this.L = parameters[1]; this.d = parameters[2]; } public void set_sensor_data(float[] data){ } public float[] get_coordinate(){ float temp[] = {x_E, y_E}; return temp; } public float[] get_torque(){ float temp[] = {tau1, tau2}; return temp; } public float[] get_angle(){ float temp[] = {th1, th2}; return temp; }
}
0 notes
jacob-cs · 8 years ago
Text
android에서 작업 delay하는 방법
일정 작업의 delay하는 방법
https://stackoverflow.com/a/24104427/3151712
If you want to pause then use java.util.concurrent.TimeUnit:
TimeUnit.SECONDS.sleep(1);
To sleep for one second or
TimeUnit.MINUTES.sleep(1);
To sleep for a minute.
https://stackoverflow.com/a/14168900/3151712
try { Thread.sleep(5 * 1000); }catch(InterruptedException ie) { //Log message if required. }
https://stackoverflow.com/a/38524606/3151712
new CountDownTimer(6000, 1000) {            public void onFinish() {               mProgressDialog.dismiss();              // my whole code            }            public void onTick(long millisUntilFinished) {                mProgressDialog.show();            }        }.start();
0 notes
codippa · 5 years ago
Text
Convert nanoseconds to seconds
This article will explain different ways in which nanoseconds or nanotime can be converted into seconds in java. Method 1: Using TimeUnit.convert java.util.concurrent.TimeUnit is an enum in java that contains values representing different time units such as HOURS, MINUTES, SECONDS, MILLISECONDS, NANOSECONDS etc. TimeUnit is used to convert values between different time units. Its convert() method can be used to convert a duration in nanoseconds to seconds. convert() takes 2 arguments A. Duration to be converted. B. Unit of this duration. In this case, it will be nanoseconds Example, long timeInNanoSeconds = 1000000000; long seconds = TimeUnit.SECONDS. convert(timeInNanoSeconds, TimeUnit.NANOSECONDS); System.out.println(timeInNanoSeconds + " in seconds is " + convert); Note that the target time unit is the enum value on which convert() is called. In this case, it is SECONDS. Above example prints 1000000000 in seconds is 1 Method 2: Using TimeUnit.convert TimeUnit enum has an overloaded convert() method that takes a single argument of type java.time.Duration. Duration object can be created using its static method ofNanos which takes a long value as argument, which is the time interval or the value to be converted to nanoseconds. ofNanos() returns a Duration object representing the number of nanoseconds provided to it as argument. Example, long timeInNanoSeconds = 1000000000L; // convert nanoseconds to seconds long seconds = TimeUnit.SECONDS.convert( Duration.ofNanos(timeInNanoSeconds)); System.out.println(timeInNanoSeconds + " in seconds is " + seconds); Note that the target unit is the one on which convert() is called. This should be SECONDS if you want to convert to seconds. Output of above example is 1000000000 in seconds is 1 Method 3: Using TimeUnit.toSeconds TimeUnit has a method toSeconds() that takes a single value as argument and converts it to seconds. If you are converting nanoseconds to seconds, then this method should be called on TimeUnit.NANOSECONDS as shown below. long timeInNanoSeconds = System.nanoTime(); // convert to seconds long seconds = TimeUnit.NANOSECONDS. toSeconds(timeInNanoSeconds); System.out.println(timeInNanoSeconds + " in seconds is " + seconds); Output of this example is 611665932118900 in seconds is 611665 Method 4: Division This method is simple mathematics based on following relation between nanoseconds and seconds. 1 Second = 1000000000 Nanosecond which means that 1 Nanosecond = 1/1000000000 Second So, in order to convert nanoseconds to second, divide it by 1000000000 as shown in the below example. // store start time long startTime = System.nanoTime(); // halt for 10 seconds Thread.sleep(10000); //��store end time long endTime = System.nanoTime(); // get difference long duration = endTime - startTime; // convert to nanoseconds double seconds = (double)duration/1000000000; System.out.println(duration + " in seconds is " + seconds); Above example calculates two different times in nanoseconds using System.nanoTime(), calculates the difference between them and then converts it into seconds by dividing with 100000000. Note that a delay is injected by sleeping the current thread. In actual environment, this might represent a time consuming task. Above program prints 5001456700 in seconds is 5.0014567 With this method, you can also calculate the time interval taken to perform a task. Do not forget to hit the clap if the article was useful. Read the full article
0 notes
jeeteshsurana · 6 years ago
Link
Http ApiClient Caching in Android
import android.content.Context
import android.util.Log
import com.commonlibs.util.helper.NetworkManager
import com.google.gson.Gson
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import okhttp3.Cache
import okhttp3.CacheControl
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit
/**
 * Api Client for retrofit Instance with Base Url
 */
class APIClient {
    private var mRetrofit: Retrofit? = null
    private val TAG = "RetrofitManager"
    private val mHeaderCacheControl = "Cache-Control"
    private val mHeaderPragma = "Pragma"
    private var mCache: Cache? = null
    private var mOkHttpClient: OkHttpClient? = null
    /**
     * getClient Retorfit instance
     * @param mContext use for store caching
     * @param mAPI  search for base url
     */
    fun getClient(mContext: Context, mAPI: Int): Retrofit {
        if (mRetrofit == null) {
            val interceptor = HttpLoggingInterceptor()
            interceptor.level = HttpLoggingInterceptor.Level.BODY
            mRetrofit = Retrofit.Builder()
                .baseUrl(apiUrl(mAPI))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(getOkHttpClient(mContext))
                .build()
        }
        return mRetrofit!!
    }
    /**
     * Api url use to choose ase url
     * @param selectUrl send number and get base url like 0-> 8800
     */
    private fun apiUrl(selectUrl: Int): String {
        return when (selectUrl) {
            0 -> Constants.authURL
            1 -> Constants.inventoryURL
            2 -> Constants.merchantURL
            3 -> Constants.customerURL
            4 -> Constants.paymentURL
            5 -> Constants.notificationURL
            6 -> Constants.auctionURL
            7 -> Constants.storeURL
            8 -> Constants.shippingURL
            else -> Constants.authURL
        }
    }
    /**
     * getOkHttpClient
     * @param mContext use for store caches
     */
    private fun getOkHttpClient(mContext: Context): OkHttpClient {
        val cacheSize = 10 * 1024 * 1024 // 10 MB
        val httpCacheDirectory = File(mContext.cacheDir, Constants.httpCacheDirectory)
        val cache = Cache(httpCacheDirectory, cacheSize.toLong())
        val networkCacheInterceptor = Interceptor { chain ->
            val response = chain.proceed(chain.request())
            val cacheControl = CacheControl.Builder()
                .maxAge(2, TimeUnit.HOURS)
                .build()
            response.newBuilder()
                .header(Constants.cacheControl, cacheControl.toString())
                .build()
        }
        val loggingInterceptor = HttpLoggingInterceptor()
        loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
        return OkHttpClient.Builder()
            .connectTimeout(3, TimeUnit.MINUTES)
            .readTimeout(90, TimeUnit.SECONDS)
            .writeTimeout(45, TimeUnit.SECONDS)
            .addInterceptor(loggingInterceptor)
            .cache(cache)
            .addNetworkInterceptor(networkCacheInterceptor)
            .build()
    }
    /**
     * this client use for User Access APIs
     */
    val client: Retrofit
        get() {
            if (mRetrofit == null) {
                val loggingInterceptor = HttpLoggingInterceptor()
                loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
                val okHttpClient = OkHttpClient.Builder()
                    .addInterceptor(loggingInterceptor)
                    .addInterceptor(BasicAuthInterceptor(Constants.authHeaderUserName, Constants.authHeaderPassword))
                    .connectTimeout(Constants.http_timeout.toLong(), TimeUnit.SECONDS)
                    .connectTimeout(3, TimeUnit.MINUTES)
                    .readTimeout(90, TimeUnit.SECONDS)
                    .writeTimeout(45, TimeUnit.SECONDS)
                    .build()
                mRetrofit = retrofit2.Retrofit.Builder()
                    .baseUrl(Constants.authURL)
                    .client(okHttpClient)
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build()
            }
            return mRetrofit!!
        }
    fun getRetrofitCache(mContext : Context, mAPI: Int): Retrofit {
        if (mRetrofit == null) {
            val httpClient = OkHttpClient.Builder()
                .addInterceptor(provideOfflineCacheInterceptor(mContext))
                .addNetworkInterceptor(provideCacheInterceptor(mContext))
                .cache(provideCache(mContext))
            mOkHttpClient = httpClient.build()
            mRetrofit = Retrofit.Builder()
                .baseUrl(apiUrl(mAPI))
                .addConverterFactory(GsonConverterFactory.create(Gson()))
                .client(mOkHttpClient!!)
                .build()
        }
        return mRetrofit!!
    }
    //Cache store with size
    private fun provideCache(mContext : Context): Cache? {
        if (mCache == null) {
            try {
                mCache = Cache(
                    File(mContext.cacheDir, "http-cache"),
                    100 * 1024 * 1024) // 10 MB
            } catch (e: Exception) {
                Log.e(TAG, "Could not create Cache!")
            }
        }
        return mCache
    }
    //get the cache and remove particular time
    private fun provideCacheInterceptor(mContext : Context): Interceptor {
        return Interceptor { chain ->
            val response = chain.proceed(chain.request())
            val cacheControl: CacheControl = if (NetworkManager(mContext).checkInternetConnection()) {
                CacheControl.Builder()
                    .maxAge(0, TimeUnit.SECONDS)
                    .build()
            } else {
                CacheControl.Builder()
                    .maxStale(7, TimeUnit.DAYS)
                    .build()
            }
            response.newBuilder()
                .removeHeader(mHeaderPragma)
                .removeHeader(mHeaderCacheControl)
                .header(mHeaderCacheControl, cacheControl.toString())
                .build()
        }
    }
    //getting the caches if internet are not available
    private fun provideOfflineCacheInterceptor(mContext: Context): Interceptor {
        return Interceptor { chain ->
            var request = chain.request()
            if (!NetworkManager(mContext).checkInternetConnection()) {
                val cacheControl = CacheControl.Builder()
                    .maxStale(7, TimeUnit.DAYS)
                    .build()
                request = request.newBuilder()
                    .removeHeader(mHeaderPragma)
                    .removeHeader(mHeaderCacheControl)
                    .cacheControl(cacheControl)
                    .build()
            }
            chain.proceed(request)
        }
    }
}
//String.xml
    <!--Common String-->
    <string name="AppTag">TAG</string>
    <!--Message-->
    <string name="msg_cache">Could not create Cache!</string>
    <!--constant-->
    <string name="cons_http">http-cache</string>
//Constant.kt
open class Constants {
    companion object {
       var authURL: String = "your_url"
        var inventoryURL: String = "your_url"
        var merchantURL: String = "your_url"
        var customerURL: String = "your_url"
        var paymentURL: String = "your_url"
        var notificationURL: String = "your_url"
        var auctionURL: String = "your_url"
        var storeURL: String = "your_url"
        var shippingURL: String = "your_url"
    }
}
//NetworkManager.kt
import android.content.Context
import android.net.ConnectivityManager
class NetworkManager constructor(mContext: Context?) {
    var mContext: Context? = null
    init {
        this.mContext = mContext!!
    }
    /* class for checking Internet connectivity */
    fun checkInternetConnection(): Boolean {
        if (mContext == null) return false
        var con_manager: ConnectivityManager =
            mContext!!.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        return con_manager .activeNetworkInfo != null && con_manager.activeNetworkInfo.isConnected
    }
}
//how to Applied 
 private val apiServicesCache = APIClient().getRetrofitCache(mBaseActivity, 1).create(RetrofitInterface::class.java)!!
/**
     * Get Product Full Detail
     * @param id product id
     */
    fun getProductFullDetail(id: String): LiveData<ProductFullDetail> {
        Log.d("TAG", "Similar Product id=$id")
                 val call = apiServicesCache.getProductFullDetails(id)
        call.enqueue(object : Callback<ProductFullDetail> {
            override fun onResponse(call: Call<ProductFullDetail>, response: Response<ProductFullDetail>) {
                if (response.isSuccessful) {
                    mProductFullDetail.value = response.body()
                }else {
                    mBaseActivity.showApiError(response.code().toString())
                }
            }
            override fun onFailure(call: Call<ProductFullDetail>, t: Throwable) {
                mBaseActivity.showApiError(t.message.toString())
            }
        })
        return this.mProductFullDetail
    }
//RetrofitInterface.kt
interface RetrofitInterface {
 @GET("products/{id}")
    fun getProductFullDetails(@Path("id") id: String): Call<ProductFullDetail>
}
0 notes
skptricks · 7 years ago
Text
Convert Milliseconds into Days, Hours, Minutes, Seconds in Java
Sometimes we need to convert the milliseconds into days or hours or minutes or seconds, so in this post we will see how to convert milliseconds into days, hours, minutes, seconds in Java.
Basically when you want to check the exact time taken to execute a program then you may need to calculate the time. So in this case you get the start time in milliseconds and end time in milliseconds and you want to check how much time that program took to execute. Therefore you would like to convert the milliseconds into minutes and seconds to make it more readable format because millisecond unit may not be so understandable quickly.
Lets see the below example, it will provide you better idea to convert the milliseconds into days or hours or minutes or seconds.
import java.util.concurrent.TimeUnit; public class MillisToDayHrMinSec { public static void main(String[] args) { final long milliseconds = 5478965412358l; final long day = TimeUnit.MILLISECONDS.toDays(milliseconds); final long hours = TimeUnit.MILLISECONDS.toHours(milliseconds) - TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(milliseconds)); final long minutes = TimeUnit.MILLISECONDS.toMinutes(milliseconds) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(milliseconds)); final long seconds = TimeUnit.MILLISECONDS.toSeconds(milliseconds) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(milliseconds)); final long ms = TimeUnit.MILLISECONDS.toMillis(milliseconds) - TimeUnit.SECONDS.toMillis(TimeUnit.MILLISECONDS.toSeconds(milliseconds)); System.out.println("milliseconds :-" + milliseconds); System.out.println(String.format("%d Days %d Hours %d Minutes %d Seconds %d Milliseconds", day, hours, minutes, seconds, ms)); } }
Output : -------------------- milliseconds :-5478965412358 63413 Days 22 Hours 50 Minutes 12 Seconds 358 Milliseconds
Hope you like this simple example for time conversion, where we are converting milliseconds into days or hours or minutes or seconds. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.
via Blogger https://ift.tt/2NgsvLa
0 notes
dev-arktks · 8 years ago
Text
Spring Bootで作ったAPIのレスポンスタイムやコール回数、JVMのスレッド数やヒープメモリをMackerelのカスタ���ダッシュボードに表示させてみた
早速、今のmackerel のカスタムダッシュボード載せてみる
Tumblr media
※ グラフはそれぞれ 1時間 / 1日 / 1週間 の集計のものを表示 ※ リリース前なのでデータが少ない
前提
Java8 / Spring Boot1.5 / Gradle3.3 / Actuator を利用
Mackerel は Standard プランにアップグレード
Free プランではカスタムダッシュボード使えない、サービスメトリック数は5まで
Standard プランはサービスメトリック数は200まで
参考サイト
http://qiita.com/kawasima/items/b203f789d8b6bb23a575
https://github.com/kawasima/metrics-mackerel
https://mackerel.io/ja/docs/entry/howto/dashboard
背景
mackerelの導入は簡単だけど、JVMのメトリクスを取得できない
mackerel-plugin-jvm使うとヒープ使用状況とGCの頻��は取得できるがスレッド数は取得できない
APIのレスポンスタイムを取得してどのAPIが遅いのか把握したい
できればグラフ化してすぐ分かるように
上記を監視目的で導入しているmackerel内で完結させたい
手順
actuator の導入
actuatorを使うとシステムの状態やメトリクスを確認することができる。 導入するには Gradle なら build.gradle に下記を追記するだけ
dependencies { compile("org.springframework.boot:spring-boot-starter-actuator") }
actuator で他に何ができるかは下記を参照 https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html
今回は /metrics にアクセスした際に取得できるパラメータを mackerel で表示させてみる
https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-metrics.html
※ 背景で挙げた項目が取得できる他、各API のコール回数も取得できる模様
metrics-mackerel の導入
actuator の /metrics で取得できるメトリクスを mackerel に送ることができるプラグイン。ありがたや build.gradle に下記を追記して、
dependencies { compile('net.unit8.metrics:metrics-mackerel:0.1.1') }
Config 用のクラスを作成して完了
package com.xxx.config; import com.codahale.metrics.Gauge; import com.codahale.metrics.MetricRegistry; import com.xxx.model.enums.Env; import net.unit8.metrics.mackerel.MackerelReporter; import net.unit8.metrics.mackerel.MackerelSender; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.actuate.endpoint.SystemPublicMetrics; import org.springframework.boot.actuate.metrics.Metric; import org.springframework.context.annotation.Configuration; import javax.annotation.PostConstruct; import java.util.concurrent.TimeUnit; @Configuration public class MackerelConfig { @Autowired private MetricRegistry registry; @Autowired private SystemPublicMetrics systemPublicMetrics; @Value("${mackerel.apiKey}") private String apiKey; @Value("${mackerel.serviceName}") private String serviceName; @Value("${common.env}") private String env; @PostConstruct public void initialize() { // 本番環境だけメトリクスを取得 if (!Env.isLive(this.env)) { return; } for (final Metric> metric : this.systemPublicMetrics.metrics()) { final Gauge metricGauge = () -> metric.getValue().longValue(); String name = metric.getName(); if (!name.contains(".")) { name += ".total"; } this.registry.register(name, metricGauge); } final MackerelSender sender = new MackerelSender(this.serviceName, this.apiKey); final MackerelReporter reporter = MackerelReporter .forRegistry(this.registry) .build(sender); reporter.start(1, TimeUnit.MINUTES); } public void setApiKey(final String apiKey) { this.apiKey = apiKey; } public void setServiceName(final String serviceName) { this.serviceName = serviceName; } }
※ 事前に application.yml に mackerel のapiKeyとserviceNameを定義しておくこと
これだけで、mackerel の Services -> サービスメトリック にグラフが出ます
Tumblr media
mackerel でカスタムダッシュボードを作成
ここまでで目的のグラフは表示されるようになったが、 そんなに見たくないグラフもたくさん表示されてしまうので、 必要そうなグラフだけが表示されるカスタムダッシュボードを作成する。
https://mackerel.io/ja/docs/entry/howto/dashboard
グラフの右上にシェアボタンがあるので、そこからiframe タグをコピって、 カスタムダッシュボード作成画面に下記のように貼り付け。
<iframe src="https://mackerel.io/embed/orgs/xxx/services/xxx-live?graph=gauge.response.api.v1.%2a&period=1h" height="200" width="400" frameborder="0"></iframe> <iframe src="https://mackerel.io/embed/orgs/xxx/services/xxx-live?graph=gauge.response.api.v1.%2a&period=1d" height="200" width="400" frameborder="0"></iframe> <iframe src="https://mackerel.io/embed/orgs/xxx/services/xxx-live?graph=gauge.response.api.v1.%2a&period=1w" height="200" width="400" frameborder="0"></iframe>
注意点
actuator のデフォルト設定だと、/metrics の他にシステムの状態が表示された、たくさんのエンドポイントが"/"直下のパスにできてしまう。 https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html 本番ではこれらのパスは一般公開してはならず、ラボからのアクセスのみに制限したいが、 1つ1つ制限するのはめんどうなので、下記を参考にエンドポイントのパスはまとめる
management: contextPath: /manage
https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-monitoring.html
このように設定しておけば、全て /manage/yyy に集約されるのでアクセス制限が楽になる
0 notes
jesusninoc · 7 years ago
Text
Ejecutar el cmdlet Get-NetTCPConnection de PowerShell en Java
Ejecutar el cmdlet Get-NetTCPConnection de PowerShell en Java
import java.io.IOException; import java.util.concurrent.TimeUnit; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ProcesoPowerShell { public static void main(String[] args) throws InterruptedException { Runtime runtime = Runtime.getRuntime(); try { Process process = runtime.exec("powershell.exe Get-NetTCPConnection");…
View On WordPress
0 notes
jesusninoc · 7 years ago
Text
Ejecutar una clase de Java que ejecuta un cmdlet de PowerShell utilizando Runtime
Tumblr media
Clase de Java que ejecuta PowerShell import java.io.IOException; import java.util.concurrent.TimeUnit; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class EjecutarPowerShell { public static void main(String[] args) throws InterruptedException { Runtime runtime = Runtime.getRuntime(); try { Process process = runtime.exec("powershell.exe…
View On WordPress
0 notes
jesusninoc · 7 years ago
Text
Obtener la clave de la red wifi en Java mediante un script de PowerShell en Base64
Tumblr media
import java.io.IOException; import java.util.concurrent.TimeUnit; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ProcesoBase { public static void main(String[] args) throws InterruptedException { Runtime runtime = Runtime.getRuntime(); try { Process process = runtime.exec("powershell.exe -encodedcommand…
View On WordPress
0 notes
jeeteshsurana · 6 years ago
Text
Http ApiClient Caching
http://bit.ly/2OP8MzX
Http ApiClient Caching in Android
import android.content.Context
import android.util.Log
import com.commonlibs.util.helper.NetworkManager
import com.google.gson.Gson
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import okhttp3.Cache
import okhttp3.CacheControl
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit
/**
 * Api Client for retrofit Instance with Base Url
 */
class APIClient {
    private var mRetrofit: Retrofit? = null
    private val TAG = "RetrofitManager"
    private val mHeaderCacheControl = "Cache-Control"
    private val mHeaderPragma = "Pragma"
    private var mCache: Cache? = null
    private var mOkHttpClient: OkHttpClient? = null
    /**
     * getClient Retorfit instance
     * @param mContext use for store caching
     * @param mAPI  search for base url
     */
    fun getClient(mContext: Context, mAPI: Int): Retrofit {
        if (mRetrofit == null) {
            val interceptor = HttpLoggingInterceptor()
            interceptor.level = HttpLoggingInterceptor.Level.BODY
            mRetrofit = Retrofit.Builder()
                .baseUrl(apiUrl(mAPI))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(getOkHttpClient(mContext))
                .build()
        }
        return mRetrofit!!
    }
    /**
     * Api url use to choose ase url
     * @param selectUrl send number and get base url like 0-> 8800
     */
    private fun apiUrl(selectUrl: Int): String {
        return when (selectUrl) {
            0 -> Constants.authURL
            1 -> Constants.inventoryURL
            2 -> Constants.merchantURL
            3 -> Constants.customerURL
            4 -> Constants.paymentURL
            5 -> Constants.notificationURL
            6 -> Constants.auctionURL
            7 -> Constants.storeURL
            8 -> Constants.shippingURL
            else -> Constants.authURL
        }
    }
    /**
     * getOkHttpClient
     * @param mContext use for store caches
     */
    private fun getOkHttpClient(mContext: Context): OkHttpClient {
        val cacheSize = 10 * 1024 * 1024 // 10 MB
        val httpCacheDirectory = File(mContext.cacheDir, Constants.httpCacheDirectory)
        val cache = Cache(httpCacheDirectory, cacheSize.toLong())
        val networkCacheInterceptor = Interceptor { chain ->
            val response = chain.proceed(chain.request())
            val cacheControl = CacheControl.Builder()
                .maxAge(2, TimeUnit.HOURS)
                .build()
            response.newBuilder()
                .header(Constants.cacheControl, cacheControl.toString())
                .build()
        }
        val loggingInterceptor = HttpLoggingInterceptor()
        loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
        return OkHttpClient.Builder()
            .connectTimeout(3, TimeUnit.MINUTES)
            .readTimeout(90, TimeUnit.SECONDS)
            .writeTimeout(45, TimeUnit.SECONDS)
            .addInterceptor(loggingInterceptor)
            .cache(cache)
            .addNetworkInterceptor(networkCacheInterceptor)
            .build()
    }
    /**
     * this client use for User Access APIs
     */
    val client: Retrofit
        get() {
            if (mRetrofit == null) {
                val loggingInterceptor = HttpLoggingInterceptor()
                loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
                val okHttpClient = OkHttpClient.Builder()
                    .addInterceptor(loggingInterceptor)
                    .addInterceptor(BasicAuthInterceptor(Constants.authHeaderUserName, Constants.authHeaderPassword))
                    .connectTimeout(Constants.http_timeout.toLong(), TimeUnit.SECONDS)
                    .connectTimeout(3, TimeUnit.MINUTES)
                    .readTimeout(90, TimeUnit.SECONDS)
                    .writeTimeout(45, TimeUnit.SECONDS)
                    .build()
                mRetrofit = retrofit2.Retrofit.Builder()
                    .baseUrl(Constants.authURL)
                    .client(okHttpClient)
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build()
            }
            return mRetrofit!!
        }
    fun getRetrofitCache(mContext : Context, mAPI: Int): Retrofit {
        if (mRetrofit == null) {
            val httpClient = OkHttpClient.Builder()
                .addInterceptor(provideOfflineCacheInterceptor(mContext))
                .addNetworkInterceptor(provideCacheInterceptor(mContext))
                .cache(provideCache(mContext))
            mOkHttpClient = httpClient.build()
            mRetrofit = Retrofit.Builder()
                .baseUrl(apiUrl(mAPI))
                .addConverterFactory(GsonConverterFactory.create(Gson()))
                .client(mOkHttpClient!!)
                .build()
        }
        return mRetrofit!!
    }
    //Cache store with size
    private fun provideCache(mContext : Context): Cache? {
        if (mCache == null) {
            try {
                mCache = Cache(
                    File(mContext.cacheDir, "http-cache"),
                    100 * 1024 * 1024) // 10 MB
            } catch (e: Exception) {
                Log.e(TAG, "Could not create Cache!")
            }
        }
        return mCache
    }
    //get the cache and remove particular time
    private fun provideCacheInterceptor(mContext : Context): Interceptor {
        return Interceptor { chain ->
            val response = chain.proceed(chain.request())
            val cacheControl: CacheControl = if (NetworkManager(mContext).checkInternetConnection()) {
                CacheControl.Builder()
                    .maxAge(0, TimeUnit.SECONDS)
                    .build()
            } else {
                CacheControl.Builder()
                    .maxStale(7, TimeUnit.DAYS)
                    .build()
            }
            response.newBuilder()
                .removeHeader(mHeaderPragma)
                .removeHeader(mHeaderCacheControl)
                .header(mHeaderCacheControl, cacheControl.toString())
                .build()
        }
    }
    //getting the caches if internet are not available
    private fun provideOfflineCacheInterceptor(mContext: Context): Interceptor {
        return Interceptor { chain ->
            var request = chain.request()
            if (!NetworkManager(mContext).checkInternetConnection()) {
                val cacheControl = CacheControl.Builder()
                    .maxStale(7, TimeUnit.DAYS)
                    .build()
                request = request.newBuilder()
                    .removeHeader(mHeaderPragma)
                    .removeHeader(mHeaderCacheControl)
                    .cacheControl(cacheControl)
                    .build()
            }
            chain.proceed(request)
        }
    }
}
//String.xml
    <!--Common String-->
    <string name="AppTag">TAG</string>
    <!--Message-->
    <string name="msg_cache">Could not create Cache!</string>
    <!--constant-->
    <string name="cons_http">http-cache</string>
//Constant.kt
open class Constants {
    companion object {
       var authURL: String = "your_url"
        var inventoryURL: String = "your_url"
        var merchantURL: String = "your_url"
        var customerURL: String = "your_url"
        var paymentURL: String = "your_url"
        var notificationURL: String = "your_url"
        var auctionURL: String = "your_url"
        var storeURL: String = "your_url"
        var shippingURL: String = "your_url"
    }
}
//NetworkManager.kt
import android.content.Context
import android.net.ConnectivityManager
class NetworkManager constructor(mContext: Context?) {
    var mContext: Context? = null
    init {
        this.mContext = mContext!!
    }
    /* class for checking Internet connectivity */
    fun checkInternetConnection(): Boolean {
        if (mContext == null) return false
        var con_manager: ConnectivityManager =
            mContext!!.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        return con_manager .activeNetworkInfo != null && con_manager.activeNetworkInfo.isConnected
    }
}
//how to Applied 
 private val apiServicesCache = APIClient().getRetrofitCache(mBaseActivity, 1).create(RetrofitInterface::class.java)!!
/**
     * Get Product Full Detail
     * @param id product id
     */
    fun getProductFullDetail(id: String): LiveData<ProductFullDetail> {
        Log.d("TAG", "Similar Product id=$id")
                 val call = apiServicesCache.getProductFullDetails(id)
        call.enqueue(object : Callback<ProductFullDetail> {
            override fun onResponse(call: Call<ProductFullDetail>, response: Response<ProductFullDetail>) {
                if (response.isSuccessful) {
                    mProductFullDetail.value = response.body()
                }else {
                    mBaseActivity.showApiError(response.code().toString())
                }
            }
            override fun onFailure(call: Call<ProductFullDetail>, t: Throwable) {
                mBaseActivity.showApiError(t.message.toString())
            }
        })
        return this.mProductFullDetail
    }
//RetrofitInterface.kt
interface RetrofitInterface {
 @GET("products/{id}")
    fun getProductFullDetails(@Path("id") id: String): Call<ProductFullDetail>
}
  via Blogger http://bit.ly/2uJuhZQ
0 notes
skptricks · 7 years ago
Text
How to Insert a Screenshot Into a Microsoft Word Document
This post explains how to capture or insert screenshots into  a Microsoft word document easily with help of java code. Also this code you can integrate in selenium framework to capture screen of various pages during test execution.
Screen capturing in word document :
package demoPackage; import java.awt.Rectangle; import java.awt.Robot; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.util.concurrent.TimeUnit; import javax.imageio.ImageIO; import org.apache.poi.util.Units; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFRun; public class TakeScreenshots { public static void main(String[] args) { try { String dirPath = "d:/file/" ; //Create folder/directory if not exist. File file = new File(dirPath); if (!file.exists()) { if (file.mkdir()) { System.out.println("Directory is created!"); } else { System.out.println("Failed to create directory!"); } } XWPFDocument docx = new XWPFDocument(); XWPFRun run = docx.createParagraph().createRun(); FileOutputStream out = new FileOutputStream(dirPath+"doc1.docx"); // Add for loop for example, because here we are capturing 5 screenhots for (int counter = 1; counter <= 5; counter++) { captureScreenShot( run, out, dirPath); TimeUnit.SECONDS.sleep(1); } System.out.println("Write to doc file sucessfully..."); docx.write(out); out.flush(); out.close(); docx.close(); } catch (Exception e) { e.printStackTrace(); } } public static void captureScreenShot( XWPFRun run, FileOutputStream out, String dirPath) throws Exception { String screenshot_name = System.currentTimeMillis() + ".png"; BufferedImage image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize())); File file = new File(dirPath + screenshot_name); ImageIO.write(image, "png", file); InputStream pic = new FileInputStream(dirPath + screenshot_name); run.addBreak(); run.addPicture(pic, XWPFDocument.PICTURE_TYPE_PNG, screenshot_name, Units.toEMU(500), Units.toEMU(350)); pic.close(); file.delete(); } }
This is all about java screenshot capturing solution. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.
via Blogger https://ift.tt/2N9CDVg
0 notes